Opencv[cv2.findContours解決image data type = 0 is not supported]

來源:互聯網
上載者:User

在找二值圖片的輪廓,給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)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.