1. 开发准备 Python 3 解释器 OpenCV-Python库 cvzone库 mediapipe库(cvzone库依赖) pip安装命令如下:
pip install cvzone mediapipe OpenCV-Python 1 安装无报错后,即可开始编写代码。
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)