From 942e749abfd18dfd9ad9596e751bbe9f6e2f963a Mon Sep 17 00:00:00 2001 From: pyhqos7bg Date: Thu, 30 May 2024 14:49:37 +0800 Subject: [PATCH] ADD file via upload --- 前景目标提取.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 前景目标提取.py diff --git a/前景目标提取.py b/前景目标提取.py new file mode 100644 index 0000000..4449e6c --- /dev/null +++ b/前景目标提取.py @@ -0,0 +1,30 @@ +import cv2 +import numpy as np + +src = cv2.imread("demo2.jpg") +r = cv2.selectROI('input', src, False) # 返回 (x_min, y_min, w, h) +# 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) + +bgdmodel = np.zeros((1,65),np.float64) # bg模型的临时数组 +fgdmodel = np.zeros((1,65),np.float64) # fg模型的临时数组 + +cv2.grabCut(src,mask,rect,bgdmodel,fgdmodel, 11, mode=cv2.GC_INIT_WITH_RECT) + +# 提取前景和可能的前景区域 +mask2 = np.where((mask==1) + (mask==3), 255, 0).astype('uint8') + +print(mask2.shape) + +result = cv2.bitwise_and(src,src,mask=mask2) +cv2.imwrite('result.jpg', result) +cv2.imwrite('roi.jpg', roi) + +cv2.imshow('roi', roi) +cv2.imshow("result", result) +cv2.waitKey(0) +cv2.destroyAllWindows()