Spaces:
Build error
Build error
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
from rembg import remove
|
3 |
+
from PIL import Image
|
4 |
+
import io
|
5 |
+
|
6 |
+
# Function to remove background using rembg
|
7 |
+
def remove_background(image_file):
|
8 |
+
# Open the uploaded image using PIL
|
9 |
+
input_image = Image.open(image_file)
|
10 |
+
|
11 |
+
# Convert image to byte format for processing
|
12 |
+
img_byte_arr = io.BytesIO()
|
13 |
+
input_image.save(img_byte_arr, format='PNG')
|
14 |
+
img_byte_arr = img_byte_arr.getvalue()
|
15 |
+
|
16 |
+
# Remove background using rembg
|
17 |
+
output_image = remove(img_byte_arr)
|
18 |
+
|
19 |
+
# Convert output byte data to an image
|
20 |
+
output_image = Image.open(io.BytesIO(output_image))
|
21 |
+
|
22 |
+
return output_image
|
23 |
+
|
24 |
+
# Streamlit UI setup
|
25 |
+
st.title("Background Removal Tool")
|
26 |
+
|
27 |
+
st.markdown("""
|
28 |
+
Upload an image, and this tool will automatically remove the background.
|
29 |
+
You can then download the processed image with a transparent background.
|
30 |
+
""")
|
31 |
+
|
32 |
+
# Sidebar for uploading the image
|
33 |
+
st.sidebar.header("Upload Your Image")
|
34 |
+
uploaded_file = st.sidebar.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
|
35 |
+
|
36 |
+
# Columns layout for displaying images
|
37 |
+
col1, col2 = st.columns(2)
|
38 |
+
|
39 |
+
if uploaded_file is not None:
|
40 |
+
# Show the original image in the first column
|
41 |
+
with col1:
|
42 |
+
st.subheader("Original Image")
|
43 |
+
st.image(uploaded_file, caption="Uploaded Image", use_column_width=True)
|
44 |
+
|
45 |
+
# Remove background and display the processed image in the second column
|
46 |
+
with col2:
|
47 |
+
st.subheader("Processed Image")
|
48 |
+
result_image = remove_background(uploaded_file)
|
49 |
+
st.image(result_image, caption="Processed Image", use_column_width=True)
|
50 |
+
|
51 |
+
# Provide a download button for the processed image
|
52 |
+
result_image_bytes = io.BytesIO()
|
53 |
+
result_image.save(result_image_bytes, format='PNG')
|
54 |
+
result_image_bytes.seek(0)
|
55 |
+
|
56 |
+
st.download_button(
|
57 |
+
label="Download Image with Removed Background",
|
58 |
+
data=result_image_bytes,
|
59 |
+
file_name="output_image.png",
|
60 |
+
mime="image/png"
|
61 |
+
)
|
62 |
+
else:
|
63 |
+
st.info("Please upload an image file to remove the background.")
|