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
IMAGE_FILES = []
BG_COLOR = (192, 192, 192)
MASK_COLOR = (255, 255, 255)
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
results = selfie_segmentation.process(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
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)
BG_COLOR = (192, 192, 192)
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("摄像头被占用")
continue
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)
condition = np.stack(
(results.segmentation_mask,) * 3, axis=-1) > 0.5
if bg_image is None:
bg_image = np.zeros(image.shape, dtype=np.uint8)
bg_image[:] = BG_COLOR
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')
成品
Original: https://blog.csdn.net/qq_44291652/article/details/122885590
Author: 我是小杰啊
Title: python+mediapipe人体分割替换背景
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/762519/
转载文章受原作者版权保护。转载请注明原作者出处!