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

2024-04-19 18:43:57 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我正在Windows10笔记本电脑上运行Python3.6.3(Anaconda64位安装)。你知道吗

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

函数存储在face计数器.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.数组格式馈送到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()

函数存储在文件.py:

import cv2

def function(ret, frame):
    output = frame

    return output

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

我非常感谢你的帮助。提前多谢了!你知道吗


Tags: 函数代码importoutput错误cv2framecap
1条回答
网友
1楼 · 发布于 2024-04-19 18:43:57

你需要修正你的简化版本。你知道吗

  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.py、命名为image_processing.py或与python使用的名称不冲突的名称也不是一个好主意。你知道吗

相关问题 更多 >