Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
875 views
in Technique[技术] by (71.8m points)

numpy - Python-OpenCV cv2 OpenCV Error: Assertion failed (scn == 3 || scn == 4) in unknown function, file ......modulesimgprocsrccolor.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:UsersPrashantDesktopest.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:Python27libsite-packagesspyderlibwidgetsexternalshellsitecustomize.py", line 540, in runfile
OpenCV Error: Assertion failed (scn == 3 || scn == 4) in unknown function, file ......modulesimgprocsrccolor.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: ......modulesimgprocsrccolor.cpp:3402: error: (-215) scn == 3 || scn == 4
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...