opencv python 中使用 cv2.drawContours填充輪廓顏色失敗的解決方法


傳遞給繪圖函數的一定要是一個 list

import cv2

imgfile = "IMG_3200.png"
img = cv2.imread(imgfile)
h, w, _ = img.shape

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)

# Find Contour
_, contours, hierarchy = cv2.findContours( thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)

# 需要搞一個list給cv2.drawContours()才行!!!!!
c_max = []
for i in range(len(contours)):
    cnt = contours[i]
    area = cv2.contourArea(cnt)

    # 處理掉小的輪廓區域,這個區域的大小自己定義。
    if(area < (h/10*w/10)):
        c_min = []
        c_min.append(cnt)
        # thickness不為-1時,表示畫輪廓線,thickness的值表示線的寬度。
        cv2.drawContours(img, c_min, -1, (0,0,0), thickness=-1)
        continue
    #
    c_max.append(cnt)
    
cv2.drawContours(img, c_max, -1, (255, 255, 255), thickness=-1)

cv2.imwrite("mask.png", img)
cv2.imshow('mask',img)
cv2.waitKey(0)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM