Open cv 배경화면 합성 2번째 버전

chi yeong Yu·2022년 4월 21일
0

opencv

목록 보기
12/12
post-thumbnail

👏구글에서 만든 Mediapipe를 활용해서 배경화면 합성 2탄을 진행해봤습니다. 👏

import cv2
import mediapipe as mp
import numpy as np

class Selfisegmentation():
    
    def __init__(self, model=1):
        self.model = model
        self.mpDraw = mp.solutions.drawing_utils
        self.mpSelfieSegmentation = mp.solutions.selfie_segmentation
        self.selfieSegmentation = self.mpSelfieSegmentation.SelfieSegmentation(self.model)
    
    def remove_BG(self, img, imgbg = (255, 255, 255), threshold=0.1):
        img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        result = self.selfieSegmentation.process(img_rgb)
        # 적혀진 설명으로는 segmentation_mask 2d np.array로 만들어준다고 한다.
        condition = np.stack((result.segmentation_mask, ) * 3, axis=-1) > threshold
        # segmentation.mask 값을 3배로 늘리고 3개 array로 분리 해준 후 값 중에 threshold보다 큰 값들만 출력한다.
        
        if isinstance(imgbg, tuple):
            _imgbg = np.zeros(img.shape, dtype=np.uint8)
            _imgbg[:] = imgbg
            imgOut = np.where(condition, img, _imgbg)
        else:
            imgOut = np.where(condition, img, imgbg)
        return imgOut

cap = cv2.VideoCapture('cows.mp4')
imgBG = cv2.imread('mountain.jpg')
imgBG = cv2.resize(imgBG, (480, 480))

segmentor = Selfisegmentation()
while cap.isOpened():
    ret, frame = cap.read()
    frame = cv2.resize(frame, (480, 480))
    imgOut = segmentor.remove_BG(frame, imgbg=imgBG, threshold=0.3)
    
    cv2.imshow('Image', frame)
    cv2.imshow('Image Out', imgOut)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
cap.release()
cv2.destroyAllWindows()

#https://google.github.io/mediapipe/solutions/selfie_segmentation
#작성되어 있는 코드를 조금 활용해서 적용해 봤습니다.
첫번째 사진은 이전에 진행한 'bodypix'
두번째 사진은 현재 진행한 'mediapipe'![](https://velog.velcdn.com/images/jumpx2/post/d4d76d4a-657d-497d-a01c-f4e322c5a376/image.gif)

가장 잘 나온 결과들만 가져왔습니다.
threshold를 조절해도 mediapipe 조금 더 괜찮은 결과가 나왔습니다.

profile
호기심천국

0개의 댓글