python-3.x - 错误:(-215:断言失败)!函数'cv :: CascadeClassifier :: detectMultiScale'中的empty()
问题描述
我正在尝试使用 python 的“Open-CV”进行人脸检测。该程序向我抛出了一个我作为 python 初学者无法理解的错误。程序的错误:
Traceback (most recent call last):
File "c:\Users\(User's name)\Documents\Python\Face-dection\Facedectection.py", line 6, in <module>
gray_img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
cv2.error: OpenCV(4.5.1) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-wvn_it83\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'
编码:
import cv2
face_cascade=cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
img = cv2.imread("photo.jpg")
gray_img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
faces=face_cascade.detectMultiScale(gray_img, scaleFactor=1.05,minNeighbors=5)
for x, y, w, h in faces:
img=cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),3)
resized=cv2.resize(img,(int(img.shape[1]/3)),(int(img.shape[0]/3)))
cv2.imshow("Deteced-face",resized)
cv2.waitKey(0)
cv2.destroyAllWindows()
注意:照片和.xml文件放在同一个文件夹中
解决方案
您需要cv2.data.haarcascades
在引用.xml
文件之前添加。
#[...]
face_cascade=cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml") #Note the change
#[...]
您的代码中还有一个问题,请查看以下代码块:
resized=cv2.resize(img,(int(img.shape[1]/3)),(int(img.shape[0]/3)))
您应该传递一个图像,它是新的宽度和高度(以元组格式)作为参数,但是您将图像以及宽度和高度作为单独的整数而不是元组格式传递。
这应该是这样的:
resized=cv2.resize(img,(int(img.shape[1]/3), int(img.shape[0]/3)))
'''
Notice I have removed an extra bracket after
cv2.resize(img,(int(img.shape[1]/3)) -> cv2.resize(img,(int(img.shape[1]/3)...
and also I have removed an extra bracket before
(int(img.shape[0]/3))) -> int(img.shape[0]/3)))
'''
这应该工作:
import cv2
face_cascade=cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml") #Note the change
img = cv2.imread("photo.jpg")
gray_img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
faces=face_cascade.detectMultiScale(gray_img, scaleFactor=1.05,minNeighbors=5)
for x, y, w, h in faces:
img=cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),3)
resized=cv2.resize(img,(int(img.shape[1]/3), int(img.shape[0]/3)))
cv2.imshow("Deteced-face",resized)
cv2.waitKey(0)
cv2.destroyAllWindows()
推荐阅读
- python - 使用 argparse.ArgumentParser() 构造解析器时出错
- php - 使用 PHP (Laravel) 将动态嵌套 JSON 数据插入 MySQL
- vba - Word中的复制范围避免剪贴板
- python - 从 Django 请求 URL 获取锚标记
- python - 如何获取当前行的行索引
- angular - 无法禁用 VSCode 以在保存时删除结尾空格?
- arrays - switch 语句中的重复案例
- dagster - 当至少一个所需的输入被给出时执行一个实体
- php - 我该如何运行作曲家更新命令
- session - Ext JS 7.3.1 经典错误 - 记录保存时 C 的状态无效