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

PythonOpencvPhoto

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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 - Python

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 - Python

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 - Python

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.

Solution 5 - Python

Only pass name of the image, no need of 0:

img=cv2.imread('sample.jpg')

Solution 6 - Python

I've had this error message show up, for completely unrelated reasons to the flags 0 or 1 mentionned in the other answers. You might be seeing it too because cv2.imread will not error out if the path string you pass it is not an image:

In [1]: import cv2
   ...: img = cv2.imread('asdfasdf')  # This is clearly not an image file
   ...: gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
   ...:

OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cv::cvtColor, file C:\projects\opencv-python\opencv\modules\imgproc\src\color.cpp, line 10638
---------------------------------------------------------------------------
error                                     Traceback (most recent call last)
<ipython-input-4-19408d38116b> in <module>()
      1 import cv2
      2 img = cv2.imread('asdfasdf')  # This is clearly not an image file
----> 3 gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

error: C:\projects\opencv-python\opencv\modules\imgproc\src\color.cpp:10638: error: (-215) scn == 3 || scn == 4 in function cv::cvtColor

So you're seeing a cvtColor failure when it's in fact a silent imread error. Keep that in mind next time you go wasting an hour of your life with that cryptic metaphor.

Solution

You might need to check that your path string represents a valid file before passing it to cv2.imread:

import os


def read_img(path):
    """Given a path to an image file, returns a cv2 array

    str -> np.ndarray"""
    if os.path.isfile(path):
        return cv2.imread(path)
    else:
        raise ValueError('Path provided is not a valid file: {}'.format(path))


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

Written this way, your code will fail gracefully.

Solution 7 - Python

This answer if for the people experiencing the same problem trying to accessing the camera.

import numpy as np
import cv2

cap = cv2.VideoCapture(0)

while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()

    # Our operations on the frame come here
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    # Display the resulting frame
    cv2.imshow('frame',gray)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

Using Linux:

if you are trying to access the camera from your computer most likely there is a permission issue, try running the python script with sudo it should fix it.

sudo python python_script.py

To test if the camera is accessible run the following command.

ffmpeg -f v4l2 -framerate 25 -video_size 640x480 -i /dev/video0 output.mkv 

Solution 8 - Python

This code for those who are experiencing the same problem trying to accessing the camera could be written with a safety check.

if ret is True:
   gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
else:
   continue

OR in case you want to close the camera/ discontinue if there will be some problem with the frame itself

if ret is True:
   gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
else:
   break

For reference https://github.com/HackerShackOfficial/AI-Smart-Mirror/issues/36

Solution 9 - Python

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

The above error is the result of an invalid image name or if the file does not exists in the local directory.

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

Also if you are using the 2nd argument of cv2.imread() as '0', then it is already converted into a grayscaled image.

The difference between converting the image by passing 0 as parameter and applying the following:

img = cv2.cvtCOLOR(img, cv2.COLOR_BGR2GRAY) 

is that, in the case img = cv2.cvtCOLOR(img, cv2.COLOR_BGR2GRAY), the images are 8uC1 and 32sC1 type images.

Solution 10 - Python

Here is what i observed when I used my own image sets in .jpg format. In the sample script available in Opencv doc, note that it has the undistort and crop the image lines as below:

# undistort
dst = cv2.undistort(img, mtx, dist, None, newcameramtx)

# crop the image
x,y,w,h = roi
dst = dst[y:y+h, x:x+w]
cv2.imwrite('calibresult.jpg',dst)

So, when we run the code for the first time, it executes the line cv2.imwrite('calibresult.jpg',dst) saving a image calibresult.jpg in the current directory. So, when I ran the code for the next time, along with my sample image sets that I used for calibrating the camera in jpg format, the code also tried to consider this newly added image calibresult.jpg due to which the error popped out

error: C:\builds\master_PackSlaveAddon-win64-vc12-static\opencv\modules\imgproc\src\color.cpp:7456: error: (-215) scn == 3 || scn == 4 in function cv::ipp_cvtColor

What I did was: I simply deleted that newly generated image after each run or alternatively changed the type of the image to say png or tiff type. That solved the problem. Check if you are inputting and writing calibresult of the same type. If so, just change the type.

Solution 11 - Python

i think it because cv2.imread cannot read .jpg picture, you need to change .jpg to .png.

Solution 12 - Python

On OS X I realised, that while cv2.imread can deal with "filename.jpg" it can not process "file.name.jpg". Being a novice to python, I can't yet propose a solution, but as François Leblanc wrote, it is more of a silent imread error.

So it has a problem with an additional dot in the filename and propabely other signs as well, as with " " (Space) or "%" and so on.

Solution 13 - Python

I also found if your webcam didnt close right or something is using it, then CV2 will give this same error. I had to restart my pc to get it to work again.

Solution 14 - Python

The simplest solution for removing that error was running the command

cap.release()
cv2.closeAllWindows()

That worked for me and also sometimes restarting the kernel was required because of old processes running in the background.

If the image isn't in the working directory then also it wont be working for that try to place the image file in pwd in the same folder as there is code else provide the full path to the image file or folder.

To avoid this problem in future try to code with exceptional handling so that if incorrect termination happens for some random reason the capturing device would get released after the program gets over.

Solution 15 - Python

2015-05-27-191152.jpg << Looking back at your image format, I occasionally confused between .png and .jpg and encountered the same error.

Solution 16 - Python

In my case the error got resolved by migrating to OpenCV 4.0 (or higher).

Solution 17 - Python

Well I am having the same problem, but I am not taking input images instead getting video frames and the above solution did not work for that. The problem is in camera accessing, the camera of your laptop is still in use by your previous code, you need to simply RESTART you KERNEL and it will work.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionarthurcklView Question on Stackoverflow
Solution 1 - PythonAdityaIntwalaView Answer on Stackoverflow
Solution 2 - PythonKalarav ParmarView Answer on Stackoverflow
Solution 3 - PythonGurkamalView Answer on Stackoverflow
Solution 4 - PythonFarooq KhanView Answer on Stackoverflow
Solution 5 - Pythonsupriya junghareView Answer on Stackoverflow
Solution 6 - PythonFrançois LeblancView Answer on Stackoverflow
Solution 7 - Pythonehivan24View Answer on Stackoverflow
Solution 8 - PythonVivek PatwariView Answer on Stackoverflow
Solution 9 - PythonShikhar JohriView Answer on Stackoverflow
Solution 10 - PythonBhanu ChanderView Answer on Stackoverflow
Solution 11 - PythonshenmemeView Answer on Stackoverflow
Solution 12 - PythonFrancisView Answer on Stackoverflow
Solution 13 - PythonMNMView Answer on Stackoverflow
Solution 14 - PythonVinay VermaView Answer on Stackoverflow
Solution 15 - PythonHong Son NguyenView Answer on Stackoverflow
Solution 16 - Pythonsunil manikaniView Answer on Stackoverflow
Solution 17 - PythonQbertView Answer on Stackoverflow