β 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:
- Variable naming clarity:
- Avoid using
inputas a variable name since it shadows Python’s built-ininput()function. - I renamed it to
input_imageandoutput_image.
- Avoid using
- File Format:
- Make sure the output filename ends with
.pngbecause the background is removed and replaced with transparency, which requires a format like PNG (JPEG does not support transparency).
- Make sure the output filename ends with
- Installation:
- You only need to run
pip install rembgonce to install the package.
- You only need to run
π‘ 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.
