1.pip安裝包
pip install opencv-python opencv-contrib-python -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com
2.之前只是安裝這兩個包就能夠實現,但是在更新MacOS後,發現報錯了,錯誤日誌如下:
qt.qpa.plugin: Could not find the Qt platform plugin "cocoa" in ""
This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem.
經過查閱文檔發現是opencv-python版本的問題,執行下面的命令後,程序又恢復正常:
pip install opencv-python-headless -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com
人臉定位識別具體代碼如下:
import cv2
import dlib
import numpy as np
import os
def catchPICFFromVideo(window_name,camera_idx,catch_pic_num,path_name):
cv2.namedWindow(window_name)
cap=cv2.VideoCapture(camera_idx)
calssfier=cv2.CascadeClassifier('/Users/icsoc/.virtualenvs/scientific_calculation/lib/python3.7/site-packages/cv2/data/haarcascade_frontalface_alt.xml')
color=(0,255,0)
num=0
while cap.isOpened():
ok,frame=cap.read()
if not ok:
break
grey=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
faceRects=calssfier.detectMultiScale(grey,scaleFactor=1.2,minNeighbors=3,minSize=(32,32))
if len(faceRects)>0:
for faceRect in faceRects:
x,y,w,h=faceRect
image_name='%s%d.jpg'%(path_name,num)
image=frame[y-10:y+h+10,x-10:x+w+10]
cv2.imwrite(image_name,image,[int(cv2.IMWRITE_PNG_COMPRESSION),9])
num+=1
if num>(catch_pic_num):
break
cv2.rectangle(frame,(x-10,y-10),(x+w+10,y+h+10),color,2)
font=cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(frame,'num:%d/100'%(num),(x+20,y+30),font,1,(255,0,255),4)
if num>(catch_pic_num):break
cv2.imshow(window_name,frame)
c=cv2.waitKey(10)
if c&0xFF==ord('q'):
break
cap.release()
cv2.destroyAllWindows()
catchPICFFromVideo("get face",0,100,".")
注意這裏的路徑:
calssfier=cv2.CascadeClassifier('/Users/icsoc/.virtualenvs/scientific_calculation/lib/python3.7/site-packages/cv2/data/haarcascade_frontalface_alt.xml')
需要改成自己opencv的python包安裝目錄即可