gpt4 book ai didi

python - 在从另一个 .py 文件调用的函数中使用 cv2.detectMultiScale() 时出错

转载 作者:太空宇宙 更新时间:2023-11-03 21:41:25 24 4
gpt4 key购买 nike

这是我在这里的第一个问题,所以我希望我以正确的方式提问。

我在装有 Windows 10 的笔记本电脑上运行 Python 3.6.3(Anaconda 64 位安装)。

我有一个主要例程,其中包括通过 cv2.VideoCapture() 捕获视频。另一个文件存储了执行人脸检测的函数。当我从主程序调用该函数时,我收到以下错误消息:错误:函数 cv::CascadeClassifier::detectMultiScale 中的 (-215) !empty()

这是代码的简化版本:

主程序:

from facecounter import facecounter
import cv2

cap = cv2.VideoCapture(0)

x = 0
while x < 20:
ret, frame = cap.read()
print(type(frame))
output = facecounter(frame, ret)
cv2.imshow("output", output)
cv2.waitKey()
x += 1

cv2.destroyAllWindows()
cap.release()

存储在 facecounter.py 中的函数:

def facecounter(frame, ret):

import cv2

face_classifier = cv2.CascadeClassifier('cascades/haarcascade_frontalface_default.xml
if ret is True:
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_classifier.detectMultiScale(gray, 1.3, 5)
number_faces = len(faces)

return number_faces

我已经搜索了这个错误,据我所知,这是由于缺少 numpy.array 格式的适当图像提供给 cv2.detectMultiScale()。所以我试图进一步简化代码以隔离错误:

主例程:

from file import function

import cv2

cap = cv2.VideoCapture(0)

x = 0
while x<300:
ret, frame = cap.read()
output = file(ret, frame)
cv2.imshow("window", output)
print(output)

cv2.destroyAllWindows()
cap.release()

file.py 中存储的函数:

import cv2

def function(ret, frame):
output = frame

return output

当我运行这个简化版本的代码时,没有出现任何错误,但是,尽管每次迭代我都打印出正确的数组,但使用 cv2.imshow() 创建的窗口显示灰色图像。

非常感谢您的帮助。非常感谢!

最佳答案

您需要修复您的简化版本。

  1. 您的函数的名称是function 而不是file
  2. 您需要调用cv2.waitKey(1)
  3. 您没有递增 x

这是固定代码

from file import function

import cv2

cap = cv2.VideoCapture(0)

x = 0
while x<300:
ret, frame = cap.read()
output = function(ret, frame)
cv2.imshow("window", output)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
print(output)
x += 1

cv2.destroyAllWindows()
cap.release()

此外,将您的 Python 文件命名为 file.pyimage_processing.py 或其他与 Python 使用的名称不冲突的名称也不是一个好主意。

关于python - 在从另一个 .py 文件调用的函数中使用 cv2.detectMultiScale() 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51086577/

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