在使用cv2.drawContours进行轮廓的颜色填充时要注意一点:
(1)颜色填充时:给其传参数的时候,需要搞一个轮廓的list给他,要不会导致颜色填充失败。
(2)画轮廓线时:就没必要搞list了,直接contours[i]就可以。
python代码:
图片:背景为黑色,有很多白色填充的。
下面代码是去除图片中自定义面积小的轮廓, 将大的轮廓填充为白色。
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)
下面代码是只保留最大轮廓,填充为白色。
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 = []
max_area = 0
max_cnt = 0
for i in range(len(contours)):
cnt = contours[i]
area = cv2.contourArea(cnt)
# find max countour
if (area>max_area):
if(max_area!=0):
c_min = []
c_min.append(max_cnt)
cv2.drawContours(img, c_min, -1, (0,0,0), cv2.FILLED)
max_area = area
max_cnt = cnt
else:
c_min = []
c_min.append(cnt)
cv2.drawContours(img, c_min, -1, (0,0,0), cv2.FILLED)
c_max.append(max_cnt)
cv2.drawContours(img, c_max, -1, (255, 255, 255), thickness=-1)
cv2.imwrite("mask.png", img)
cv2.imshow('mask',img)
cv2.waitKey(0)