gpt4 book ai didi

python - Opencv人脸检测网络摄像头不保存检测到的人脸

转载 作者:行者123 更新时间:2023-12-02 17:58:11 24 4
gpt4 key购买 nike

我使用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

最佳答案

您忘记添加 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()

关于python - Opencv人脸检测网络摄像头不保存检测到的人脸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64238653/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com