Elivis
Elivis

Reputation: 307

A error occurred when i use findContours to process a image in opencv

I am trying to process a image with opencv.Here is my test code.

import numpy as np
import cv2
im = cv2.imread('keli.jpg')
imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)

thresh = cv2.adaptiveThreshold(im,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY,7,2)

contours,hierarchy = cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
img = cv2.drawContours(im, contours, -1, (0,255,0), 1)

cv2.imwrite("result.jpg",img)

And here is the error

OpenCV Error: Assertion failed (src.type() == CV_8UC1) in adaptiveThreshold, file /build/buildd/opencv-2.4.8+dfsg1/modules/imgproc/src/thresh.cpp, line 796
Traceback (most recent call last):
  File "contour.py", line 6, in <module>
    thresh = cv2.adaptiveThreshold(im,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY,7,2)
cv2.error: /build/buildd/opencv-2.4.8+dfsg1/modules/imgproc/src/thresh.cpp:796: error: (-215) src.type() == CV_8UC1 in function adaptiveThreshold

How can i solve this problem.

Upvotes: 1

Views: 589

Answers (1)

Miki
Miki

Reputation: 41765

adaptiveThreshold needs an CV_8UC1 (grayscale) image, so just pass imgray instead of im:

thresh = cv2.adaptiveThreshold(imgray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 7, 2)

Upvotes: 2

Related Questions