open cv error: (-215) scn == 3 || scn == 4 in function cvtColor

I'm currently in Ubuntu 14.04, using python 2.7 and cv2.

When I run this code:

import numpy as np
import cv2

img = cv2.imread('2015-05-27-191152.jpg',0)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

it returns:

 File "face_detection.py", line 11, in <module>
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.error: /home/arthurckl/Desktop/opencv-3.0.0-rc1/modules/imgproc/src/color.cpp:7564: error: (-215) scn == 3 || scn == 4 in function cvtColor

I already searched here and one answer said that I could be loading my photo the wrong way, because it should have 3 dimensions: rows, columns and depth.

When I print the img.shape it returns only two numbers, so I must be doing it wrong. But I don't know the right way to load my photo.


Solution 1:

Give the full path of image with forward slash. It solved the error for me.

E.g.

import numpy as np
import cv2

img = cv2.imread('C:/Python34/images/2015-05-27-191152.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

Also, if you give 0 in second parameter while loading image using cv2.imread than no need to convert image using cvtColor, it is already loaded as grayscale image eg.

import numpy as np
import cv2

gray = cv2.imread('C:/Python34/images/2015-05-27-191152.jpg',0)

Solution 2:

Please Set As Below

img = cv2.imread('2015-05-27-191152.jpg',1)     // Change Flag As 1 For Color Image
                                                //or O for Gray Image So It image is 
                                                //already gray

Solution 3:

img = cv2.imread('2015-05-27-191152.jpg',0)

The above line of code reads your image in grayscale color model, because of the 0 appended at the end. And if you again try to convert an already gray image to gray image it will show that error.

So either use above style or try undermentioned code:

img = cv2.imread('2015-05-27-191152.jpg')
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

Solution 4:

First thing you should check is that whether the image exists in the root directory or not. This is mostly due to image with height = 0. Which means that cv2.imread(imageName) is not reading the image.