[英]To get the center mask from an image of masks using Python3 and opencv
檢測物體的輪廓。
遍歷輪廓並找到包圍圖像中心的輪廓。
使用該輪廓,為圖像創建一個蒙版並蒙版該圖像。
import cv2
import numpy as np
def process(img):
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img_canny = cv2.Canny(img_gray, 0, 50)
img_dilate = cv2.dilate(img_canny, None, iterations=1)
img_erode = cv2.erode(img_dilate, None, iterations=1)
return img_erode
def get_masked(img):
h, w, _ = img.shape
center = h // 2, w // 2
contours, _ = cv2.findContours(process(img), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
for cnt in contours:
if cv2.contourArea(cnt) > 100:
if cv2.pointPolygonTest(cnt, center, False) > 0:
mask = np.zeros((h, w), 'uint8')
cv2.drawContours(mask, [cnt], -1, 255, -1)
return cv2.bitwise_and(img, img, mask=mask)
img = cv2.imread("blobs.png")
cv2.imshow("img_processed", get_masked(img))
cv2.waitKey(0)
import cv2
import numpy as np
def process(img):
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img_canny = cv2.Canny(img_gray, 0, 50)
img_dilate = cv2.dilate(img_canny, None, iterations=1)
img_erode = cv2.erode(img_dilate, None, iterations=1)
return img_erode
process
function 處理圖像) ,並且對於輪廓面積大於100
的每個輪廓(以濾除噪聲) ,檢查圖像的中心是否為在輪廓內(通過檢查調用cv2.pointPolygonTest
的結果是否返回正數來完成) ,創建遮罩,遮罩圖像並返回遮罩圖像:def get_masked(img):
h, w, _ = img.shape
center = h // 2, w // 2
contours, _ = cv2.findContours(process(img), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
for cnt in contours:
if cv2.contourArea(cnt) > 100:
if cv2.pointPolygonTest(cnt, center, False) > 0:
mask = np.zeros((h, w), 'uint8')
cv2.drawContours(mask, [cnt], -1, 255, -1)
return cv2.bitwise_and(img, img, mask=mask)
get_masked
function 並顯示圖像:img = cv2.imread("blobs.png")
cv2.imshow("img_processed", get_masked(img))
cv2.waitKey(0)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.