Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/opencv/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 程序遇到OpenCV错误:断言失败(scn==3 | | scn==4)_Python 3.x_Opencv_Python Imaging Library_Face Detection - Fatal编程技术网

Python 3.x 程序遇到OpenCV错误:断言失败(scn==3 | | scn==4)

Python 3.x 程序遇到OpenCV错误:断言失败(scn==3 | | scn==4),python-3.x,opencv,python-imaging-library,face-detection,Python 3.x,Opencv,Python Imaging Library,Face Detection,我尝试在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("haarcasca

我尝试在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)

我得到的值是
(243320)
。那么我错在哪里呢?

我用不同颜色的gif图像尝试了你的代码,并且使用
img
上的face_cascade本身似乎可以工作。尝试注释掉灰度转换并使用

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

加载的图像已为灰度(单通道)。不需要转换到grayscale@Miki你是对的,我用彩色gif图像替换了它,但问题仍然存在!是否有理由使用PIL加载图像,然后将其传递给OpenCV?基本上,openCV告诉您,它没有3或4个通道将其从BGR转换为灰色。顺便说一句,如果是彩色图像,PIL是RGB而不是BGR。OpenCV中的彩色图像具有形状(高度、宽度、通道),因此在您的情况下,它应该是(243320,3)@SouvikRay,如果它是灰色的,则可能只有一个通道。据我所知,PIL实际上检查它是1个通道还是3个通道。默认情况下,OpenCV始终加载3个通道。蒂菲尔给出的答案可能有用。您可以尝试使用该形状,如果它是3个通道,那么您可以转换,否则您可以继续而不转换为灰度。如果您知道您的图像始终是灰度的,为什么要将它们从bgr转换为灰度?