-1

I want to remove the background and replace it with a white background and resize it for images in a folder. I only get an error.

I got the following code:

from PIL import Image
import rembg

def process(session, image, *, size=None, bgcolor='white'):
    "session is a rembg Session, and image is a PIL Image"
    if size is not None:
        image = image.resize(size)
    else:
        size = image.size
    result = Image.new("RGB", size, bgcolor)
    out = rembg.remove(image, session=session)
    result.paste(out, mask=out)
    return result

from pathlib import Path

for path_in in Path(r'C:\Users\test').glob('*.jpg'):
    path_out = path_in.parent / f"{path_in.stem}-out.png"
    if path_out.exists():
        continue
    with Image.open(path_in) as img:
        out = process(session, img, size=(700, 700), bgcolor='#FFFFFF')
        out.save(path_out)

Error

NameError: name 'session' is not defined 

on this line:

out = process(session, img, size=(700, 700), bgcolor='#FFFFFF')

Would appreciate the help!

Christoph Rackwitz
  • 11,317
  • 4
  • 27
  • 36
Deidraak
  • 113
  • 4

1 Answers1

1

Only issue here is undefined session, you need identify with this session = rembg.new_session(). After that you can take output.

The Lord
  • 72
  • 1
  • 7