28
votes

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
4

4 Answers

85
votes

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.

1
votes

If you are getting this error on a raspberry PI with PI camera, try running this command first:

sudo modprobe bcm2835-v4l2
1
votes

1st print ret. If it is showing false then your image is not taken properly. If it is showing True Try this command - sudo modprobe bcm2835-v4l2 Or in your /etc/modules file add bcm2835-v4l2 at the bottom.

-2
votes

I had this problem and couldn't find a solution, but on the web, it was working. My solution was almost funny - you can't have two streams. I turned off the web stream and then it was fine!