在opencv中使用findContours处理图像时出现错误

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

我正在尝试用 opencv.Here 处理图像是我的测试代码。

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)

这里是错误

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

我该如何解决这个问题。

adaptiveThreshold 需要一个 CV_8UC1(灰度)图像,所以只需传递 imgray 而不是 im:

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