How to remove background of jpg that was converted from a png with a transparent background? In python

123 Views Asked by At

The title says it all, I've tried with cv2, but it just doesn't work. I could use some online stuff but I have 100+ photos and It will take a lot of time (for the record no I didn't download stock photos and now I want to illegally do something with them or something like that, It's complicated)

1

There are 1 best solutions below

0
Benioriginalul On

I managed to do it with rembg, it's not THAT fast but it works couldn't find any alternative. basic example:

from rembg import remove
from PIL import Image
import easygui as eg
input_path = eg.fileopenbox(title='Select image file')
output_path = eg.filesavebox(title='Save file to..')
input = Image.open(input_path)
output = remove(input)
output.save(output_path)

Here I just converted every jpg to another directory

import os
from rembg import remove
from PIL import Image

input_dir = r'C:\Users\BainBan Main\Desktop\Makise_Ai\ss'

# Process each directory
directories = [
    'eyes_going_right_up',
    'eyes_going_left_down',
    'eyes_going_left_up'
]

for directory in directories:
    input_path = os.path.join(input_dir, directory)
    output_path = os.path.join(input_dir, f'{directory}_png')

    # Create the output directory if it doesn't exist
    os.makedirs(output_path, exist_ok=True)

    # Process each JPG file in the input directory
    for filename in os.listdir(input_path):
        if filename.endswith('.jpg'):
            input_file = os.path.join(input_path, filename)
            output_file = os.path.join(output_path, f'{os.path.splitext(filename)[0]}_png.png')

            # Open the input image, remove the background, and save as PNG
            input_image = Image.open(input_file)
            output_image = remove(input_image)
            output_image.save(output_file)