Categories: Python
Tags:

βœ… Here is the code to remove Background from Images using Rembg library

# Install rembg
# pip install rembg

from rembg import remove
from PIL import Image

input_path = 'cl.jpg'
output_path = 'output.png'

input_image = Image.open(input_path)
output_image = remove(input_image)
output_image.save(output_path)

βœ… Notes:

  1. Variable naming clarity:
    • Avoid using input as a variable name since it shadows Python’s built-in input() function.
    • I renamed it to input_image and output_image.
  2. File Format:
    • Make sure the output filename ends with .png because the background is removed and replaced with transparency, which requires a format like PNG (JPEG does not support transparency).
  3. Installation:
    • You only need to run pip install rembg once to install the package.

πŸ’‘ Tip:

If you get an error like cannot identify image file, make sure the input image path (cl.jpg) is correct and the file exists.

Let me know if you want to apply this on multiple images or do batch processing.