python+mediapipe人体分割替换背景
前言
mediapipe官网:随时随地进行机器学习
MediaPipe为直播和流媒体提供跨平台、可定制的 ML 解决方案。
一、mediapipe是什么?
mediapipe官网随时随地进行机器学习
MediaPipe为直播和流媒体提供跨平台、可定制的 ML 解决方案。
二、使用方法&注意事项
1.引入库
安装mediapipe
pip install mediapipe
2.上代码
import cv2
import mediapipe as mp
import numpy as np
mp_drawing = mp.solutions.drawing_utils
mp_selfie_segmentation = mp.solutions.selfie_segmentation
# For static images:
IMAGE_FILES = []
BG_COLOR = (192, 192, 192) # gray
MASK_COLOR = (255, 255, 255) # white
with mp_selfie_segmentation.SelfieSegmentation(model_selection=0) as selfie_segmentation:
for idx, file in enumerate(IMAGE_FILES):
image = cv2.imread(file)
image_height, image_width, _ = image.shape
# 处理前将BGR图像转换为RGB。
results = selfie_segmentation.process(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
# 在背景图像上绘制自拍分割。
# 为了改进边界周围的分割,考虑应用一个联合
# 使用“图像”对“results.segmentation mask”进行双边过滤。
condition = np.stack((results.segmentation_mask,) * 3, axis=-1) > 0.1
# 生成纯色图像以显示输出的自拍分割蒙版。
fg_image = np.zeros(image.shape, dtype=np.uint8)
fg_image[:] = MASK_COLOR
bg_image = np.zeros(image.shape, dtype=np.uint8)
bg_image[:] = BG_COLOR
output_image = np.where(condition, fg_image, bg_image)
cv2.imwrite('/tmp/selfie_segmentation_output' + str(idx) + '.png', output_image)
# For webcam input:
BG_COLOR = (192, 192, 192) # gray
cap = cv2.VideoCapture(0)
with mp_selfie_segmentation.SelfieSegmentation(
model_selection=1) as selfie_segmentation:
bg_image = None
while cap.isOpened():
success, image = cap.read()
if not success:
print("摄像头被占用")
# 如果加载视频,请使用“break”而不是“continue”。
continue
# 水平翻转图像以供稍后自拍视图显示,并转换
# 将 BGR 图像转为 RGB。
image = cv2.cvtColor(cv2.flip(image, 1), cv2.COLOR_BGR2RGB)
# 为了提高性能,可选择将图像标记为不可写入
# 通过引用传递。
image.flags.writeable = False
results = selfie_segmentation.process(image)
image.flags.writeable = True
image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
# 在背景图像上绘制自拍分割。
# 为了改进边界周围的分割,考虑应用一个联合
# 使用“图像”对“results.segmentation mask”进行双边过滤。
condition = np.stack(
(results.segmentation_mask,) * 3, axis=-1) > 0.5
# 背景可以自定义。
# a) 加载一张图片(与输入图片的宽度和高度相同)到
# 作为背景,例如,bg_image = cv2.imread('/path/to/image/file')
# b) 通过应用图像过滤来模糊输入图像,例如,
# bg_image = cv2.GaussianBlur(image,(55,55),0)
if bg_image is None:
bg_image = np.zeros(image.shape, dtype=np.uint8)
bg_image[:] = BG_COLOR
# bg_image = cv2.GaussianBlur(image,(55,55),0)
bg_image = cv2.imread('001.png')
output_image = np.where(condition, image, bg_image)
cv2.imshow('MediaPipe Selfie Segmentation', output_image)
if cv2.waitKey(5) & 0xFF == 27:
break
cap.release()
3.注意事项
bg_image = cv2.GaussianBlur(image,(55,55),0) #这个是背景虚化
bg_image = cv2.imread('001.png') #这个是图片,注意:图片要和摄像机输入设备分辨率一样大的图片,否则或报错