OpenCV基础_007_ 两个背景虚化的例子

背景虚化案例1

import numpy as np
import cv2

camera = cv2.VideoCapture(0)


while (True):
    ret, frame = camera.read()
    if not ret:
        continue

    # 阈值分割
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    ret, thresh = cv2.threshold(gray, 0, 255,cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)

    # 开运算
    kernel = np.ones((3,3), np.uint8)
    opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel,iterations=2)

    # 膨胀获取背景区域
    sure_bg = cv2.dilate(opening, kernel, iterations=3)

    # 获取前景区域
    dist_transform = cv2.distanceTransform(opening, cv2.DIST_L2, 5)
    ret, sure_fg = cv2.threshold(dist_transform, 0.7 * dist_transform.max(), 255, 0)
    sure_fg = sure_fg.astype(np.uint8)

    # 背景减去前景获取不确定的区域
    unknown = cv2.subtract(sure_bg, sure_fg)

    # 标注前景
    ret, markers = cv2.connectedComponents(sure_fg)

    # 设置确定区域为背景1
    markers += 1

    # 设置不确定区域为0
    markers[unknown==255] = 0

    markers = cv2.watershed(frame, markers)
    frame[markers==-1] = [0,255, 0]
  


    cv2.imshow("Demo", sure_bg)
    # quit or save frame
    key = cv2.waitKey(1) 
    if key == ord("a"):
        break

cv2.destroyAllWindows()

背景虚化案例2

import numpy as np
import cv2

camera = cv2.VideoCapture(0)

while (True):
    ret, frame = camera.read()
    if not ret:
        continue

    img = frame.copy()

    # 创建黑色掩膜
    mask = np.zeros(img.shape[:2], np.uint8)

    # 创建用0填充的背景和前景
    bg = np.zeros((1, 65), np.float64)
    fg = np.zeros((1, 65), np.float64)

    # 迭代的次数
    rect = (100, 1, 421, 378)
    cv2.grabCut(img, mask, rect, bg, fg, 5, cv2.GC_INIT_WITH_RECT)

    # 0,2表示背景,1,3表示前景,表0,2的像素乘以0,1和3的像素乘以1保持不变
    mask2 = np.where((mask==2) | (mask==0), 0, 1).astype('uint8')
    img = img*mask2[:,:,np.newaxis]


    cv2.imshow("demo", img)
    # quit or save frame
    key = cv2.waitKey(1) & 0xff
    if key == ord("a"):
        break
    

cv2.destroyAllWindows()

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

机器人迈克猫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值