gpt4 book ai didi

python-3.x - 程序遇到 OpenCV 错误 : Assertion failed (scn == 3 || scn == 4)

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

我正在尝试检测 gif 图像中的人脸,但由于 OpenCV 不支持 gif 格式,所以我使用 PIL 模块读取 gif 图像并将其转换回 numpy 数组供 OpenCV 使用。但这样做我我收到断言错误。

下面是我的代码

import cv2
import numpy as np
from PIL import Image

# get the features and pass it to the Cascade Classifier
face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
# read the image
img = Image.open("mypic.sleepy")
# check if image exists
if img is None:
raise Exception("could not load image !")
# represent the image in matrix format for the OpenCV to work on it
img = np.array(img)
# convert it to gray scale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# detect the objects resembling faces
faces = face_cascade.detectMultiScale(gray,1.5,3) #(image,scale_factor, minm_no_of_neighbours)
for face in faces:
# the detected face is represented in the form of a rectangle
x, y, w, h = face
# draw a rectangle on the face in the image
cv2.rectangle(img, (x,y), (x + w, y + h), (0, 255, 0), 2)
# show the image
cv2.imshow("Detected Faces", img)
# hold the window
cv2.waitKey(0)
# destroy all windows
cv2.destroyAllWindows()

这是我遇到的错误

OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cvtColor, file /home/souvik/opencv-3.3.0/modules/imgproc/src/color.cpp, line 10638

我在互联网上发现的通常建议是图像未加载,这就是它抛出此类错误的原因,但很明显,在我的情况下,图像确实已加载,否则我的代码会抛出异常。此外,如果我尝试运行此代码

print(img.shape)

我得到的值是 (243, 320)。那么我哪里出错了?

最佳答案

我已经用不同颜色的 gif 图像尝试了您的代码,并且在 img 上使用 face_cascade 本身似乎有效。尝试注释掉灰度转换并使用

faces = face_cascade.detectMultiScale(img,1.5,3)

关于python-3.x - 程序遇到 OpenCV 错误 : Assertion failed (scn == 3 || scn == 4),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47696801/

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