gpt4 book ai didi

Python OpenCV 与 CascadeClassifier 发生错误

转载 作者:行者123 更新时间:2023-11-30 09:14:21 25 4
gpt4 key购买 nike

import cv2
import imageio

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')

def detect(frame):
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for(x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)
gray_face = gray[y:y+h, x:x+w]
color_face = frame[y:y+h, x:x+w]
eyes = eye_cascade.detectMultiScale(gray_face, 1.1, 3)
for (ex, ey, ew, eh) in eyes:
cv2.rectangle(color_face, (ex, ey), (ex+ew, ey+eh), (0, 255, 0), 2)
return frame

reader = imageio.get_reader('1.mp4')
fps = reader.get_meta_data()['fps']
writer = imageio.get_writer('output.mp4', fps=fps)
for i, frame in enumerate(reader):
frame = detect(frame)
writer.append_data(frame)
print(i)
writer.close()

我收到的错误是这样的;

Traceback (most recent call last):
File "C:/Users/Mustafa Koca/PycharmProjects/mustafakoca/face_det.py", line 23, in <module>
frame = detect(frame)
File "C:/Users/Mustafa Koca/PycharmProjects/mustafakoca/face_det.py", line 9, in detect
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
cv2.error: OpenCV(4.1.2) C:\projects\opencv-python\opencv\modules\objdetect\src\cascadedetect.cpp:1689: error: (-215:Assertion failed) !empty() in function 'cv::CascadeClassifier::detectMultiScale'

最佳答案

xml 文件不在当前文件夹中,而是在 cv2 模块的某个文件夹中,您必须使用完整路径来加载它们。

幸运的是,有一个带有文件夹名称的特殊变量 - cv2.data.haarcascades

face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_eye.xml')

确保您可以使用os.path.join()而不是+

face_cascade = cv2.CascadeClassifier(os.path.join(cv2.data.haarcascades, 'haarcascade_frontalface_default.xml'))
eye_cascade = cv2.CascadeClassifier(os.path.join(cv2.data.haarcascades, 'haarcascade_eye.xml'))

如果加载 xml 文件,那么这应该给出 False

print(face_cascade.empty())
print(eye_cascade.empty())

关于Python OpenCV 与 CascadeClassifier 发生错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59166301/

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