moli
moli

Reputation: 19

Why i have this issue with cv2.findContours function?

Traceback (most recent call last): File "C:/Users/michail.gakas/Desktop/python scripts/counters.1py.py", line 10, in imgray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) 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

My code:

import numpy as np
import cv2

img = cv2.imread('star.jpg',0)

imgray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(imgray,127,255,0)
im2, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
#cv2.waitKey(0)
#cv2.destroyAllWindows()

I am using python 2.7 CV3 but i had CV2 installed before

Upvotes: 0

Views: 785

Answers (1)

ljetibo
ljetibo

Reputation: 3094

I don't have OpenCV with me right now but from what I see you did

img = cv2.imread("star.jpg", 0)

but what you probably wanted to do is open it in color as:

img = cv2.imread("star.jpg", 1)

or open it "unchanged" as:

img = cv2.imread("star.jpg", -1)

What you did is you opened an image in grayscale mode and then tried to convert it to grayscale. That error actually states that assert didn't find an image with 3 or 4 channels and BGR2GRAYSCALE goes from a color jpg image (3 channels) or a color png image (4 channels, 1 for alpha sometimes) to a 1 channel grayscale image. Alpha channel is discarded in this function. Pls make your life easier and use the official flags cv2 offers for easier code readability.

cv2.IMREAD_UNCHANGED (<0) loads the image as is (including the alpha channel if present)
cv2.IMREAD_GRAYSCALE ( 0) loads the image as an intensity one
cv2.IMREAD_COLOR (>0) loads the image in the RGB format

Upvotes: 1

Related Questions