我正在嘗試減去影像的背景以創建輪廓影像以進行進一步處理。我的影像資料集如下圖所示:

這是我到目前為止所做的:
import cv2
import numpy as np
frame = cv2.imread("test.png")
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
lower_blue = np.array([0, 0, 120])
upper_blue = np.array([180, 38, 255])
mask = cv2.inRange(hsv, lower_blue, upper_blue)
result = cv2.bitwise_and(frame, frame, mask=mask)
b, g, r = cv2.split(result)
filter = g.copy()
ret,mask = cv2.threshold(filter,10,255, 1)
frame[ mask == 0] = 255
cv2.imwrite("123.png", mask)
我得到的結果是:

現在我試圖找到并應用輪廓,但它不起作用
contours_mask, hierachy = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
for contour in range(len(contours_mask)):
# create mask
if contour != 1:
cv2.fillConvexPoly(mask_b, contours_mask[contour], (0, 0, 0))
有沒有辦法去除噪音并得到像這樣的影像?

uj5u.com熱心網友回復:
在這種情況下,要獲得人物的近似輪廓,可以使用 OSTU 的方法。
import cv2
import numpy as np
# load image, convert to grayscale
frame = cv2.imread("test.png")
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# binarize image using OSTU's method
*_, mask = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV cv2.THRESH_OTSU)

輸出掩碼非常接近實際結果,但是,如果您想細化掩碼,我建議使用cv2.grabCut函式來提取前景和背景段。
# get the bounding box of the silhouette
contours, *_ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
c = max(contours, key=cv2.contourArea)
rect = cv2.boundingRect(c)
# initialize grabCut's parameters
mask_refined = np.empty_like(mask)
fgd_model = np.zeros((1, 65))
bgd_model = np.zeros((1, 65))
iter_count = 10
mode = cv2.GC_INIT_WITH_RECT
# segment image
mask_refined, bgd_model, fgd_model = cv2.grabCut(frame, mask_refined, rect, bgd_model, fgd_model, iter_count, mode)
# select foreground and background
output = np.where((mask_refined == cv2.GC_BGD) | (mask_refined == cv2.GC_PR_BGD), 0, 255).astype(np.uint8)

轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/314779.html
