2018-03-23 11:12:56 4298浏览
现在的人脸识别技术已经得到了非常广泛的应用,支付领域、身份验证、美颜相机里都有它的应用。用iPhone的同学们应该对下面的功能比较熟悉。
$sudoapt-getinstallbuild-essentialcmake $sudoapt-getinstalllibgtk-3-dev $sudoapt-getinstalllibboost-all-dev
$pipinstallnumpy $pipinstallscipy $pipinstallopencv-python $pipinstalldlib人脸检测基于事先训练好的模型数据,从这里可以下到模型数据,dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2下载到本地路径后解压,记下解压后的文件路径,程序中会用到。
上面下载的模型数据是用来估计人脸上68个特征点(x,y)的坐标位置,这68个坐标点的位置如下图所示:
defrect_to_bb(rect): x=rect.left() y=rect.top() w=rect.right()-x h=rect.bottom()-y return(x,y,w,h)
defshape_to_np(shape,dtype="int"): coords=np.zeros((68,2),dtype=dtype) foriinrange(0,68): coords[i]=(shape.part(i).x,shape.part(i).y) returncoords
defresize(image,width=1200): r=width*1.0/image.shape[1] dim=(width,int(image.shape[0]*r)) resized=cv2.resize(image,dim,interpolation=cv2.INTER_AREA) returnresized
importsys importnumpyasnp importdlib importcv2 iflen(sys.argv)<2: print"Usage:%s<imagefile>"%sys.argv[0] sys.exit(1) image_file=sys.argv[1] detector=dlib.get_frontal_face_detector() predictor=dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
image=cv2.imread(image_file) image=resize(image,width=1200) gray=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) rects=detector(gray,1)
for(i,rect)inenumerate(rects): shape=predictor(gray,rect) shape=shape_to_np(shape) (x,y,w,h)=rect_to_bb(rect) cv2.rectangle(image,(x,y),(x+w,y+h),(0,255,0),2) cv2.putText(image,"Face#{}".format(i+1),(x-10,y-10), cv2.FONT_HERSHEY_SIMPLEX,0.5,(0,255,0),2) for(x,y)inshape: cv2.circle(image,(x,y),2,(0,0,255),-1) cv2.imshow("Output",image) cv2.waitKey(0)
下面是原图
下面是程序识别的结果
可以看到脸部区域被绿色的长方形框起来了,脸上的特征(鼻子,眼睛等)被红色点点标识出来了。最后想要了解更多关于Python发展前景趋势,请关注扣丁学堂python培训官网、微信等平台,扣丁学堂IT职业在线学习教育平台为您提供最新的Python视频教程系统,通过千锋扣丁学堂金牌讲师在线录制的Python视频教程课程,让你快速掌握Python从入门到精通开发实战技能。扣丁学堂Python开发工程师技术交流群:279521237。
【关注微信公众号获取更多学习资料】