所以我正在嘗試撰寫一個代碼,當從網路攝像頭檢測到面部時,它會在面部周圍顯示一個綠色方塊。那部分已經完成。我接下來要做的是,當程式不再檢測到面部時,它會中斷回圈并退出程式。我嘗試通過“if”或“else”或在網上找到一些方法,但我哪兒也不去。有什么辦法嗎?這是我的代碼:
import cv2
import os
import time
cascPath = os.path.dirname(
cv2.__file__) "/data/haarcascade_frontalface_alt2.xml"
faceCascade = cv2.CascadeClassifier(cascPath)
video_capture = cv2.VideoCapture(0)
while True:
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(60, 60),
flags=cv2.CASCADE_SCALE_IMAGE)
for (x,y,w,h) in faces:
cv2.rectangle(frame, (x, y), (x w, y h),(0,255,0), 2)
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
video_capture.release()
cv2.destroyAllWindows()
uj5u.com熱心網友回復:
添加這個怎么樣?統計未檢測到人臉的次數;如果超過閾值則中斷:
iter_with_no_faces=0 #put this outside the main loop
### put the follwing after updating `faces`
if len(faces) ==0:
iter_with_no_faces =1
## add break condition as this:
if iter_with_no_faces >100:
break
你可以iter_with_no_faces在faces回圈中:iter_with_no_faces=0
總之,這可能需要稍作修改:
import cv2
import os
import time
cascPath = os.path.dirname(
cv2.__file__) "/data/haarcascade_frontalface_alt2.xml"
faceCascade = cv2.CascadeClassifier(cascPath)
video_capture = cv2.VideoCapture(0)
iter_with_no_faces=0 #put this outside the main loop
while True:
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(60, 60),
flags=cv2.CASCADE_SCALE_IMAGE)
for (x,y,w,h) in faces:
cv2.rectangle(frame, (x, y), (x w, y h),(0,255,0), 2)
if len(faces) ==0:
iter_with_no_faces =1
else:
iter_with_no_faces=0 # I assume you want to continue program when a face detected for a duration. you can omit else statement
if iter_with_no_faces >100: #set this threshold to larger or smaller number
break
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
video_capture.release()
cv2.destroyAllWindows()
uj5u.com熱心網友回復:
import cv2
def main():
cascPath = './haarcascade_frontalface_alt2.xml' # path to the xml file - change to your path
faceCascade = cv2.CascadeClassifier(cascPath)
video_capture = cv2.VideoCapture(0)
for i in range(10 ** 10):
ret, frame = video_capture.read()
if ret:
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(60, 60),
flags=cv2.CASCADE_SCALE_IMAGE)
if len(faces) > 0:
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x w, y h), (0, 255, 0), 2)
cv2.imshow('Video', frame)
k = cv2.waitKey(1)
if k == ord('q'):
break
else:
print('No face detected on iter {}'.format(i))
# add here break or whatever you want to do if no face detected
video_capture.release()
cv2.destroyAllWindows()
return
if __name__ == '__main__':
main()
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/432790.html
下一篇:OpenCV:將向量堆疊到墊子上
