Problems with removing green screen using OpenCV

Viewed 25

Hello i'm not good at OpenCV but i want to practice in it. This program must make video without greenscreen and save it. But it has bug which i can't detect.

https://i.stack.imgur.com/KJLRH.jpg //background photo

https://youtu.be/XOI3-UWFVQQ //greenscreen video

Remove green background screen from image using OpenCV/Python //main part of code i took here

class Video_sv(object):

    def __init__(self, path_green: str, path_bg: str):
        self.video = cv2.VideoCapture(path_green)//path to the video with green background
        self.bg = cv2.imread(path_bg)// background with resolution 1920x1080 and jpeg format

    def get_video(self):
        frame_width = int(self.video.get(3))
        frame_height = int(self.video.get(4))

        size = (frame_width, frame_height)
        # size = (1920, 1080)
        result = cv2.VideoWriter('filename.avi',
                                 cv2.VideoWriter_fourcc(*'MJPG'),
                                 24, size)  # 24-FPS

        while True:
            ret, frame = self.video.read()

            # Break the loop
            if not ret:

                break

            else:

                result.write(self.replace_background2(frame, self.bg))

                # Display the frame
                # saved in the file
                cv2.imshow('Frame', frame)

        # When everything done, release
        # the video capture and video
        # write objects

        result.release()

        # Closes all the frames
        cv2.destroyAllWindows()

    

    @staticmethod
    def replace_background2(frame, bg):

        img = frame

        # convert to LAB
        lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)

        # extract A channel
        A = lab[:, :, 1]

        # threshold A channel
        thresh = cv2.threshold(A, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]

        # blur threshold image
        blur = cv2.GaussianBlur(thresh, (0, 0), sigmaX=5, sigmaY=5, borderType=cv2.BORDER_DEFAULT)

        # stretch so that 255 -> 255 and 127.5 -> 0
        mask = skimage.exposure.rescale_intensity(blur, in_range=(127.5, 255), out_range=(0, 255)).astype(np.uint8)

        # add mask to image as alpha channel
        result = img.copy()
        result = cv2.cvtColor(img, cv2.COLOR_BGR2BGRA)
        result[:, :, 3] = mask

        return cv2.bitwise_not(result, bg)

    

What i need to do to solve this problem ?

0 Answers
Related