-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproject.py
70 lines (55 loc) · 2.21 KB
/
project.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import tkinter as tk
from tkinter import filedialog
from PIL import Image, ImageTk
import rembg
import numpy as np
import sys
import os
class BackgroundRemovalApp:
def __init__(self, root):
self.root = root
root.title("Remove Background")
# Create a label to display the image
self.label = tk.Label(root)
self.label.pack(padx=10, pady=10)
# Create a button to initiate background removal and image saving
remove_button = tk.Button(root, text="Start Here", command=self.remove_background)
remove_button.pack(pady=10)
# Associate the F5 keypress event with the program restart function
root.bind("<F5>", self.restart_program)
def remove_background(self):
# Open a dialog to select an image
file_path = filedialog.askopenfilename()
if file_path:
try:
# Load the image using the PIL library
image = Image.open(file_path)
# Convert the image to a format accepted by rembg
image_array = np.array(image)
output = rembg.remove(image_array)
# Convert the rembg output back to a PIL image
output_image = Image.fromarray(output)
# Save the image with the removed background
save_path = filedialog.asksaveasfilename(defaultextension=".png", filetypes=[("PNG files", "*.png")])
if save_path:
output_image.save(save_path)
# Update the image displayed in the interface
self.update_display(output_image)
except Exception as e:
# Handle errors, e.g., when the selected file is not an image
print(f"Error: {e}")
def update_display(self, image):
# Update the displayed image in the interface
photo = ImageTk.PhotoImage(image)
self.label.config(image=photo)
self.label.image = photo
def restart_program(self, event):
# Restart the program
python = sys.executable
os.execl(python, python, *sys.argv)
def main():
root = tk.Tk()
app = BackgroundRemovalApp(root)
root.mainloop()
if __name__ == "__main__":
main()