Remove Background Color From Image

Hi, so i was playing around opencv and found a way online on how to detect and crop the image, but

how can i remove its Background color, so only the image is saved in Lossy web Compressed PNG format.

My Code:

import cv2
import numpy as np
import os


o = os.getcwd()

for s in os.listdir():
    if ".jpg" in s:
        T = os.path.splitext(s)[0]
        img = cv2.imread(s)
        blurred = cv2.blur(img, (3,3))
        canny = cv2.Canny(blurred, 50, 200)


        ## find the non-zero min-max coords of canny
        pts = np.argwhere(canny>0)
        y1,x1 = pts.min(axis=0)
        y2,x2 = pts.max(axis=0)

        ## crop the region
        cropped = img[y1:y2, x1:x2]
        cv2.imwrite(f"{o}/{T}.png", cropped)

My Input Image:

Input Image

My Output Image:

89

related:

to my limited knowledge there’s no easy & generic way in opencv, you can try grabCut or even floodFill, but I would use/train a neural segmentation model to generate foreground mask.