版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Gpwner/article/details/79866088
在找二值图片的轮廓,给cv2.findContours函数传递二值图片的时候,抛出一下异常:
(_, cnts, _) = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
TypeError: image data type = 0 is not supported
于是将例子简化,得到一下例子,运行正常:
import cv2
if __name__ == '__main__':
img = cv2.imread('/home/xzchuang/下载/book/1692612937.jpg')
imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(imgray, 1, 255, 0)
print(thresh.dtype)
for i in range(thresh.shape[0]):
for j in range(thresh.shape[1]):
if thresh[i][j] != 0 and thresh[i][j] != 255:
print('异常:{}'.format(thresh[i][j]))
im2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img, contours, -1, (0, 0, 255), 3)
cv2.imshow("img", img)
cv2.waitKey(500)
对比原来的图像,所有像素值:255/0
我自己的例子也是255/0
图像的shape也返回的是同样的类型,看看类型?
image.dtype.果然,问题出现在这,精简例子中的dtype是uint8,而我的项目中得到的type是int64,也就是说cv2.findContours函数接受的图片参数(每一个像素值必须是uint8),于是解决办法自然是将int64类型的图片转换为uint8的:image.astype(np.uint8)