SRUTHI123 commited on
Commit
9147ea0
·
verified ·
1 Parent(s): 848d7db

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +31 -29
app.py CHANGED
@@ -3,54 +3,56 @@ from PIL import Image
3
  import numpy as np
4
  from ultralytics import YOLO
5
 
 
6
  st.set_page_config(page_title="Suspicious Activity Detection", layout="centered")
7
 
8
- # Load the YOLOv11 model
9
  @st.cache_resource
10
  def load_model():
11
- return YOLO("yolo11l.pt") # Ensure your model file is present in the root directory
12
 
13
  model = load_model()
14
 
15
- # ------------------ Intelligent Action Classification Logic ------------------
16
  def classify_action(detections):
17
  """
18
- Classifies the activity based on detected object types and confidence scores.
19
- Adjusted to better separate 'Sneaking' from 'Peaking'.
20
  """
21
- action_scores = {'Stealing': 0, 'Sneaking': 0, 'Peaking': 0, 'Normal': 0}
 
 
 
 
 
 
22
  objects = [d[0] for d in detections]
23
  confidences = [d[1] for d in detections]
24
-
25
  has_person = 'person' in objects
26
- has_bag = any(obj in objects for obj in ['backpack', 'handbag'])
27
- low_conf = max(confidences) < 0.6 if confidences else True
28
- few_objects = len(set(objects)) <= 2
29
- mostly_person = objects.count('person') >= len(objects) * 0.6
30
 
31
  if has_person:
32
- if has_bag:
33
  action_scores['Stealing'] += 0.7
34
- if low_conf and few_objects:
35
- action_scores['Sneaking'] += 0.9
36
- elif mostly_person and few_objects:
37
  action_scores['Peaking'] += 0.6
38
- else:
39
- action_scores['Normal'] += 0.8
40
  else:
41
- action_scores['Normal'] += 1.0
42
 
43
- # Normalize scores
44
  total = sum(action_scores.values())
45
  if total > 0:
46
- for k in action_scores:
47
- action_scores[k] /= total
48
 
49
  return action_scores
50
 
51
  # ------------------ Detection Function ------------------
52
  def detect_action(image_path):
53
- results = model.predict(source=image_path, conf=0.4, iou=0.5, save=False, verbose=False)
54
  result = results[0]
55
 
56
  detections = [
@@ -64,10 +66,10 @@ def detect_action(image_path):
64
  return annotated_image, action_scores
65
 
66
  # ------------------ Streamlit UI ------------------
67
- st.title("🛡️ Suspicious Activity Detection")
68
- st.markdown("Upload an image to detect if someone is **Stealing**, **Sneaking**, **Peaking**, or acting **Normal**.")
69
 
70
- uploaded_file = st.file_uploader("📸 Upload an image", type=["jpg", "jpeg", "png"])
71
 
72
  if uploaded_file:
73
  image = Image.open(uploaded_file).convert("RGB")
@@ -76,14 +78,14 @@ if uploaded_file:
76
  temp_path = "/tmp/uploaded.jpg"
77
  image.save(temp_path)
78
 
79
- with st.spinner("🔍 Detecting suspicious activity..."):
80
  detected_image, action_scores = detect_action(temp_path)
81
 
82
- st.image(detected_image, caption="🔍 Detection Results", use_column_width=True)
83
 
84
  st.subheader("📊 Action Confidence Scores")
85
  for action, score in action_scores.items():
86
  st.write(f"**{action}**: {score:.2%}")
87
 
88
- top_action = max(action_scores.items(), key=lambda x: x[1])
89
- st.success(f"🎯 **Predicted Action:** {top_action[0]} ({top_action[1]:.2%} confidence)")
 
3
  import numpy as np
4
  from ultralytics import YOLO
5
 
6
+ # Streamlit configuration
7
  st.set_page_config(page_title="Suspicious Activity Detection", layout="centered")
8
 
9
+ # Load YOLOv11 model
10
  @st.cache_resource
11
  def load_model():
12
+ return YOLO("yolo11l (1).pt") # Match the uploaded filename
13
 
14
  model = load_model()
15
 
16
+ # ------------------ Action Classification Logic ------------------
17
  def classify_action(detections):
18
  """
19
+ Classify action using object types and confidence.
20
+ Sneaking: person detected with low confidence, alone, and few objects.
21
  """
22
+ action_scores = {
23
+ 'Stealing': 0,
24
+ 'Sneaking': 0,
25
+ 'Peaking': 0,
26
+ 'Normal': 0
27
+ }
28
+
29
  objects = [d[0] for d in detections]
30
  confidences = [d[1] for d in detections]
 
31
  has_person = 'person' in objects
32
+ num_objects = len(objects)
 
 
 
33
 
34
  if has_person:
35
+ if ('handbag' in objects or 'backpack' in objects) and num_objects > 2:
36
  action_scores['Stealing'] += 0.7
37
+ if max(confidences) < 0.55 and num_objects <= 2:
38
+ action_scores['Sneaking'] += 0.8
39
+ if num_objects <= 2 and max(confidences) > 0.55:
40
  action_scores['Peaking'] += 0.6
41
+ if action_scores['Stealing'] == 0 and action_scores['Sneaking'] == 0 and action_scores['Peaking'] == 0:
42
+ action_scores['Normal'] = 1.0
43
  else:
44
+ action_scores['Normal'] = 1.0
45
 
 
46
  total = sum(action_scores.values())
47
  if total > 0:
48
+ for key in action_scores:
49
+ action_scores[key] /= total
50
 
51
  return action_scores
52
 
53
  # ------------------ Detection Function ------------------
54
  def detect_action(image_path):
55
+ results = model.predict(source=image_path, conf=0.3, iou=0.5, save=False, verbose=False)
56
  result = results[0]
57
 
58
  detections = [
 
66
  return annotated_image, action_scores
67
 
68
  # ------------------ Streamlit UI ------------------
69
+ st.title("🔍 Suspicious Activity Detection")
70
+ st.markdown("Upload an image to detect if someone is **Stealing**, **Sneaking**, **Peaking**, or just acting **Normal**.")
71
 
72
+ uploaded_file = st.file_uploader("📤 Upload an image", type=["jpg", "jpeg", "png"])
73
 
74
  if uploaded_file:
75
  image = Image.open(uploaded_file).convert("RGB")
 
78
  temp_path = "/tmp/uploaded.jpg"
79
  image.save(temp_path)
80
 
81
+ with st.spinner("🕵️ Detecting suspicious activity..."):
82
  detected_image, action_scores = detect_action(temp_path)
83
 
84
+ st.image(detected_image, caption="🔍 Detected Image", use_column_width=True)
85
 
86
  st.subheader("📊 Action Confidence Scores")
87
  for action, score in action_scores.items():
88
  st.write(f"**{action}**: {score:.2%}")
89
 
90
+ most_likely_action = max(action_scores.items(), key=lambda x: x[1])
91
+ st.success(f"🎯 **Predicted Action**: {most_likely_action[0]} ({most_likely_action[1]:.2%} confidence)")