Skip to content

Commit ae92257

Browse files
Add files via upload
midpoint of bottom: (xc,yc)
1 parent c3f12c2 commit ae92257

File tree

7 files changed

+326
-0
lines changed

7 files changed

+326
-0
lines changed

YOLO_Tracking.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import cv2
2+
import torch
3+
import numpy as np
4+
from ultralytics import YOLO
5+
6+
7+
model=YOLO('yolov8s.pt')
8+
9+
10+
sample_vids = ['CCTV_720p.mov', 'CCTV_1080p.mov', 'peopleCount.mp4']
11+
12+
13+
14+
15+
for vid in sample_vids:
16+
# Capture video
17+
cap = cv2.VideoCapture('SampleVideos/'+vid)
18+
19+
while cap.isOpened():
20+
ret, frame = cap.read()
21+
if not ret:
22+
break
23+
24+
# Preprocess and model inference
25+
results = model(frame)
26+
27+
# Filter for person class and extract midpoints
28+
midpoints = []
29+
for x1, y1, x2, y2, conf, cls in results.xyxy[0].numpy():
30+
if int(cls) == 0: # Person class
31+
midpoint_x = (x1 + x2) / 2
32+
midpoint_y = y2
33+
midpoints.append((midpoint_x, midpoint_y))
34+
35+
# Further processing with midpoints
36+
37+
cap.release()
38+
cv2.destroyAllWindows()

coco.txt

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
person
2+
bicycle
3+
car
4+
motorcycle
5+
airplane
6+
bus
7+
train
8+
truck
9+
boat
10+
traffic light
11+
fire hydrant
12+
stop sign
13+
parking meter
14+
bench
15+
bird
16+
cat
17+
dog
18+
horse
19+
sheep
20+
cow
21+
elephant
22+
bear
23+
zebra
24+
giraffe
25+
backpack
26+
umbrella
27+
handbag
28+
tie
29+
suitcase
30+
frisbee
31+
skis
32+
snowboard
33+
sports ball
34+
kite
35+
baseball bat
36+
baseball glove
37+
skateboard
38+
surfboard
39+
tennis racket
40+
bottle
41+
wine glass
42+
cup
43+
fork
44+
knife
45+
spoon
46+
bowl
47+
banana
48+
apple
49+
sandwich
50+
orange
51+
broccoli
52+
carrot
53+
hot dog
54+
pizza
55+
donut
56+
cake
57+
chair
58+
couch
59+
potted plant
60+
bed
61+
dining table
62+
toilet
63+
tv
64+
laptop
65+
mouse
66+
remote
67+
keyboard
68+
cell phone
69+
microwave
70+
oven
71+
toaster
72+
sink
73+
refrigerator
74+
book
75+
clock
76+
vase
77+
scissors
78+
teddy bear
79+
hair drier
80+
toothbrush

coco_person.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
person

main.py

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
import cv2
2+
import pandas as pd
3+
import numpy as np
4+
from ultralytics import YOLO
5+
6+
7+
model=YOLO('yolov8s.pt')
8+
9+
sample_vids = ['CCTV_720p.mov', 'CCTV_1080p.mov', 'peopleCount.mp4']
10+
11+
vid = 'SampleVideos/' + sample_vids[1]
12+
13+
area1=[(312,388),(289,390),(474,469),(497,462)]
14+
15+
area2=[(279,392),(250,397),(423,477),(454,469)]
16+
def RGB(event, x, y, flags, param):
17+
if event == cv2.EVENT_MOUSEMOVE :
18+
colorsBGR = [x, y]
19+
print(colorsBGR)
20+
21+
22+
cv2.namedWindow('RGB')
23+
cv2.setMouseCallback('RGB', RGB)
24+
25+
cap=cv2.VideoCapture(vid)
26+
27+
28+
my_file = open("coco.txt", "r")
29+
data = my_file.read()
30+
class_list = data.split("\n")
31+
#print(class_list)
32+
33+
trackers = []
34+
count=0
35+
36+
while True:
37+
ret, frame = cap.read()
38+
if not ret:
39+
break
40+
count += 1
41+
if count % 2 != 0:
42+
continue
43+
frame = cv2.resize(frame, (1020, 500))
44+
45+
results = model.predict(frame)
46+
47+
# Accessing the boxes, confidences, and class IDs
48+
boxes = results[0].boxes.xyxy
49+
confidences = results[0].boxes.conf
50+
class_ids = results[0].boxes.cls
51+
52+
# Iterating through detections
53+
for i in range(len(boxes)):
54+
box = boxes[i]
55+
confidence = confidences[i]
56+
class_id = class_ids[i]
57+
58+
# Convert class_id to a Python integer
59+
class_id = int(class_id) # or class_id.item() if class_id is a single-element tensor
60+
61+
x1, y1, x2, y2 = map(int, box[:4])
62+
xc = int((x1 + x2) / 2)
63+
yc = y2
64+
65+
c = class_list[class_id]
66+
67+
if 'person' in c:
68+
cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
69+
cv2.putText(frame, str(c), (x1, y1), cv2.FONT_HERSHEY_COMPLEX, 0.5, (255, 255, 255), 1)
70+
cv2.circle(frame, (x1, y1), 5, (0, 0, 255), -1) # Top-left in red
71+
cv2.circle(frame, (x2, y1), 5, (0, 255, 0), -1) # Top-right in green
72+
cv2.circle(frame, (x1, y2), 5, (255, 0, 0), -1) # Bottom-left in blue
73+
cv2.circle(frame, (x2, y2), 5, (255, 255, 0), -1) # Bottom-right in cyan
74+
cv2.circle(frame, (xc, yc), 5, (255, 0, 255), -1) # Bottom-Midpoint in pink
75+
76+
77+
78+
cv2.polylines(frame,[np.array(area1,np.int32)],True,(255,0,0),2)
79+
cv2.putText(frame,str('1'),(504,471),cv2.FONT_HERSHEY_COMPLEX,(0.5),(0,0,0),1)
80+
81+
cv2.polylines(frame,[np.array(area2,np.int32)],True,(255,0,0),2)
82+
cv2.putText(frame,str('2'),(466,485),cv2.FONT_HERSHEY_COMPLEX,(0.5),(0,0,0),1)
83+
84+
cv2.imshow("RGB", frame)
85+
if cv2.waitKey(1)&0xFF==27:
86+
break
87+
88+
cap.release()
89+
cv2.destroyAllWindows()
90+

