Backgroud remove with python CodeX Rakib

 


Here is the python code for remove background 


from rembg import remove
from PIL import Image
import os
from tkinter import Tk, filedialog
from datetime import datetime

# Hide the root window of tkinter
root = Tk()
root.withdraw()

# Open a file dialog to choose an input image
input_path = filedialog.askopenfilename(
    title="Select an image",
    filetypes=[("Image files", "*.png;*.jpg;*.jpeg;*.bmp;*.webp")]
)

if input_path:
    try:
        # Open the image
        inp = Image.open(input_path)

        # Remove background
        output = remove(inp)

        # Get user's Downloads folder
        downloads_folder = os.path.join(os.path.expanduser("~"), "Downloads")

        # Generate unique filename based on timestamp
        filename = f"bg_removed_{datetime.now().strftime('%Y%m%d_%H%M%S')}.png"
        output_path = os.path.join(downloads_folder, filename)

        # Save the output image
        output.save(output_path)

        print(f"Background removed and saved to: {output_path}")

        # Optionally show the result
        Image.open(output_path).show()

    except Exception as e:
        print(f"An error occurred: {e}")
else:
    print("No file selected.")

Post a Comment

Previous Post Next Post