在黑色背景下,將照片內封閉空心圖案的空心區域染色
import cv2
import numpy as np
img = cv2.imread('E:\Python-workspace\OpenCV\OpenCV/beyond.png',1)#第一個參數為選擇照片的路徑,注意照片路徑最后一個為正斜杠其他都為反斜杠;第二個參數,其中1表示所選照片為彩色照片,0表示灰度照片
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_,th = cv2.threshold(img_gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)# 尋找輪廓,使用cv2.RETR_CCOMP尋找內外輪廓
image, contours, hierarch = cv2.findContours(th, cv2.RETR_CCOMP, 2)
# 找到內層輪廓并填充hierarchy = np.squeeze(hierarch)#使用np.squeeze壓縮hierarch的成為一維數據for i in range(len(contours)):# 存在父輪廓,說明是里層if (hierarchy[i][3] != -1):cv2.drawContours(img, contours, i, (255, 255, 0), -1)#這里的(255,255,0)代表cyan,也可自定義
cv2.imwrite('E:\Python-workspace\OpenCV\OpenCV/yanyu.jpg', img)
效果如下:
運行前:
運行后: