Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import torch
|
| 3 |
+
import cv2
|
| 4 |
+
import numpy as np
|
| 5 |
+
from PIL import Image
|
| 6 |
+
from detectron2 import model_zoo
|
| 7 |
+
from detectron2.engine import DefaultPredictor
|
| 8 |
+
from detectron2.config import get_cfg
|
| 9 |
+
from detectron2.utils.visualizer import Visualizer
|
| 10 |
+
from detectron2.data import MetadataCatalog
|
| 11 |
+
|
| 12 |
+
# Set up Detectron2 model for panoptic segmentation
|
| 13 |
+
cfg = get_cfg()
|
| 14 |
+
cfg.merge_from_file(model_zoo.get_config_file("COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml"))
|
| 15 |
+
cfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url("COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml")
|
| 16 |
+
cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5 # Set a threshold for the model's confidence
|
| 17 |
+
predictor = DefaultPredictor(cfg)
|
| 18 |
+
|
| 19 |
+
st.title("🎯 Smart Background Remover & Object Tagger with Panoptic Segmentation")
|
| 20 |
+
|
| 21 |
+
uploaded_file = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])
|
| 22 |
+
if uploaded_file:
|
| 23 |
+
# Read image
|
| 24 |
+
image = Image.open(uploaded_file).convert("RGB")
|
| 25 |
+
image_np = np.array(image)
|
| 26 |
+
|
| 27 |
+
st.image(image_np, caption="Original Image", use_container_width=True)
|
| 28 |
+
|
| 29 |
+
with st.spinner("Detecting and segmenting..."):
|
| 30 |
+
# Run panoptic segmentation
|
| 31 |
+
outputs = predictor(image_np)
|
| 32 |
+
panoptic_seg, segments_info = outputs["panoptic_seg"], outputs["instances"].to("cpu")
|
| 33 |
+
|
| 34 |
+
# Visualize the results
|
| 35 |
+
v = Visualizer(image_np[:, :, ::-1], MetadataCatalog.get(cfg.DATASETS.TRAIN[0]), scale=1.2)
|
| 36 |
+
v = v.draw_panoptic_segmentation(panoptic_seg.to("cpu"), segments_info)
|
| 37 |
+
result_image = v.get_image()[:, :, ::-1]
|
| 38 |
+
|
| 39 |
+
st.markdown("---")
|
| 40 |
+
st.image(result_image, caption="Panoptic Segmentation Output", use_container_width=True)
|
| 41 |
+
|
| 42 |
+
# Download option for filtered image
|
| 43 |
+
result_img = Image.fromarray(result_image)
|
| 44 |
+
st.download_button("📥 Download Filtered Image", result_img.save, file_name="filtered_panoptic.png", mime="image/png")
|