【OpenCV】119 Grabcut图像分割—背景替换

119 Grabcut图像分割—背景替换

代码

import cv2 as cv
import numpy as np

src = cv.imread("../images/master.jpg");
background = cv.imread("../images/river.jpg")
h,w,_ = src.shape
src = cv.resize(src,(int(w * 0.8),int(h * 0.8)))
cv.imshow("input", src)
cv.imshow("background", background)

h, w, ch = src.shape
mask = np.zeros(src.shape[:2], dtype=np.uint8)
rect = (53,12,w-100,h-12)
bgdmodel = np.zeros((1,65),np.float64)
fgdmodel = np.zeros((1,65),np.float64)

cv.grabCut(src,mask,rect,bgdmodel,fgdmodel,5,mode=cv.GC_INIT_WITH_RECT)
mask2 = np.where((mask==1) + (mask==3), 255, 0).astype('uint8')
print(mask2.shape)

# 高斯模糊
se = cv.getStructuringElement(cv.MORPH_RECT, (3, 3))
cv.dilate(mask2, se, mask2)
mask2 = cv.GaussianBlur(mask2, (5, 5), 0)
cv.imshow('background-mask',mask2)

# 虚化背景
background = cv.GaussianBlur(background, (0, 0), 15)

# blend image
result = np.zeros((h, w, ch), dtype=np.uint8)
for row in range(h):
    for col in range(w):
        w1 = mask2[row, col] / 255.0
        b, g, r = src[row, col]
        b1,g1,r1 = background[row, col]
        b = (1.0-w1) * b1 + b * w1
        g = (1.0-w1) * g1 + g * w1
        r = (1.0-w1) * r1 + r * w1
        result[row, col] = (b, g, r)

cv.imshow("result", result)
cv.waitKey(0)
cv.destroyAllWindows()

实验结果

在这里插入图片描述

解释

使用Grabcut实现图像对象提取,通过背景图像替换,实现图像合成,通过对背景图像高斯模糊实现背景虚化效果,完整的步骤如下:

  1. ROI区域选择
  2. Grabcut对象分割
  3. Mask生成
  4. 使用mask,实现背景与前景的高斯权重融合

所有内容均来源于贾志刚老师的知识星球——OpenCV研习社,本文为个人整理学习,已获得贾老师授权,有兴趣、有能力的可以加入贾老师的知识星球进行深入学习。
在这里插入图片描述

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
对于使用OpenCV来进行图像背景替换,一种常见的方法是使用图像分割和蒙版技术。以下是一个基本的步骤: 1. 导入必要的库: ```python import cv2 import numpy as np ``` 2. 加载图像: ```python image = cv2.imread('input_image.jpg') background = cv2.imread('background_image.jpg') ``` 3. 对图像进行分割: 可以使用各种图像分割算法,如GrabCut、人工智能模型等。这里以GrabCut为例: ```python mask = np.zeros(image.shape[:2], np.uint8) bgdModel = np.zeros((1,65),np.float64) fgdModel = np.zeros((1,65),np.float64) rect = (50, 50, image.shape[1]-50, image.shape[0]-50) # 定义前景区域的矩形边界 cv2.grabCut(image, mask, rect, bgdModel, fgdModel, 5, cv2.GC_INIT_WITH_RECT) # 执行GrabCut算法 # 创建一个蒙版,将GrabCut输出的可能前景标记和可能背景标记设置为前景(确定)或背景(确定) mask2 = np.where((mask==2)|(mask==0), 0, 1).astype('uint8') ``` 4. 通过蒙版将前景提取出来: ```python foreground = image * mask2[:,:,np.newaxis] ``` 5. 调整前景和背景的大小: ```python foreground = cv2.resize(foreground, (background.shape[1], background.shape[0])) ``` 6. 替换背景: ```python result = cv2.bitwise_or(background, foreground) ``` 7. 显示结果: ```python cv2.imshow('Result', result) cv2.waitKey(0) cv2.destroyAllWindows() ``` 这只是一个简单的示例,你还可以根据具体需求进行更复杂的图像处理和优化。同样,你可以尝试其他的图像分割算法和技术来实现背景替换

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值