这是我在OpenCV 3.1中检测面部和眼睛的第一次尝试。这是我的代码:
import cv2 as cv
import numpy as np
face_cascade = cv.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv.CascadeClassifier('haarcascade_eye.xml')
cam = cv.VideoCapture(0)
while True:
tf, img = cam.read()
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x, y, w, h) in faces:
img = cv.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
roi_gray = gray[y:y + h, x:x + w]
roi_color = img[y:y + h, x:x + w]
eyes = eye_cascade.detectMultiScalenter code heree(roi_gray)
for (ex, ey, ew, eh) in eyes:
cv.rectangle(roi_color, (ex, ey), (ex + ew, ey + eh), (0, 255, 0), 2)
print(tf)
cv.imshow('my cam', img)
key = cv.waitKey(1)
if key == 27:
break
cam.release()
cv.destroyAllWindows()
我得到了这个错误:
OpenCV Error: Assertion failed (!empty()) in cv::CascadeClassifier::detectMultiScale, file D:\Build\OpenCV\opencv-3.1.0\modules\objdetect\src\cascadedetect.cpp, line 1639
Traceback (most recent call last):
File "C:/Users/hedon/PycharmProjects/deneme_1.1/ilk.py", line 13, in <module>
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
cv2.error: D:\Build\OpenCV\opencv-3.1.0\modules\objdetect\src\cascadedetect.cpp:1639: error: (-215) !empty() in function cv::CascadeClassifier::detectMultiScale
谁能告诉我我的错误在哪里?我也尝试过:
建议使用
gray = cv.cvtColor(img, cv.COLOR_BAYER_GR2GRAY)
。同样的错误:OpenCV Error: Assertion failed (scn == 1 && dcn == 1) in cv::demosaicing, file D:\Build\OpenCV\opencv-3.1.0\modules\imgproc\src\demosaicing.cpp, line 1630
Traceback (most recent call last):
File "C:/Users/hedon/PycharmProjects/deneme_1.1/ilk.py", line 11, in <module>
gray = cv.cvtColor(img, cv.COLOR_BAYER_BG2GRAY)
cv2.error: D:\Build\OpenCV\opencv-3.1.0\modules\imgproc\src\demosaicing.cpp:1630: error: (-215) scn == 1 && dcn == 1 in function cv::demosaicing
最佳答案
告诉您分类器为空,因为您没有正确加载xml文件。
使用xml文件的完整路径以确保正确加载它们。
关于python - cv.cvtColor(img,cv.COLOR_BGR2GRAY)不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39233231/