2017-09-16 30 views
0

我是python中的新手。我使用python 3.5和openCV3。我有以下代碼是假設通過網絡攝像頭捕獲約20幀:在python中捕獲臉部框架


import cv2 
import time 
cam = cv2.VideoCapture(0) 
print(cam.isOpened()) 
detector=cv2.CascadeClassifier('haarcascade_frontalface_default.xml') 

Id=1 
sampleNum=0 

time.sleep(5) 
while(True): 
    ret, img = cam.read() 
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 
    faces = detector.detectMultiScale(gray, 1.3, 5) 

    for (x,y,w,h) in faces: 
     cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

     #incrementing sample number 
     sampleNum=sampleNum+1 
     #saving the captured face in the dataset folder 
     cv2.imwrite("dataSet/User."+Id +'.'+ str(sampleNum) + ".jpg", gray[y:y+h,x:x+w]) 

     cv2.imshow('frame',img) 
    #wait for 100 miliseconds 
    if cv2.waitKey(100) & 0xFF == ord('q'): 
     break 
    # break if the sample number is morethan 20 
    elif sampleNum>20: 
     break 
cam.release() 
cv2.destroyAllWindows() 

但是我發現了這樣的錯誤:

灰色= cv2.cvtColor(IMG, cv2.COLOR_BGR2GRAY)

錯誤:...... \ modules \ imgproc \ src \ color.cpp:7456:error:(-215)scn == 3 || scn == 4功能cv :: ipp_cvtColor

請問我該如何克服這種錯誤?

+0

什麼是打印的輸出(cam.isOpened())? –

+0

我只是仔細檢查凸輪是否工作。但是,我上面的代碼未能捕捉到我的照片並將其保存在數據集文件夾中! – Mary

回答

0

此代碼在我的機器上工作並跟蹤我的臉部。請嘗試以下操作:

  • 確保haarcascade xml文件與您運行代碼的位置相同。您也可以指定文件的絕對路徑。
  • 檢查gray圖片是否看起來像您期望的cv2.imgshow('gray', gray)(並插入睡眠以便您可以看到它)。該cam.isOpened()應返回true
  • 檢查,如果其數據類型是UINT8 np.ndarray:print(gray.dtype)
+0

我可以現在使用什麼版本的python? 3.5?或更少? – Mary

+0

另外,你的意思是說我必須將這行從cv2.imshow('frame',img)改爲cv2.imshow('gray',grey)!!!另外,我試圖指定它不起作用的xml的絕對路徑! – Mary

+0

文件 「C:/用戶/瑪麗/桌面/項目/面部個記錄/ face_datasets.py」,第13行,在 灰色= cv2.cvtColor(IMG,cv2.COLOR_BGR2GRAY) 錯誤:.. \ .. \ .. \ modules \ imgproc \ src \ color.cpp:7456:error:(-215)scn == 3 || scn == 4在函數cv :: ipp_cvtColor中 – Mary