Mediapipe 人物去背
这篇教学会使用 MediaPipe 的自拍分割模型 ( Selfie Segmentation ) 侦测人物主体后,将背景去除,再透过 OpenCV 读取摄影镜头图像加入虚拟背景,即时将去背的人物与背景合成。
因为程序使用 Jupyter 搭配 Tensorflow 进行开发,所以请先阅读“使用 Anaconda”和“使用 MediaPipe”,安装对应的软件包,如果不要使用 Juputer,也可参考“使用 Python 虚拟环境”,建立虚拟环境进行实作。
使用 MediaPipe,侦测人物主体并去背
Mediapipe Selfie Segmentation 使用基于 MobileNetV3 的模型,可以将场景中的突出人物与背景分离,虽然能做到即时的去背效果,但如果是“复杂”的的背景,然后会出现侦测错误的状况,因此仍然建议使用“单纯”的背景,才能看出比较好的效果 ( 有时甚至需要打光,强化主体人物,达到更好的去背效果 )。
下方的程序码延伸“读取并播放影片”文章的范例,搭配 mediapipe ,侦测人物主体并去背的方法,透过摄影镜头获取图像后,将人物和 windows 的经典背景进行合成。
import cv2
import mediapipe as mp
import numpy as np
mp_drawing = mp.solutions.drawing_utils # mediapipe 繪圖功能
mp_selfie_segmentation = mp.solutions.selfie_segmentation # mediapipe 自拍分割方法
cap = cv2.VideoCapture(0)
bg = cv2.imread('windows-bg.jpg') # 載入 windows 經典背景
# mediapipe 啟用自拍分割
with mp_selfie_segmentation.SelfieSegmentation(
model_selection=1) as selfie_segmentation:
if not cap.isOpened():
print("Cannot open camera")
exit()
while True:
ret, img = cap.read()
if not ret:
print("Cannot receive frame")
break
img = cv2.resize(img,(520,300)) # 縮小尺寸,加快演算速度
img2 = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # 將 BGR 轉換成 RGB
results = selfie_segmentation.process(img2) # 取得自拍分割結果
condition = np.stack((results.segmentation_mask,) * 3, axis=-1) > 0.1 # 如果滿足模型判斷條件 ( 表示要換成背景 ),回傳 True
output_image = np.where(condition, img, bg)
# 將主體與背景合成,如果滿足背景條件,就更換為 bg 的像素,不然維持原本的 img 的像素
cv2.imshow('oxxostudio', output_image)
if cv2.waitKey(5) == ord('q'):
break # 按下 q 鍵停止
cap.release()
cv2.destroyAllWindows()
微信扫码关注
抖音扫码关注