SRUTHI123 commited on
Commit
36bb73f
·
verified ·
1 Parent(s): bdf1b61

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +83 -28
app.py CHANGED
@@ -1,44 +1,99 @@
1
  import streamlit as st
2
  from PIL import Image
3
  import numpy as np
4
- import cv2
5
  from ultralytics import YOLO
6
 
7
- # Title
8
- st.title("Suspicious Activity Detection")
9
- st.markdown("Upload an image to detect activity (Normal, Peaking, Sneaking, Stealing).")
10
 
11
- # Load model
12
  @st.cache_resource
13
  def load_model():
14
- model = YOLO("yolo11l.pt") # Make sure this file is uploaded to your Space
15
- return model
16
 
17
  model = load_model()
18
 
19
- # File uploader
20
- uploaded_file = st.file_uploader("Upload an image...", type=["jpg", "jpeg", "png"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
  if uploaded_file:
23
  image = Image.open(uploaded_file).convert("RGB")
24
  st.image(image, caption="Uploaded Image", use_column_width=True)
25
 
26
- # Convert to numpy array for OpenCV/YOLO
27
- img_array = np.array(image)
28
-
29
- # Run prediction
30
- st.info("Running detection...")
31
- results = model.predict(source=img_array, conf=0.25, classes=None)
32
-
33
- for r in results:
34
- # Show annotated image
35
- annotated_img = r.plot()
36
- st.image(annotated_img, caption="Detection Result", use_column_width=True)
37
-
38
- # Show detected objects with confidence
39
- st.subheader("Detections:")
40
- for box in r.boxes:
41
- conf = float(box.conf[0])
42
- cls_id = int(box.cls[0])
43
- cls_name = model.names[cls_id]
44
- st.write(f"- **{cls_name}** (Confidence: {conf:.2f})")
 
1
  import streamlit as st
2
  from PIL import Image
3
  import numpy as np
 
4
  from ultralytics import YOLO
5
 
6
+ # Set Streamlit page config
7
+ st.set_page_config(page_title="Suspicious Activity Detection", layout="centered")
 
8
 
9
+ # Load the YOLOv11 model
10
  @st.cache_resource
11
  def load_model():
12
+ return YOLO("yolo11l.pt") # Make sure yolo11l.pt is uploaded in your Space
 
13
 
14
  model = load_model()
15
 
16
+ # ------------------ Modified Action Classification ------------------
17
+ def classify_action(detections):
18
+ """
19
+ Improved classification to distinguish Sneaking from Peaking.
20
+ """
21
+ action_scores = {
22
+ 'Stealing': 0,
23
+ 'Sneaking': 0,
24
+ 'Peaking': 0,
25
+ 'Normal': 0
26
+ }
27
+
28
+ objects = [d[0] for d in detections]
29
+ confidences = [d[1] for d in detections]
30
+
31
+ has_person = 'person' in objects
32
+ avg_conf = np.mean(confidences) if confidences else 0
33
+ num_objects = len(set(objects))
34
+
35
+ # Stealing Logic
36
+ if has_person and ('handbag' in objects or 'backpack' in objects or 'suitcase' in objects):
37
+ action_scores['Stealing'] += 0.6
38
+ if has_person and ('refrigerator' in objects or 'microwave' in objects or 'tv' in objects):
39
+ action_scores['Stealing'] += 0.4
40
+
41
+ # Sneaking Logic: person present, low confidence, few objects
42
+ if has_person and avg_conf < 0.5 and num_objects <= 2:
43
+ action_scores['Sneaking'] += 0.9
44
+
45
+ # Peaking Logic: moderate confidence, minimal visible objects
46
+ if has_person and 0.5 <= avg_conf <= 0.75 and num_objects <= 1:
47
+ action_scores['Peaking'] += 0.7
48
+
49
+ # Normal if nothing else fits
50
+ if all(score == 0 for score in action_scores.values()):
51
+ action_scores['Normal'] = 1.0
52
+
53
+ # Normalize
54
+ total = sum(action_scores.values())
55
+ if total > 0:
56
+ for key in action_scores:
57
+ action_scores[key] /= total
58
+
59
+ return action_scores
60
+
61
+ # ------------------ Detection Function ------------------
62
+ def detect_action(image_path):
63
+ results = model.predict(source=image_path, conf=0.4, iou=0.5, save=False, verbose=False)
64
+ result = results[0]
65
+
66
+ detections = [
67
+ (model.names[int(cls)], float(conf))
68
+ for cls, conf in zip(result.boxes.cls, result.boxes.conf)
69
+ ]
70
+
71
+ annotated_image = result.plot()
72
+ action_scores = classify_action(detections)
73
+
74
+ return annotated_image, action_scores
75
+
76
+ # ------------------ Streamlit UI ------------------
77
+ st.title("🔍 Suspicious Activity Detection")
78
+ st.markdown("Upload an image to detect if someone is **Stealing**, **Sneaking**, **Peaking**, or just acting **Normal**.")
79
+
80
+ uploaded_file = st.file_uploader("📤 Upload an image", type=["jpg", "jpeg", "png"])
81
 
82
  if uploaded_file:
83
  image = Image.open(uploaded_file).convert("RGB")
84
  st.image(image, caption="Uploaded Image", use_column_width=True)
85
 
86
+ temp_path = "/tmp/uploaded.jpg"
87
+ image.save(temp_path)
88
+
89
+ with st.spinner("🕵️ Detecting suspicious activity..."):
90
+ detected_image, action_scores = detect_action(temp_path)
91
+
92
+ st.image(detected_image, caption="🔍 Detected Image", use_column_width=True)
93
+
94
+ st.subheader("📊 Action Confidence Scores")
95
+ for action, score in action_scores.items():
96
+ st.write(f"**{action}**: {score:.2%}")
97
+
98
+ most_likely_action = max(action_scores.items(), key=lambda x: x[1])
99
+ st.success(f"🎯 **Predicted Action**: {most_likely_action[0]} ({most_likely_action[1]:.2%} confidence)")