peopleTracking.py

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
import cv2
2+
import numpy as np
3+
import time
4+
5+
# Load YOLO
6+
net = cv2.dnn.readNet("yolov3.weights", "yolov3.cfg")
7+
layer_names = net.getLayerNames()
8+
output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
9+
10+
classes = []
11+
with open("coco.names", "r") as f:
12+
classes = [line.strip() for line in f.readlines()]
13+
14+
# Loading camera
15+
cap = cv2.VideoCapture(0)
16+
17+
while True:
18+
_, frame = cap.read()
19+
20+
height, width, channels = frame.shape
21+
22+
# Detecting objects
23+
blob = cv2.dnn.blobFromImage(frame, 0.00392, (416, 416), (0, 0, 0), True, crop=False)
24+
net.setInput(blob)
25+
outs = net.forward(output_layers)
26+
27+
# Showing informations on the screen
28+
class_ids = []
29+
confidences = []
30+
boxes = []
31+
for out in outs:
32+
for detection in out:
33+
scores = detection[5:]
34+
class_id = np.argmax(scores)
35+
confidence = scores[class_id]
36+
if confidence > 0.5:
37+
# Object detected
38+
center_x = int(detection[0] * width)
39+
center_y = int(detection[1] * height)
40+
w = int(detection[2] * width)
41+
h = int(detection[3] * height)
42+
43+
# Rectangle coordinates
44+
x = int(center_x - w / 2)
45+
y = int(center_y - h / 2)
46+
47+
boxes.append([x, y, w, h])
48+
confidences.append(float(confidence))
49+
class_ids.append(class_id)
50+
51+
indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
52+
53+
for i in range(len(boxes)):
54+
if i in indexes:
55+
x, y, w, h = boxes[i]
56+
label = str(classes[class_ids[i]])
57+
if label == "person":
58+
# Draw rectangle for person
59+
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
60+
61+
cv2.imshow("Image", frame)
62+
key = cv2.waitKey(1)
63+
if key == 27: # ESC key to break
64+
break
65+
66+
cap.release()
67+
cv2.destroyAllWindows()

tracker.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import math
2+
3+
4+
class Tracker:
5+
def __init__(self):
6+
# Store the center positions of the objects
7+
self.center_points = {}
8+
# Keep the count of the IDs
9+
# each time a new object id detected, the count will increase by one
10+
self.id_count = 0
11+
12+
13+
def update(self, objects_rect):
14+
# Objects boxes and ids
15+
objects_bbs_ids = []
16+
17+
# Get center point of new object
18+
for rect in objects_rect:
19+
x, y, w, h = rect
20+
cx = (x + x + w) // 2
21+
cy = (y + y + h) // 2
22+
23+
# Find out if that object was detected already
24+
same_object_detected = False
25+
for id, pt in self.center_points.items():
26+
dist = math.hypot(cx - pt[0], cy - pt[1])
27+
28+
if dist < 35:
29+
self.center_points[id] = (cx, cy)
30+
# print(self.center_points)
31+
objects_bbs_ids.append([x, y, w, h, id])
32+
same_object_detected = True
33+
break
34+
35+
# New object is detected we assign the ID to that object
36+
if same_object_detected is False:
37+
self.center_points[self.id_count] = (cx, cy)
38+
objects_bbs_ids.append([x, y, w, h, self.id_count])
39+
self.id_count += 1
40+
41+
# Clean the dictionary by center points to remove IDS not used anymore
42+
new_center_points = {}
43+
for obj_bb_id in objects_bbs_ids:
44+
_, _, _, _, object_id = obj_bb_id
45+
center = self.center_points[object_id]
46+
new_center_points[object_id] = center
47+
48+
# Update dictionary with IDs not used removed
49+
self.center_points = new_center_points.copy()
50+
return objects_bbs_ids

yolov8s.pt

21.5 MB
Binary file not shown.

0 commit comments

Comments
 (0)