arthurckl
arthurckl

Reputation: 5431

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.

Upvotes: 96

Views: 279844

Answers (17)

MNM
MNM

Reputation: 2743

I also found if your webcam didn't 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.

Upvotes: 0

S_Anuj
S_Anuj

Reputation: 373

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.

Upvotes: 0

sunil manikani
sunil manikani

Reputation: 320

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

Upvotes: 0

shenmeme
shenmeme

Reputation: 21

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

Upvotes: 0

Vivek Patwari
Vivek Patwari

Reputation: 29

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

Upvotes: 1

Hong Son Nguyen
Hong Son Nguyen

Reputation: 21

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

Upvotes: 0

Vinay Verma
Vinay Verma

Reputation: 1098

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.

Upvotes: 0

Francis
Francis

Reputation: 45

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.

Upvotes: 0

Shikhar Johri
Shikhar Johri

Reputation: 41

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.

Upvotes: 1

ehivan24
ehivan24

Reputation: 31

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 

Upvotes: 1

Fran&#231;ois Leblanc
Fran&#231;ois Leblanc

Reputation: 1750

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.

Upvotes: 2

AdityaIntwala
AdityaIntwala

Reputation: 2576

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)

Upvotes: 109

Gurkamal
Gurkamal

Reputation: 71

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)

Upvotes: 7

Farooq Khan
Farooq Khan

Reputation: 622

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.

Upvotes: 5

supriya junghare
supriya junghare

Reputation: 41

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

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

Upvotes: 4

Bhanu Chander
Bhanu Chander

Reputation: 490

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.

Upvotes: 0

Kalarav Parmar
Kalarav Parmar

Reputation: 304

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

Upvotes: 18

Related Questions