[python] 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.

This question is related to python opencv photo

The answer is


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)

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.


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


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


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 

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


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

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.


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.


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


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.


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.


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.


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.


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.


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

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

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to opencv

Real time face detection OpenCV, Python OpenCV TypeError: Expected cv::UMat for argument 'src' - What is this? OpenCV !_src.empty() in function 'cvtColor' error ConvergenceWarning: Liblinear failed to converge, increase the number of iterations How do I install opencv using pip? Access IP Camera in Python OpenCV ImportError: libSM.so.6: cannot open shared object file: No such file or directory Convert np.array of type float64 to type uint8 scaling values How to import cv2 in python3? cmake error 'the source does not appear to contain CMakeLists.txt'

Examples related to photo

open cv error: (-215) scn == 3 || scn == 4 in function cvtColor Link a photo with the cell in excel How can I link a photo in a Facebook album to a URL Adding images or videos to iPhone Simulator