diff options
| author | zhang <zch921005@126.com> | 2020-03-28 20:32:36 +0800 |
|---|---|---|
| committer | zhang <zch921005@126.com> | 2020-03-28 20:32:36 +0800 |
| commit | 71e4aa85367ef9af880204f13029211f16ff4f80 (patch) | |
| tree | c2272a20b4144cf5e4828c97092db3ba0213b9af /dip/segmentation/image_fusion.py | |
| parent | a3563e0afb9db883c4a366592ff783a42a3eb78d (diff) | |
数字图像处理行人检测与前景背景分割
Diffstat (limited to 'dip/segmentation/image_fusion.py')
| -rw-r--r-- | dip/segmentation/image_fusion.py | 53 |
1 files changed, 53 insertions, 0 deletions
diff --git a/dip/segmentation/image_fusion.py b/dip/segmentation/image_fusion.py new file mode 100644 index 0000000..4ef0762 --- /dev/null +++ b/dip/segmentation/image_fusion.py @@ -0,0 +1,53 @@ +import cv2 +import numpy as np + +src = cv2.imread("sample_person.jpg") +src = cv2.resize(src, (0, 0), fx=0.5, fy=0.5) +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])] +img = src.copy() +cv2.rectangle(img, (int(r[0]), int(r[1])), (int(r[0]) + int(r[2]), int(r[1]) + int(r[3])), (255, 0, 0), 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) + +background = cv2.imread("sample_giraffe.jpg") + +h, w, ch = src.shape +background = cv2.resize(background, (w, h)) +# cv.imwrite("background.jpg", background) + +# mask = np.zeros(src.shape[:2], dtype=np.uint8) +bgdmodel = np.zeros((1, 65), np.float64) +fgdmodel = np.zeros((1, 65), np.float64) + +cv2.grabCut(src, mask, rect, bgdmodel, fgdmodel, 5, mode=cv2.GC_INIT_WITH_RECT) +mask2 = np.where((mask == 1) | (mask == 3), 255, 0).astype('uint8') + +# 高斯模糊,边缘变得光滑 +se = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)) +cv2.dilate(mask2, se, mask2) +mask2 = cv2.GaussianBlur(mask2, (5, 5), 0) +cv2.imshow('background-mask', mask2) +# cv.imwrite('background-mask.jpg', mask2) + +# 虚化背景 +# background = cv.GaussianBlur(background, (0, 0), 3) +mask2 = mask2 / 255.0 +print('mask2 shape', mask2.shape) +a = mask2[..., None] +print('a shape', a.shape) + +# 融合方法 com = a*fg + (1-a)*bg +result = a * (src.astype(np.float32)) + (1 - a) * (background.astype(np.float32)) +# result = cv2.bitwise_and(background.astype(np.uint8), background.astype(np.uint8), mask=mask2) + +cv2.imshow("result", result.astype(np.uint8)) +cv2.imwrite("result.jpg", result.astype(np.uint8)) + +cv2.waitKey(0) +cv2.destroyAllWindows() |
