【问题标题】:Program encounters OpenCV Error: Assertion failed (scn == 3 || scn == 4)程序遇到 OpenCV 错误:断言失败 (scn == 3 || scn == 4)
【发布时间】:2018-05-21 15:54:53
【问题描述】:

我正在尝试检测 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)的值。那么我哪里出错了?

【问题讨论】:

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

标签: python-3.x opencv python-imaging-library face-detection


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2014-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多