Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python-OpenCV cv2 OpenCV Error: Assertion failed (scn == 3 || scn == 4) in unknown function, file ..\..\..\modules\imgproc\src\color.cpp

I am trying to learn contours in python using cv2.

I tried the following code given in a tutorial guide:

import cv2 import numpy as np from matplotlib import pyplot as plt  im = cv2.imread('C:\Users\Prashant\Desktop\test.jpg') imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY) ret,thresh = cv2.threshold(imgray,127,255,0) image, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) img = cv2.drawContour(im, contours, -1, (0,255,0), 3) cv2.imshow('Image1',img) 

I am getting this error:

File "C:\Python27\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 540, in runfile OpenCV Error: Assertion failed (scn == 3 || scn == 4) in unknown function, file ..\..\..\modules\imgproc\src\color.cpp, line 3402 Traceback (most recent call last):  File "<stdin>", line 1, in <module>    execfile(filename, namespace)  File "C:/Users/Prashant/.spyder2/.temp.py", line 15, in <module>    imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)  cv2.error: ..\..\..\modules\imgproc\src\color.cpp:3402: error: (-215) scn == 3 || scn == 4 
like image 251
Prashant Shrivastava Avatar asked Dec 29 '13 04:12

Prashant Shrivastava


People also ask

How do I fix cv2 error?

importerror no module named cv2 error occurs when cv2 module is not properly installed or its path is not properly set or configured. The straight way fix for this error (no module named cv2) is to reinstall this module (OpenCV-python). In some scenario reinstalling this module automatically remove the older version.

What is Assertion failed in OpenCV?

It means when your program unable to find any face it throws an error because of null value. To avoid this error, you can use if else condition in your python code. If it is not able to detect any face it will pass otherwise it will run your code. Hope this will give you some idea how to avoid this error.

How do I view cv2 images?

To read and display image using OpenCV Python, you could use cv2. imread() for reading image to a variable and cv2. imshow() to display the image in a separate window.


1 Answers

It says your input image should have 3 or 4 channels before applying the function cv2.cvtColor.

so check your image shape before applying the function by print im.shape. if the result is None type (most of the times, this is the problem), your image is not loaded correctly, most probably because your path is not correct.

The point is that your image should have 3 dimensions, rows, columns and depth.

like image 65
Abid Rahman K Avatar answered Sep 30 '22 09:09

Abid Rahman K