Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
from transformers import AutoImageProcessor, DetaForObjectDetection
|
| 3 |
+
from PIL import Image
|
| 4 |
+
import requests
|
| 5 |
+
|
| 6 |
+
st.title("Object Detection")
|
| 7 |
+
|
| 8 |
+
# Sidebar instructions
|
| 9 |
+
st.sidebar.header("Instructions")
|
| 10 |
+
st.sidebar.write("1. Enter an image URL in the text input below.")
|
| 11 |
+
st.sidebar.write("2. Click the 'Detect Objects' button to process the image.")
|
| 12 |
+
|
| 13 |
+
# Image URL input
|
| 14 |
+
image_url = st.text_input("Enter image URL:", "http://images.cocodataset.org/val2017/000000039769.jpg")
|
| 15 |
+
|
| 16 |
+
if st.button("Detect Objects"):
|
| 17 |
+
try:
|
| 18 |
+
# Load the image
|
| 19 |
+
image = Image.open(requests.get(image_url, stream=True).raw)
|
| 20 |
+
|
| 21 |
+
# Initialize the image processor and model
|
| 22 |
+
image_processor = AutoImageProcessor.from_pretrained("jozhang97/deta-swin-large")
|
| 23 |
+
model = DetaForObjectDetection.from_pretrained("jozhang97/deta-swin-large")
|
| 24 |
+
|
| 25 |
+
# Process the image
|
| 26 |
+
inputs = image_processor(images=image, return_tensors="pt")
|
| 27 |
+
outputs = model(**inputs)
|
| 28 |
+
|
| 29 |
+
# Convert outputs to Pascal VOC format
|
| 30 |
+
target_sizes = torch.tensor([image.size[::-1]])
|
| 31 |
+
results = image_processor.post_process_object_detection(outputs, threshold=0.5, target_sizes=target_sizes)[0]
|
| 32 |
+
|
| 33 |
+
# Display the image and detected objects
|
| 34 |
+
st.image(image, use_column_width=True)
|
| 35 |
+
for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
|
| 36 |
+
box = [round(i, 2) for i in box.tolist()]
|
| 37 |
+
st.write(f"Detected {model.config.id2label[label.item()]} with confidence {round(score.item(), 3)} at location {box}")
|
| 38 |
+
except:
|
| 39 |
+
st.write("Error: Unable to process the image. Please check the URL and try again.")
|