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

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

Souvik Ray
1#
Souvik Ray Published in 2017-12-07 14:03:59Z

I am trying detect a face in a gif image but since OpenCV doesn't support gif formats, so I used PIL module to read the gif image and convert it back to a numpy array for OpenCV to use.But doing so I am getting an assertion error.

Here is my code below

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()

This is the error I am encountering

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

The usual suggestion I found in the internet is that the image is not loaded and that's why it throws such error but clearly in my case the image is indeed loaded otherwise my code would throw an exception.Also If I try to run this code

print(img.shape)

I get a value of (243, 320).So where am I going wrong?

Miki
2#
Miki Reply to 2017-12-07 15:06:15Z

I've tried your code with different color gif images and using the face_cascade on img itself seems to work. Try to comment out the grayscale conversion and use

faces = face_cascade.detectMultiScale(img,1.5,3)
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.302018 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO