shivvamm commited on
Commit
c9ec3dd
·
1 Parent(s): 035a50a

Added Upload

Browse files
Files changed (2) hide show
  1. app.py +108 -0
  2. requirements.txt +11 -0
app.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from PIL import Image
3
+ import numpy as np
4
+ import matplotlib.pyplot as plt
5
+ import pandas as pd
6
+ import torch
7
+ from collections import Counter
8
+ from torchvision.models.detection import fasterrcnn_resnet50_fpn_v2, FasterRCNN_ResNet50_FPN_V2_Weights
9
+ from torchvision.utils import draw_bounding_boxes
10
+ import io
11
+
12
+ # Streamlit page configuration
13
+ st.set_page_config(
14
+ page_title="Object Detector Dashboard",
15
+ page_icon="🔍",
16
+ layout="wide",
17
+ initial_sidebar_state="expanded"
18
+ )
19
+
20
+ st.sidebar.title("Traffic Monitoring AI")
21
+
22
+ weights = FasterRCNN_ResNet50_FPN_V2_Weights.DEFAULT
23
+ categories = weights.meta["categories"]
24
+ img_preprocess = weights.transforms()
25
+
26
+ @st.cache_resource
27
+ def load_model(threshold):
28
+ model = fasterrcnn_resnet50_fpn_v2(weights=weights, box_score_thresh=threshold)
29
+ model.eval()
30
+ return model
31
+
32
+ def make_prediction(img, model):
33
+ img_processed = img_preprocess(img)
34
+ prediction = model(img_processed.unsqueeze(0))
35
+ prediction = prediction[0]
36
+ prediction["labels"] = [categories[label] for label in prediction["labels"]]
37
+ return prediction
38
+
39
+ def create_image_with_bboxes(img, prediction):
40
+ img_tensor = torch.tensor(img)
41
+ img_with_bboxes = draw_bounding_boxes(
42
+ img_tensor,
43
+ boxes=prediction["boxes"],
44
+ labels=prediction["labels"],
45
+ colors=["Green" if label == "person" else "red" for label in prediction["labels"]],
46
+ width=1
47
+ )
48
+ img_with_bboxes_np = img_with_bboxes.detach().numpy().transpose(1, 2, 0)
49
+ return img_with_bboxes_np
50
+
51
+ threshold = st.sidebar.slider("Confidence Threshold", min_value=0.0, max_value=1.0, value=0.1, step=0.01)
52
+
53
+ st.title("Vehicle Detection")
54
+ st.markdown("Upload your images for object detection:")
55
+
56
+ # Allow users to upload multiple images
57
+ uploaded_files = st.file_uploader("Choose images...", type=["jpg", "jpeg", "png"], accept_multiple_files=True)
58
+
59
+ if uploaded_files:
60
+ st.markdown("**Processing uploaded images...**")
61
+
62
+ # Load the model once
63
+ model = load_model(threshold)
64
+
65
+ all_predictions = []
66
+ cols = st.columns(min(len(uploaded_files), 4)) # Create columns for displaying images
67
+
68
+ with st.spinner("Processing images, please wait..."):
69
+ for i, uploaded_file in enumerate(uploaded_files):
70
+ try:
71
+ img = Image.open(uploaded_file)
72
+ img = img.convert("RGB") # Ensure the image is in RGB format
73
+
74
+ prediction = make_prediction(img, model)
75
+ img_with_bbox = create_image_with_bboxes(np.array(img).transpose(2, 0, 1), prediction)
76
+
77
+ with cols[i % 4]:
78
+ st.header(f"Image {i + 1}: Object Detection Results")
79
+ fig = plt.figure(figsize=(5, 5))
80
+ ax = fig.add_subplot(111)
81
+ plt.imshow(img_with_bbox)
82
+ plt.xticks([], [])
83
+ plt.yticks([], [])
84
+ ax.spines[["top", "bottom", "right", "left"]].set_visible(True)
85
+ st.pyplot(fig, use_container_width=True)
86
+
87
+ for label in prediction["labels"]:
88
+ all_predictions.append({"Image": f"Image {i + 1}", "Label": label})
89
+
90
+ except Exception as e:
91
+ st.error(f"Error processing image {i + 1}: {e}")
92
+
93
+ if all_predictions:
94
+ image_object_counts = []
95
+ for i in range(1, len(uploaded_files) + 1):
96
+ current_image_preds = [pred['Label'] for pred in all_predictions if pred['Image'] == f"Image {i}"]
97
+ object_count = Counter(current_image_preds)
98
+ for label, count in object_count.items():
99
+ image_object_counts.append({"Image": f"Image {i}", "Label": label, "Count": count})
100
+
101
+ df_summary = pd.DataFrame(image_object_counts)
102
+
103
+ vehicle_categories = ['car', 'bus', 'motorcycle', 'truck', 'train', 'bicycle', 'scooter']
104
+ df_vehicles = df_summary[df_summary['Label'].isin(vehicle_categories)]
105
+
106
+ if not df_vehicles.empty:
107
+ st.header("Combined Vehicle Detection Table for All Images")
108
+ st.dataframe(df_vehicles, use_container_width=True)
requirements.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ matplotlib
2
+ numpy
3
+ pandas
4
+ Pillow
5
+ Pillow
6
+ Requests
7
+ selenium
8
+ streamlit
9
+ torch
10
+ torchvision
11
+ webdriver_manager