Souvik Ray
Souvik Ray

Reputation: 3028

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

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?

Upvotes: 1

Views: 422

Answers (1)

Tiphel
Tiphel

Reputation: 323

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)

Upvotes: 1

Related Questions