OpenCV人脸检测网络摄像头未保存检测到的人脸

时间:2020-10-07 06:48:18

标签: python opencv face-detection

我正在使用opencv来检测网络摄像头中的面部,并且每当检测到面部时,我都希望裁剪面部的ROI,并将其图像本地保存在系统中。但是,当我运行代码时,它什么也不做。 我的网络摄像头在opencv(我已经测试过)中工作。但是由于未知原因,此特定代码无法正常工作。

import os
import cv2

ctr=0
# import face detection cascade
face_cascade = cv2.CascadeClassifier('/home/opi/opencv-3.3.0/data/haarcascades/haarcascade_frontalface_default.xml')
# create capture object
cap = cv2.VideoCapture(0)


while(True):
    # capture frame-by-frame
    ret, img = cap.read()
    # convert image to grayscale
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(img, 1.3, 5)
    # for each face draw a rectangle around and copy the face

    for (x,y,w,h) in faces:
        cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
        roi_color = img[y:y+h, x:x+w]
        roi_gray = gray[y:y+h, x:x+w]
        #SAVE THE DETECTED FACES LOCALLY
        roi_gray=cv2.resize(roi_gray,(100,100))
        cv2.imwrite('faces'+'/'+str(ctr)+'.jpg',roi_gray)
        ctr+=1
    # display the resulting frame
    cv2.imshow('frame',img)


# when everything done, release the capture
cap.release()
cv2.destroyAllWindows()

当我按Ctrl + C杀死代码时,我看到的这个错误也没有多大意义:-

opi@admin:~$ python input.py
^CTraceback (most recent call last):
  File "input.py", line 18, in <module>
    faces = face_cascade.detectMultiScale(img, 1.3, 5)
KeyboardInterrupt

1 个答案:

答案 0 :(得分:0)

您已经忘记添加cv2.waitKey(1),这就是为什么您的代码在无限循环(while True: ...)中崩溃的原因。我们也可以说没有时间显示(刷新)帧...

添加以下代码块:

# display the resulting frame
cv2.imshow('frame',img)

key = cv2.waitKey(1)
if key == 32: # if the space key is pressed
    break

最终代码:

import os
import cv2

ctr=0
# import face detection cascade
face_cascade = cv2.CascadeClassifier('/home/opi/opencv-3.3.0/data/haarcascades/haarcascade_frontalface_default.xml')
# create capture object
cap = cv2.VideoCapture(0)


while True:
    # capture frame-by-frame
    ret, img = cap.read()
    # convert image to grayscale
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(img, 1.3, 5)
    # for each face draw a rectangle around and copy the face

    for (x,y,w,h) in faces:
        cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
        roi_color = img[y:y+h, x:x+w]
        roi_gray = gray[y:y+h, x:x+w]
        #SAVE THE DETECTED FACES LOCALLY
        roi_gray=cv2.resize(roi_gray,(100,100))
        cv2.imwrite('faces'+'/'+str(ctr)+'.jpg',roi_gray)
        ctr+=1
    # display the resulting frame
    cv2.imshow('frame',img)

    key = cv2.waitKey(1)
    if key == 32: # if space key is pressed
        break


# when everything done, release the capture
cap.release()
cv2.destroyAllWindows()
相关问题