慕斯709654
您可以使用 Grabcut [1] 算法从边界框中提取片段。Grabcut 尝试将像素聚类为两组,边界框外和边界框内,同时惩罚与具有相似颜色的相邻像素的标签不一致。例如:import cv2 import numpy as npim = cv2.imread('beef.jpg')mask = np.zeros(im.shape[:2], np.uint8)bgd_model = np.zeros((1, 65), np.float64)fgd_model = np.zeros((1, 65), np.float64)rect = (30, 25, 30 + 318, 25 + 350) # (x, y, w, h)cv2.grabCut(im, mask, rect, bgd_model, fgd_model, 10, cv2.GC_INIT_WITH_RECT) mask = np.where((mask == cv2.GC_BGD) | (mask == cv2.GC_PR_BGD), 0, 1).astype(np.uint8)contour, _= cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)cv2.drawContours(im, contour, -1, (0, 255, 0)) cv2.imwrite("output.png", im) [1] Rother、Carsten、Vladimir Kolmogorov 和 Andrew Blake。“GrabCut”交互式前景提取使用迭代图形切割。”ACM Transactions on Graphics (TOG) 23.3 (2004):309-314。