Program encounters OpenCV Error: Assertion failed (scn == 3 || scn == 4)

Program encounters OpenCV Error: Assertion failed (scn == 3 || scn == 4)

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

下面是我的代码

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

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

print(img.shape)

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

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

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