先上代码:
import cv2
import time
cap = cv2.VideoCapture(0)
cv2.namedWindow('v')
face_cascade = cv2.CascadeClassifier(r'D:\asoftware\anaconda\Lib\site-packages\cv2\data\haarcascade_frontalface_default.xml')
while True:
ret, frame = cap.read()
grey = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(grey, 1.3, 5)
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2)
cv2.imshow('人脸识别', frame)
flag = cv2.waitKey(1)
if flag == 27:
break
cv2.destroyAllWindows()
import cv2
import time
cap = cv2.VideoCapture(0)
cv2.namedWindow('v')
face_cascade = cv2.CascadeClassifier(r'D:\asoftware\anaconda\Lib\site-packages\cv2\data\haarcascade_frontalface_default.xml')
while True:
ret, frame = cap.read()
grey = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(grey, 1.3, 5)
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2)
cv2.imshow('人脸识别', frame)
flag = cv2.waitKey(1)
if flag == 27:
break
cv2.destroyAllWindows()
注:代码转自
https://blog.csdn.net/weixin_43881394/article/details/107955737?utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-2.no_search_link&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-2.no_search_link
原文已经非常详细了,没有太大的问题,但我在操作的时候总会报错
error Traceback (most recent call last)
<ipython-input-1-139199a737a2> in <module>()
10 ret, frame = cap.read()
11 grey = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
---> 12 faces = face_cascade.detectMultiScale(grey, 1.3, 5)
13
14 for (x, y, w, h) in faces:
error: OpenCV(3.4.1) C:\projects\opencv-python\opencv\modules\objdetect\src\cascadedetect.cpp:1698: error: (-215) !empty() in function cv::CascadeClassifier::detectMultiScale
最后发现把代码(这里的xml文件的目录地址是我自己电脑的)
'D:\asoftware\anaconda\Lib\site-packages\cv2\data\haarcascade_frontalface_default.xml'
改为
r'D:\asoftware\anaconda\Lib\site-packages\cv2\data\haarcascade_frontalface_default.xml'
即在单引号前加一个r就行了
原因: 最后发现,是因为目录中有以a开头的文件夹,\a被识别为转义字符。
解决方法: 加r保持字符串原始值,不对其中的符号进行转义。
|