1. 程式人生 > 其它 >opencv python 中使用 cv2.drawContours填充輪廓顏色失敗的解決方法

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)