python中的OpenCV findContours
我正在openCV 3.0上使用python。为了找到最大的白像素区域,首先将灰度图像阈值化为二值图像python中的OpenCV findContours,python,opencv3.0,Python,Opencv3.0,我正在openCV 3.0上使用python。为了找到最大的白像素区域,首先将灰度图像阈值化为二值图像 import cv2 import numpy as np img = cv2.imread('graimage.png') img = cv2.resize(img,(400,500)) gray = img.copy() (thresh, im_bw) = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY ) derp,contours
import cv2
import numpy as np
img = cv2.imread('graimage.png')
img = cv2.resize(img,(400,500))
gray = img.copy()
(thresh, im_bw) = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY )
derp,contours,hierarchy = cv2.findContours(im_bw,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
cnts = max(cnts, key=cv2.contourArea)
但它显示了如下错误
cv2.error:../opencv/modules/imgproc/src/contours.cpp:198:error:(-210)[开始]FindContentours在模式下仅支持CV_8UC1图像!=CV_RETR_FLOODFILL仅在函数cvStartFindContours中支持CV_32SC1图像
这似乎在评论中得到了回答,但只是将问题标记为已回答: CV_8UC1表示8位像素,无符号,只有一个通道,因此为灰度。看起来您正在使用3个颜色通道或CV_8UC3阅读它。您可以通过打印
img.dtype
和img.shape
来检查图像类型。数据类型应为uint8,形状应为(#,#),表示二维。我猜你会看到图形按原样为图像打印(#,#,3),表示三个颜色通道
正如@user3515225所说,您可以通过使用
cv2.imread('img.png',cv2.imread\u grayscale)
以灰度形式读取图像来解决这个问题。不过,这假设您在其他任何地方都不使用颜色。如果您需要图像的单独灰度副本,请将gray=img.copy()
替换为gray=cv2.cvtColor(img,cv2.COLOR\u RGB2GRAY)
。您的图像是8位无符号字符吗?或者您可以编写“img=imread('grainimage.png',0')以转换为灰度。