From 71e4aa85367ef9af880204f13029211f16ff4f80 Mon Sep 17 00:00:00 2001 From: zhang Date: Sat, 28 Mar 2020 20:32:36 +0800 Subject: =?UTF-8?q?=E6=95=B0=E5=AD=97=E5=9B=BE=E5=83=8F=E5=A4=84=E7=90=86?= =?UTF-8?q?=E8=A1=8C=E4=BA=BA=E6=A3=80=E6=B5=8B=E4=B8=8E=E5=89=8D=E6=99=AF?= =?UTF-8?q?=E8=83=8C=E6=99=AF=E5=88=86=E5=89=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- dip/segmentation/grab_cut.py | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 dip/segmentation/grab_cut.py (limited to 'dip/segmentation/grab_cut.py') diff --git a/dip/segmentation/grab_cut.py b/dip/segmentation/grab_cut.py new file mode 100644 index 0000000..363496b --- /dev/null +++ b/dip/segmentation/grab_cut.py @@ -0,0 +1,41 @@ +import cv2 +import numpy as np + +src = cv2.imread("sample_person.jpg") +src = cv2.resize(src, (0, 0), fx=0.5, fy=0.5) + +# 交互式,返回 (x_min, y_min, w, h) +r = cv2.selectROI('input', src, True) + +# roi区域 +roi = src[int(r[1]):int(r[1] + r[3]), int(r[0]):int(r[0] + r[2])] + +# 原图mask,与原图等大小 +mask = np.zeros(src.shape[:2], dtype=np.uint8) + +# 矩形roi +rect = (int(r[0]), int(r[1]), int(r[2]), int(r[3])) # 包括前景的矩形,格式为(x,y,w,h) + +# bg模型的临时数组 +bgdmodel = np.zeros((1, 65), np.float64) +# fg模型的临时数组 +fgdmodel = np.zeros((1, 65), np.float64) + +cv2.grabCut(src, mask, rect, bgdmodel, fgdmodel, 11, mode=cv2.GC_INIT_WITH_RECT) + +print(np.unique(mask)) +# 提取前景和可能的前景区域 +mask2 = np.where((mask == 1) | (mask == 3), 255, 0).astype('uint8') + +print(mask2.shape) + +# 按位与 src & src == 0,得到的是二进制 +result = cv2.bitwise_and(src, src, mask=mask2) +# cv2.imwrite('result.jpg', result) +# cv2.imwrite('roi.jpg', roi) + +cv2.imshow('mask', mask2) +cv2.imshow('roi', roi) +cv2.imshow("result", result) +cv2.waitKey(0) +cv2.destroyAllWindows() -- cgit v1.2.3