在找二值圖片的輪廓,給cv2.findContours函數傳遞二值圖片的時候,拋出一下異常:
(_, cnts, _) = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)TypeError: image data type = 0 is not supported
於是將例子簡化,得到一下例子,運行正常:
import cv2if __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)