How do i use python to remove backgrounds of multiple images?

508 Views Asked by At

I want to know how to remove the background of multiple images at once

I tried this:

from rembg import remove
from PIL import Image
import os

for i in os.listdir(r'C:\\Users\\Carlo Karim\\Desktop\\folder'):
input_path = r'C:\\Users\\Carlo Karim\\Desktop\\folder' + i
output_path = r'C:\\Users\\Carlo Karim\\Documents\\output'

input = Image.open(input_path)
output = remove(input)
output.save(output_path)

but it gave me an error at line 6 and I can't seem to make this work.

1

There are 1 best solutions below

0
Luke Bowes On BEST ANSWER

3 things to note

  1. Your input path needs \\ at the end

  2. Your output string needs to be a path with an image extension

  3. Output needs to be PNG for transparency

     from rembg import remove
     from PIL import Image
     import os
    
     for i in os.listdir(r'C:\\Users\\Carlo Karim\\Desktop\\folder'):
    
         j = i.rsplit('.', maxsplit=1)[0]
         input_path = r'C:\\Users\\Carlo Karim\\Desktop\\folder\\' + i
         output_path = r'C:\\Users\\Carlo Karim\\Documents\\output\\' + j + ".png"
    
         input = Image.open(input_path)
         output = remove(input)
         output.save(output_path)