首页 文章

在python中捕获面部框架

提问于
浏览
0

我是python的新手 . 我正在使用python 3.5和openCV3 . 我有以下代码,假设通过网络摄像头捕获大约20帧:


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

但是我收到了这个错误:

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

错误:...... \ modules \ imgproc \ src \ color.cpp:7456:错误:(-215)scn == 3 ||函数cv :: ipp_cvtColor中的scn == 4

我怎么能克服这样的错误呢?

1 回答

  • 0

    这段代码在我的机器上运行并跟踪我的脸 . 请尝试以下方法:

    • 确保haarcascade xml文件与运行代码的目录位于同一目录中 . 您还可以指定文件的绝对路径以确定 .

    • 检查 gray 图像是否与您期望的图像 cv2.imgshow('gray', gray) (并插入睡眠以便您可以看到它) . cam.isOpened()应该返回True

    • 检查其数据类型是否为uint8 np.ndarray: print(gray.dtype)

相关问题