karthikmn commited on
Commit
416d33c
·
verified ·
1 Parent(s): f2a9aff

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +82 -85
app.py CHANGED
@@ -1,87 +1,84 @@
1
  import torch
 
2
  import cv2
3
- from transformers import DetrImageProcessor, DetrForObjectDetection
4
- import numpy as np
5
-
6
- # Load the pre-trained DETR model from Hugging Face for object detection
7
- model_name = "facebook/detr-resnet-50"
8
- processor = DetrImageProcessor.from_pretrained(model_name)
9
- model = DetrForObjectDetection.from_pretrained(model_name)
10
-
11
- # Initialize video capture (use 0 for webcam or video file path)
12
- cap = cv2.VideoCapture('video_feed.mp4') # Use 0 for webcam
13
- def detect_people_and_fight(frame):
14
- # Convert the frame to RGB (Hugging Face models expect RGB input)
15
- frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
16
-
17
- # Process the image to get the required inputs for the model
18
- inputs = processor(images=frame_rgb, return_tensors="pt")
19
-
20
- # Perform inference to detect objects in the image
21
- with torch.no_grad():
22
- outputs = model(**inputs)
23
-
24
- # Get the predicted labels, boxes, and scores
25
- target_sizes = torch.tensor([frame.shape[0:2]])
26
- results = processor.post_process_object_detection(outputs, target_sizes=target_sizes, threshold=0.5)[0]
27
-
28
- people_count = 0
29
- bounding_boxes = []
30
- for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
31
- if label.item() == 0: # class '0' is the label for "person"
32
- people_count += 1
33
- x_min, y_min, x_max, y_max = box.tolist()
34
- bounding_boxes.append((x_min, y_min, x_max, y_max))
35
- # Draw bounding box around detected people
36
- cv2.rectangle(frame, (int(x_min), int(y_min)), (int(x_max), int(y_max)), (0, 255, 0), 2)
37
-
38
- # Return the number of people detected and the bounding boxes
39
- return people_count, bounding_boxes
40
- def detect_fight(bounding_boxes, frame):
41
- fight_detected = False
42
- # Check if there are at least two people
43
- if len(bounding_boxes) > 1:
44
- for i in range(len(bounding_boxes)):
45
- for j in range(i + 1, len(bounding_boxes)):
46
- # Calculate distance between the centers of the bounding boxes
47
- x1, y1, x2, y2 = bounding_boxes[i]
48
- x3, y3, x4, y4 = bounding_boxes[j]
49
-
50
- # Compute center points of bounding boxes
51
- center1 = (int((x1 + x2) / 2), int((y1 + y2) / 2))
52
- center2 = (int((x3 + x4) / 2), int((y3 + y4) / 2))
53
-
54
- # Calculate Euclidean distance between the two centers
55
- dist = np.sqrt((center1[0] - center2[0]) ** 2 + (center1[1] - center2[1]) ** 2)
56
-
57
- # If people are too close to each other (e.g., less than 50 pixels), we assume a potential fight
58
- if dist < 50: # Threshold distance can be adjusted
59
- fight_detected = True
60
- cv2.line(frame, center1, center2, (0, 0, 255), 2) # Draw a line between the two people
61
-
62
- return fight_detected
63
- while True:
64
- ret, frame = cap.read()
65
- if not ret:
66
- break
67
-
68
- # Detect people in the frame
69
- people_count, bounding_boxes = detect_people_and_fight(frame)
70
-
71
- # Check for fight (if multiple people are very close to each other)
72
- fight_detected = detect_fight(bounding_boxes, frame)
73
-
74
- # Display results on the frame
75
- cv2.putText(frame, f"People detected: {people_count}", (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2)
76
- if fight_detected:
77
- cv2.putText(frame, "Fight Detected!", (50, 100), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
78
-
79
- # Show the resulting frame
80
- cv2.imshow("Crowd and Fight Detection", frame)
81
-
82
- # Exit the loop when 'q' is pressed
83
- if cv2.waitKey(1) & 0xFF == ord('q'):
84
- break
85
-
86
- cap.release()
87
- cv2.destroyAllWindows()
 
1
  import torch
2
+ from transformers import AutoFeatureExtractor, AutoModelForObjectDetection
3
  import cv2
4
+ import pandas as pd
5
+ import smtplib
6
+ from datetime import datetime, timedelta
7
+
8
+ # Load pre-trained model
9
+ model_name = "hustvl/yolos-small"
10
+ feature_extractor = AutoFeatureExtractor.from_pretrained(model_name)
11
+ model = AutoModelForObjectDetection.from_pretrained(model_name)
12
+
13
+ def detect_number_plates(image):
14
+ # Pre-process image
15
+ inputs = feature_extractor(images=image, return_tensors="pt")
16
+
17
+ # Run object detection
18
+ outputs = model(**inputs)
19
+
20
+ # Extract detected number plates
21
+ number_plates = []
22
+ for i, detection in enumerate(outputs):
23
+ for j, score in enumerate(detection["scores"]):
24
+ if score > 0.5 and detection["labels"][j] == 7: # 7 is the class ID for number plates
25
+ x1, y1, x2, y2 = detection["boxes"][j]
26
+ number_plates.append((x1, y1, x2, y2))
27
+
28
+ return number_plates
29
+
30
+ def save_to_excel(number_plates):
31
+ # Create a pandas DataFrame
32
+ df = pd.DataFrame({
33
+ "Date": [datetime.now().strftime("%Y-%m-%d %H:%M:%S") for _ in range(len(number_plates))],
34
+ "Number Plate": [f"{x1}, {y1}, {x2}, {y2}" for x1, y1, x2, y2 in number_plates]
35
+ })
36
+
37
+ # Append to existing Excel file or create a new one
38
+ try:
39
+ existing_df = pd.read_excel("number_plates.xlsx")
40
+ combined_df = pd.concat([existing_df, df])
41
+ combined_df.to_excel("number_plates.xlsx", index=False)
42
+ except FileNotFoundError:
43
+ df.to_excel("number_plates.xlsx", index=False)
44
+
45
+ def monitor_vehicles(number_plates):
46
+ # Load registered number plates from a file or database
47
+ registered_plates = pd.read_csv("registered_plates.csv")["Number Plate"].tolist()
48
+
49
+ # Check each detected number plate
50
+ for x1, y1, x2, y2 in number_plates:
51
+ number_plate = f"{x1}, {y1}, {x2}, {y2}"
52
+ if number_plate not in registered_plates:
53
+ # Check if the vehicle has been present for more than 24 hours
54
+ try:
55
+ existing_df = pd.read_excel("number_plates.xlsx")
56
+ vehicle_entries = existing_df[existing_df["Number Plate"] == number_plate]
57
+ if len(vehicle_entries) > 0 and (datetime.now() - vehicle_entries.iloc[-1]["Date"]).total_seconds() > 86400:
58
+ # Send an alert email
59
+ send_alert_email(number_plate)
60
+ except FileNotFoundError:
61
+ pass
62
+
63
+
64
+ def send_alert_email(number_plate):
65
+ # Set up email server
66
+ server = smtplib.SMTP("smtp.gmail.com", 587)
67
+ server.starttls()
68
+ server.login("your_email@gmail.com", "your_password")
69
+
70
+ # Send email
71
+ subject = "Unregistered Vehicle Alert"
72
+ body = f"Unregistered vehicle with number plate {number_plate} has been present for more than 24 hours."
73
+ message = f"Subject: {subject}\n\n{body}"
74
+ server.sendmail("your_email@gmail.com", "recipient_email@gmail.com", message)
75
+ server.quit()
76
+
77
+ def main(image_path):
78
+ image = cv2.imread(image_path)
79
+ number_plates = detect_number_plates(image)
80
+ save_to_excel(number_plates)
81
+ monitor_vehicles(number_plates)
82
+
83
+ # Example usage
84
+ main("/Users/majjikarthikreddy/Downloads/WhatsApp Image 2025-04-10 at 10.29.25.jpeg")