Spaces:
Sleeping
Sleeping
Created app.py
Browse files
app.py
ADDED
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import cv2
|
3 |
+
import supervision as sv
|
4 |
+
from ultralytics import YOLO
|
5 |
+
import numpy as np
|
6 |
+
from PIL import Image
|
7 |
+
import io
|
8 |
+
import torch
|
9 |
+
|
10 |
+
# Load the YOLO model
|
11 |
+
@st.cache_resource
|
12 |
+
def load_model():
|
13 |
+
model = YOLO("mosaic_medium_100_tiny_object.pt")
|
14 |
+
model.to('cpu')
|
15 |
+
return model
|
16 |
+
|
17 |
+
model = load_model()
|
18 |
+
|
19 |
+
def process_image(image):
|
20 |
+
# Convert PIL Image to numpy array
|
21 |
+
image_np = np.array(image)
|
22 |
+
|
23 |
+
# Convert RGB to BGR (OpenCV uses BGR)
|
24 |
+
image_cv2 = cv2.cvtColor(image_np, cv2.COLOR_RGB2BGR)
|
25 |
+
|
26 |
+
def callback(image_slice: np.ndarray) -> sv.Detections:
|
27 |
+
result = model(image_slice)[0]
|
28 |
+
return sv.Detections.from_ultralytics(result)
|
29 |
+
|
30 |
+
slicer = sv.InferenceSlicer(callback=callback, slice_wh=(256, 256), iou_threshold=0.8)
|
31 |
+
|
32 |
+
detections = slicer(image_cv2)
|
33 |
+
|
34 |
+
# Filter detections for building class (assuming class_id 2 is for buildings)
|
35 |
+
building_detections = detections[detections.class_id == 2]
|
36 |
+
|
37 |
+
label_annotator = sv.LabelAnnotator()
|
38 |
+
box_annotator = sv.BoxAnnotator()
|
39 |
+
|
40 |
+
annotated_image = box_annotator.annotate(scene=image_cv2.copy(), detections=building_detections)
|
41 |
+
annotated_image = label_annotator.annotate(scene=annotated_image, detections=building_detections)
|
42 |
+
|
43 |
+
# Convert BGR back to RGB for displaying in Streamlit
|
44 |
+
return cv2.cvtColor(annotated_image, cv2.COLOR_BGR2RGB)
|
45 |
+
|
46 |
+
def main():
|
47 |
+
st.title("Building Detection App")
|
48 |
+
|
49 |
+
uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
|
50 |
+
|
51 |
+
if uploaded_file is not None:
|
52 |
+
image = Image.open(uploaded_file)
|
53 |
+
st.image(image, caption="Uploaded Image", use_column_width=True)
|
54 |
+
|
55 |
+
if st.button("Detect Buildings"):
|
56 |
+
with st.spinner("Processing..."):
|
57 |
+
result_image = process_image(image)
|
58 |
+
st.image(result_image, caption="Processed Image", use_column_width=True)
|
59 |
+
|
60 |
+
if __name__ == "__main__":
|
61 |
+
main()
|