【Python】快速简单实现图像背景更换

😎 hello,大家好,我是wangzirui32,今天我们来学习如何快速简单实现图像背景更换,开始学习吧!

1. 开发准备

    Python 3 解释器 OpenCV-Python库 cvzone库 mediapipe库(cvzone库依赖)

pip安装命令如下:

pip install cvzone mediapipe OpenCV-Python

安装无报错后,即可开始编写代码。

2. 代码

代码如下:

import cv2
from cvzone.SelfiSegmentationModule import SelfiSegmentation

# 读取input.png
image = cv2.imread(input.png)

segmentor = SelfiSegmentation()
# 更换背景
new_image = segmentor.removeBG(image, (255, 255, 255), threshold=0.3)

# 输出照片
cv2.imwrite("output.png", new_image)

removeBG参数如下:

    img需要更换背景的图片 imgBg图片背景,可以为图片对象,也可以为元组RGB值 threshold图片分割阈值,用来控制删除背景区域的大小

3. 效果

效果如下:(左为input.png,右为output.png)


经验分享 程序员 微信小程序 职场和发展