0
votes

I'm new in python. I'm using python 3.5, and openCV3. I have the following code which is suppose to capture around 20 frames through the webcam:


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()

However I'm getting this error:

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

error: ......\modules\imgproc\src\color.cpp:7456: error: (-215) scn == 3 || scn == 4 in function cv::ipp_cvtColor

How can I overcome such error please?

1
what is the output of print(cam.isOpened()) ? - I.Newton
I just double check if the cam is working or not. However my above code failedto capture my photo and save it in a dataset folder! - Mary

1 Answers

0
votes

This code worked on my machine and tracks my face. Try the following:

  • make sure the haarcascade xml file is in the same directory as where you run the code. You can also specify the absolute path to the file to be sure.
  • check if the gray image looks like what you expect cv2.imgshow('gray', gray) (and insert a sleep so you can see it). The cam.isOpened() should return True
  • check if its datatype is an uint8 np.ndarray: print(gray.dtype)