Commit
·
52d6f05
1
Parent(s):
b3fd29d
Updated code
Browse files- code/tracker.py +389 -0
- code/yolo_detection.py +145 -0
code/tracker.py
ADDED
@@ -0,0 +1,389 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import json
|
3 |
+
import numpy as np
|
4 |
+
from scipy.optimize import linear_sum_assignment
|
5 |
+
import logging
|
6 |
+
from collections import defaultdict
|
7 |
+
|
8 |
+
class PixelBBoxTracker:
|
9 |
+
def __init__(self, max_disappeared=50, max_distance=100, max_pigs=9):
|
10 |
+
self.tracks = {} # Active tracks: {id: {'centroid', 'disappeared', 'bbox'}}
|
11 |
+
self.next_id = 1
|
12 |
+
self.max_disappeared = max_disappeared
|
13 |
+
self.max_distance = max_distance
|
14 |
+
self.max_pigs = max_pigs
|
15 |
+
self.disappeared_tracks = {} # Temporarily lost tracks
|
16 |
+
self.track_history = defaultdict(list) # Store recent positions
|
17 |
+
self.ambiguous_threshold = 0.1 # Cost difference threshold for ambiguity
|
18 |
+
self.iou_weight = 0.4 # Weight for IoU in cost calculation
|
19 |
+
self.centroid_weight = 0.4 # Weight for centroid distance
|
20 |
+
self.area_weight = 0.2 # Weight for area similarity
|
21 |
+
|
22 |
+
def _get_centroid(self, bbox):
|
23 |
+
x, y, w, h = bbox
|
24 |
+
return np.array([x + w/2, y + h/2])
|
25 |
+
|
26 |
+
def _calculate_area(self, bbox):
|
27 |
+
_, _, w, h = bbox
|
28 |
+
return w * h
|
29 |
+
|
30 |
+
def _area_similarity(self, area1, area2):
|
31 |
+
"""Calculate normalized area similarity (1.0 = identical areas)"""
|
32 |
+
if area1 == 0 or area2 == 0:
|
33 |
+
return 0.0
|
34 |
+
min_area = min(area1, area2)
|
35 |
+
max_area = max(area1, area2)
|
36 |
+
return min_area / max_area
|
37 |
+
|
38 |
+
def _bbox_iou(self, box1, box2):
|
39 |
+
"""Calculate Intersection over Union (IoU) of two bounding boxes"""
|
40 |
+
# Box format: [x, y, w, h]
|
41 |
+
x1, y1, w1, h1 = box1
|
42 |
+
x2, y2, w2, h2 = box2
|
43 |
+
|
44 |
+
# Calculate intersection coordinates
|
45 |
+
xi1 = max(x1, x2)
|
46 |
+
yi1 = max(y1, y2)
|
47 |
+
xi2 = min(x1 + w1, x2 + w2)
|
48 |
+
yi2 = min(y1 + h1, y2 + h2)
|
49 |
+
|
50 |
+
# Calculate intersection area
|
51 |
+
inter_width = max(0, xi2 - xi1)
|
52 |
+
inter_height = max(0, yi2 - yi1)
|
53 |
+
inter_area = inter_width * inter_height
|
54 |
+
|
55 |
+
# Calculate union area
|
56 |
+
box1_area = w1 * h1
|
57 |
+
box2_area = w2 * h2
|
58 |
+
union_area = box1_area + box2_area - inter_area
|
59 |
+
|
60 |
+
return inter_area / union_area if union_area > 0 else 0.0
|
61 |
+
|
62 |
+
def _calculate_cost(self, track, detection_bbox):
|
63 |
+
"""Calculate combined cost using centroid distance, IoU, and area similarity"""
|
64 |
+
# Get track information
|
65 |
+
last_centroid = track["centroid"]
|
66 |
+
last_bbox = track["bbox"]
|
67 |
+
track_area = self._calculate_area(last_bbox)
|
68 |
+
|
69 |
+
# Detection information
|
70 |
+
detection_centroid = self._get_centroid(detection_bbox)
|
71 |
+
detection_area = self._calculate_area(detection_bbox)
|
72 |
+
|
73 |
+
# Calculate components
|
74 |
+
centroid_distance = np.linalg.norm(detection_centroid - last_centroid)
|
75 |
+
normalized_distance = min(centroid_distance / self.max_distance, 1.0)
|
76 |
+
|
77 |
+
iou = self._bbox_iou(last_bbox, detection_bbox)
|
78 |
+
iou_term = 1.0 - iou
|
79 |
+
|
80 |
+
area_sim = self._area_similarity(track_area, detection_area)
|
81 |
+
area_term = 1.0 - area_sim
|
82 |
+
|
83 |
+
# Combine with weights
|
84 |
+
cost = (self.centroid_weight * normalized_distance +
|
85 |
+
self.iou_weight * iou_term +
|
86 |
+
self.area_weight * area_term)
|
87 |
+
|
88 |
+
return cost
|
89 |
+
|
90 |
+
def update(self, detections):
|
91 |
+
# Filter out small bounding boxes
|
92 |
+
detections = [d for d in detections if self._calculate_area(d['bbox']) >= 100]
|
93 |
+
|
94 |
+
# Get current frame information
|
95 |
+
current_centroids = [self._get_centroid(d['bbox']) for d in detections]
|
96 |
+
detection_bboxes = [d['bbox'] for d in detections]
|
97 |
+
track_ids = [-1] * len(detections) # Initialize all as unmatched
|
98 |
+
|
99 |
+
# Stage 1: Match existing tracks to detections
|
100 |
+
if self.tracks and detections:
|
101 |
+
track_ids_list = list(self.tracks.keys())
|
102 |
+
cost_matrix = np.full((len(track_ids_list), len(detections)), 10.0) # High default cost
|
103 |
+
|
104 |
+
# Calculate cost matrix
|
105 |
+
for t_idx, track_id in enumerate(track_ids_list):
|
106 |
+
track = self.tracks[track_id]
|
107 |
+
for d_idx, bbox in enumerate(detection_bboxes):
|
108 |
+
cost = self._calculate_cost(track, bbox)
|
109 |
+
centroid_distance = np.linalg.norm(current_centroids[d_idx] - track["centroid"])
|
110 |
+
|
111 |
+
# Only consider if within max distance
|
112 |
+
if centroid_distance <= self.max_distance:
|
113 |
+
cost_matrix[t_idx, d_idx] = cost
|
114 |
+
|
115 |
+
# Apply Hungarian algorithm for optimal matching
|
116 |
+
try:
|
117 |
+
row_ind, col_ind = linear_sum_assignment(cost_matrix)
|
118 |
+
|
119 |
+
# Process matches
|
120 |
+
for t_idx, d_idx in zip(row_ind, col_ind):
|
121 |
+
if cost_matrix[t_idx, d_idx] < 0.8: # Only accept good matches
|
122 |
+
track_id = track_ids_list[t_idx]
|
123 |
+
track = self.tracks[track_id]
|
124 |
+
bbox = detection_bboxes[d_idx]
|
125 |
+
|
126 |
+
# Update track information
|
127 |
+
track["centroid"] = current_centroids[d_idx]
|
128 |
+
track["bbox"] = bbox
|
129 |
+
track["disappeared"] = 0
|
130 |
+
self.track_history[track_id].append(current_centroids[d_idx])
|
131 |
+
|
132 |
+
# Assign track ID to detection
|
133 |
+
track_ids[d_idx] = track_id
|
134 |
+
except Exception as e:
|
135 |
+
pass
|
136 |
+
|
137 |
+
# Stage 2: Handle unmatched detections
|
138 |
+
unmatched_detections = [d_idx for d_idx, tid in enumerate(track_ids) if tid == -1]
|
139 |
+
regained_ids = []
|
140 |
+
new_track_ids = []
|
141 |
+
|
142 |
+
for d_idx in unmatched_detections:
|
143 |
+
centroid = current_centroids[d_idx]
|
144 |
+
bbox = detection_bboxes[d_idx]
|
145 |
+
|
146 |
+
# Try to regain from disappeared tracks
|
147 |
+
best_match_id = None
|
148 |
+
min_cost = float('inf')
|
149 |
+
|
150 |
+
for track_id, track in self.disappeared_tracks.items():
|
151 |
+
cost = self._calculate_cost(track, bbox)
|
152 |
+
centroid_distance = np.linalg.norm(centroid - track["centroid"])
|
153 |
+
|
154 |
+
if cost < min_cost and centroid_distance <= self.max_distance:
|
155 |
+
min_cost = cost
|
156 |
+
best_match_id = track_id
|
157 |
+
|
158 |
+
# Regain track if found
|
159 |
+
if best_match_id and len(self.tracks) < self.max_pigs:
|
160 |
+
# Update track information
|
161 |
+
self.tracks[best_match_id] = {
|
162 |
+
"centroid": centroid,
|
163 |
+
"bbox": bbox,
|
164 |
+
"disappeared": 0
|
165 |
+
}
|
166 |
+
self.track_history[best_match_id].append(centroid)
|
167 |
+
track_ids[d_idx] = best_match_id
|
168 |
+
regained_ids.append(best_match_id)
|
169 |
+
del self.disappeared_tracks[best_match_id]
|
170 |
+
|
171 |
+
# Create new track if no match and under capacity
|
172 |
+
elif len(self.tracks) < self.max_pigs:
|
173 |
+
new_id = self.next_id
|
174 |
+
self.tracks[new_id] = {
|
175 |
+
"centroid": centroid,
|
176 |
+
"bbox": bbox,
|
177 |
+
"disappeared": 0
|
178 |
+
}
|
179 |
+
self.track_history[new_id].append(centroid)
|
180 |
+
track_ids[d_idx] = new_id
|
181 |
+
new_track_ids.append(new_id)
|
182 |
+
self.next_id += 1
|
183 |
+
|
184 |
+
# Stage 3: Update disappeared tracks
|
185 |
+
lost_track_ids = []
|
186 |
+
|
187 |
+
# Check all active tracks
|
188 |
+
for track_id in list(self.tracks.keys()):
|
189 |
+
# If track wasn't matched
|
190 |
+
if track_id not in track_ids:
|
191 |
+
self.tracks[track_id]["disappeared"] += 1
|
192 |
+
|
193 |
+
# Move to disappeared if disappeared too long
|
194 |
+
if self.tracks[track_id]["disappeared"] > self.max_disappeared:
|
195 |
+
self.disappeared_tracks[track_id] = self.tracks[track_id]
|
196 |
+
del self.tracks[track_id]
|
197 |
+
lost_track_ids.append(track_id)
|
198 |
+
# Keep history for potential regain
|
199 |
+
|
200 |
+
# Stage 4: Cap at max pigs
|
201 |
+
if len(self.tracks) > self.max_pigs:
|
202 |
+
# Remove oldest lost track (highest disappeared count)
|
203 |
+
oldest_id = None
|
204 |
+
max_disappeared = -1
|
205 |
+
for track_id, track in self.tracks.items():
|
206 |
+
if track["disappeared"] > max_disappeared:
|
207 |
+
max_disappeared = track["disappeared"]
|
208 |
+
oldest_id = track_id
|
209 |
+
|
210 |
+
if oldest_id:
|
211 |
+
self.disappeared_tracks[oldest_id] = self.tracks[oldest_id]
|
212 |
+
del self.tracks[oldest_id]
|
213 |
+
lost_track_ids.append(oldest_id)
|
214 |
+
|
215 |
+
# Return only current detections with track IDs
|
216 |
+
all_track_ids = []
|
217 |
+
all_bboxes = []
|
218 |
+
|
219 |
+
for i, tid in enumerate(track_ids):
|
220 |
+
if tid != -1:
|
221 |
+
all_track_ids.append(tid)
|
222 |
+
all_bboxes.append(detection_bboxes[i])
|
223 |
+
|
224 |
+
return all_track_ids, all_bboxes, regained_ids, lost_track_ids
|
225 |
+
|
226 |
+
|
227 |
+
# The rest of your code remains the same (read_json_file, save_json_file, setup_logger, and main)
|
228 |
+
|
229 |
+
def read_json_file(json_path):
|
230 |
+
with open(json_path, 'r') as f:
|
231 |
+
data = json.load(f)
|
232 |
+
|
233 |
+
frame_data = {}
|
234 |
+
for item in data:
|
235 |
+
frame_id = item['frame_id']
|
236 |
+
det = {
|
237 |
+
"bbox": item["bbox"],
|
238 |
+
"area": item.get("area", 0)
|
239 |
+
}
|
240 |
+
|
241 |
+
if frame_id not in frame_data:
|
242 |
+
frame_data[frame_id] = {
|
243 |
+
"frame_width": item.get("frame_width", 1280),
|
244 |
+
"frame_height": item.get("frame_height", 720),
|
245 |
+
"detections": []
|
246 |
+
}
|
247 |
+
|
248 |
+
frame_data[frame_id]["detections"].append(det)
|
249 |
+
|
250 |
+
return frame_data
|
251 |
+
|
252 |
+
|
253 |
+
def save_json_file(output_path, results):
|
254 |
+
coco_output = {
|
255 |
+
"images": [],
|
256 |
+
"annotations": [],
|
257 |
+
"categories": [{"id": 1, "name": "pig"}]
|
258 |
+
}
|
259 |
+
|
260 |
+
annotation_id = 1
|
261 |
+
for frame_id in sorted(results.keys()):
|
262 |
+
frame = results[frame_id]
|
263 |
+
width = frame["frame_width"]
|
264 |
+
height = frame["frame_height"]
|
265 |
+
file_name = f"{frame_id:08d}.jpg"
|
266 |
+
|
267 |
+
coco_output["images"].append({
|
268 |
+
"id": frame_id,
|
269 |
+
"file_name": file_name,
|
270 |
+
"width": width,
|
271 |
+
"height": height
|
272 |
+
})
|
273 |
+
|
274 |
+
for det in frame["detections"]:
|
275 |
+
x, y, w, h = det["bbox"]
|
276 |
+
area = det.get("area", w * h)
|
277 |
+
coco_output["annotations"].append({
|
278 |
+
"id": annotation_id,
|
279 |
+
"image_id": frame_id,
|
280 |
+
"category_id": 1,
|
281 |
+
"bbox": [x, y, w, h],
|
282 |
+
"track_id": det["track_id"],
|
283 |
+
"area": area,
|
284 |
+
"iscrowd": 0
|
285 |
+
})
|
286 |
+
annotation_id += 1
|
287 |
+
|
288 |
+
with open(output_path, 'w') as f:
|
289 |
+
json.dump(coco_output, f, indent=2)
|
290 |
+
|
291 |
+
|
292 |
+
def setup_logger(log_path):
|
293 |
+
logger = logging.getLogger('tracking_logger')
|
294 |
+
logger.setLevel(logging.INFO)
|
295 |
+
|
296 |
+
for handler in logger.handlers[:]:
|
297 |
+
logger.removeHandler(handler)
|
298 |
+
|
299 |
+
file_handler = logging.FileHandler(log_path)
|
300 |
+
file_handler.setLevel(logging.INFO)
|
301 |
+
|
302 |
+
console_handler = logging.StreamHandler()
|
303 |
+
console_handler.setLevel(logging.INFO)
|
304 |
+
|
305 |
+
formatter = logging.Formatter('%(asctime)s - %(message)s')
|
306 |
+
file_handler.setFormatter(formatter)
|
307 |
+
console_handler.setFormatter(formatter)
|
308 |
+
|
309 |
+
logger.addHandler(file_handler)
|
310 |
+
logger.addHandler(console_handler)
|
311 |
+
|
312 |
+
return logger
|
313 |
+
|
314 |
+
|
315 |
+
if __name__ == "__main__":
|
316 |
+
input_dir = "path/to/your/detected_json"
|
317 |
+
output_dir = "path/to/your/tracked_json"
|
318 |
+
log_dir = "path/to/your/tracking_log"
|
319 |
+
os.makedirs(output_dir, exist_ok=True)
|
320 |
+
os.makedirs(log_dir, exist_ok=True)
|
321 |
+
|
322 |
+
for file_name in os.listdir(input_dir):
|
323 |
+
if not file_name.endswith(".json"):
|
324 |
+
continue
|
325 |
+
|
326 |
+
input_path = os.path.join(input_dir, file_name)
|
327 |
+
output_path = os.path.join(output_dir, file_name.replace("detection.json", "tracked.json"))
|
328 |
+
log_path = os.path.join(log_dir, file_name.replace(".json", ".log"))
|
329 |
+
|
330 |
+
logger = setup_logger(log_path)
|
331 |
+
logger.info(f"Starting processing for {file_name}")
|
332 |
+
|
333 |
+
frames = read_json_file(input_path)
|
334 |
+
tracker = PixelBBoxTracker(max_disappeared=180, max_distance=125, max_pigs=9)
|
335 |
+
results = {}
|
336 |
+
detection_counts = defaultdict(list)
|
337 |
+
|
338 |
+
for frame_id in sorted(frames.keys()):
|
339 |
+
frame = frames[frame_id]
|
340 |
+
detections = frame["detections"]
|
341 |
+
|
342 |
+
# Remove original track ID
|
343 |
+
for det in detections:
|
344 |
+
det.pop("track_id", None)
|
345 |
+
|
346 |
+
# Process tracking
|
347 |
+
track_ids, bboxes, regained_ids, lost_track_ids = tracker.update(detections)
|
348 |
+
|
349 |
+
# Prepare detections for this frame
|
350 |
+
frame_detections = []
|
351 |
+
for track_id, bbox in zip(track_ids, bboxes):
|
352 |
+
frame_detections.append({
|
353 |
+
"bbox": bbox,
|
354 |
+
"track_id": track_id,
|
355 |
+
"area": bbox[2] * bbox[3] # w * h
|
356 |
+
})
|
357 |
+
|
358 |
+
# Store results
|
359 |
+
results[frame_id] = {
|
360 |
+
"frame_width": frame["frame_width"],
|
361 |
+
"frame_height": frame["frame_height"],
|
362 |
+
"detections": frame_detections
|
363 |
+
}
|
364 |
+
|
365 |
+
# Logging
|
366 |
+
detection_count = len(frame_detections)
|
367 |
+
detection_counts[detection_count].append(frame_id)
|
368 |
+
|
369 |
+
if detection_count > 9:
|
370 |
+
logger.warning(f"Frame {frame_id}: Too many detections ({detection_count}) - capped to 9")
|
371 |
+
elif detection_count < 9:
|
372 |
+
logger.info(f"Frame {frame_id}: Only {detection_count} detections")
|
373 |
+
|
374 |
+
if lost_track_ids:
|
375 |
+
logger.info(f"Frame {frame_id}: Lost tracks - {', '.join(map(str, lost_track_ids))}")
|
376 |
+
|
377 |
+
if regained_ids:
|
378 |
+
logger.info(f"Frame {frame_id}: Regained tracks - {', '.join(map(str, regained_ids))}")
|
379 |
+
|
380 |
+
# Save detection count statistics
|
381 |
+
logger.info("\nDetection Count Statistics:")
|
382 |
+
for count, frames in sorted(detection_counts.items()):
|
383 |
+
logger.info(f"{count} detections: {len(frames)} frames")
|
384 |
+
|
385 |
+
# Save results
|
386 |
+
save_json_file(output_path, results)
|
387 |
+
logger.info(f"Tracking complete. Output saved to {output_path}\n")
|
388 |
+
|
389 |
+
print("All files processed successfully.")
|
code/yolo_detection.py
ADDED
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
|
3 |
+
import cv2
|
4 |
+
import numpy as np
|
5 |
+
from pathlib import Path
|
6 |
+
from ultralytics import YOLO
|
7 |
+
from collections import defaultdict
|
8 |
+
import time
|
9 |
+
import json
|
10 |
+
|
11 |
+
|
12 |
+
# Configuration
|
13 |
+
INPUT_VIDEOS_DIR = "datasets/usplf/tracking/pen2_cam2" # Directory containing input videos
|
14 |
+
OUTPUT_DIR = "datasets/usplf/tracking/detected_json/pen2_cam2"
|
15 |
+
# POLYGON_VERTICES = np.array([[89,139], [325,57], [594, 6], [1128, 29], [1129, 364], [1031, 717],[509, 653],[287, 583], [100, 506],[74, 321]]) # Pen2 Cam1 polygon coordinates
|
16 |
+
POLYGON_VERTICES = np.array([[179, 3], [844, 8], [1151, 137], [1151, 316], [1135, 486], [995, 531],[801, 592],[278, 711], [167, 325]]) # Pen2 Cam2 polygon coordinates
|
17 |
+
CONF_THRESH = 0.55 # Confidence threshold
|
18 |
+
# TRACKER_CONFIG = "custom_bytetrack.yaml" # Built-in tracker config
|
19 |
+
|
20 |
+
# Visualization settings
|
21 |
+
SHOW_MASK_OVERLAY = True
|
22 |
+
MASK_ALPHA = 0.3 # Transparency for polygon mask
|
23 |
+
BOX_COLOR = (0, 255, 0) # Green
|
24 |
+
TEXT_COLOR = (255, 255, 255) # White
|
25 |
+
FONT_SCALE = 0.8
|
26 |
+
THICKNESS = 2
|
27 |
+
|
28 |
+
def create_mask(frame_shape):
|
29 |
+
mask = np.zeros(frame_shape[:2], dtype=np.uint8)
|
30 |
+
cv2.fillPoly(mask, [POLYGON_VERTICES], 255)
|
31 |
+
return mask
|
32 |
+
|
33 |
+
def draw_visuals_detection(frame, mask, detections, frame_count, fps):
|
34 |
+
if SHOW_MASK_OVERLAY:
|
35 |
+
overlay = frame.copy()
|
36 |
+
cv2.fillPoly(overlay, [POLYGON_VERTICES], (0, 100, 0))
|
37 |
+
cv2.addWeighted(overlay, MASK_ALPHA, frame, 1 - MASK_ALPHA, 0, frame)
|
38 |
+
|
39 |
+
for det in detections:
|
40 |
+
x, y, w, h = det['bbox']
|
41 |
+
conf = det['confidence']
|
42 |
+
|
43 |
+
# Draw bounding box
|
44 |
+
cv2.rectangle(
|
45 |
+
frame,
|
46 |
+
(int(x - w / 2), int(y - h / 2)),
|
47 |
+
(int(x + w / 2), int(y + h / 2)),
|
48 |
+
BOX_COLOR, THICKNESS
|
49 |
+
)
|
50 |
+
|
51 |
+
# Display confidence
|
52 |
+
cv2.putText(frame, f"{conf:.2f}",
|
53 |
+
(int(x - w / 2), int(y - h / 2) - 10),
|
54 |
+
cv2.FONT_HERSHEY_SIMPLEX, FONT_SCALE, TEXT_COLOR, THICKNESS)
|
55 |
+
|
56 |
+
# Overlay info
|
57 |
+
cv2.putText(frame, f"Frame: {frame_count}", (10, 30),
|
58 |
+
cv2.FONT_HERSHEY_SIMPLEX, FONT_SCALE, TEXT_COLOR, THICKNESS)
|
59 |
+
cv2.putText(frame, f"FPS: {fps:.1f}", (10, 60),
|
60 |
+
cv2.FONT_HERSHEY_SIMPLEX, FONT_SCALE, TEXT_COLOR, THICKNESS)
|
61 |
+
cv2.putText(frame, f"Pigs: {len(detections)}", (10, 90),
|
62 |
+
cv2.FONT_HERSHEY_SIMPLEX, FONT_SCALE, TEXT_COLOR, THICKNESS)
|
63 |
+
|
64 |
+
return frame
|
65 |
+
|
66 |
+
|
67 |
+
def process_video(video_path, output_path):
|
68 |
+
model = YOLO("trained_model_weight/pig_detect/yolo/pig_detect_pen2_best.pt")
|
69 |
+
cap = cv2.VideoCapture(str(video_path))
|
70 |
+
frame_count = 0
|
71 |
+
results_list = []
|
72 |
+
fps_history = []
|
73 |
+
|
74 |
+
# Video properties
|
75 |
+
frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
76 |
+
frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
77 |
+
mask = create_mask((frame_height, frame_width))
|
78 |
+
|
79 |
+
win_name = f"Pig Detection - {video_path.name}"
|
80 |
+
cv2.namedWindow(win_name, cv2.WINDOW_NORMAL)
|
81 |
+
|
82 |
+
while cap.isOpened():
|
83 |
+
start_time = time.time()
|
84 |
+
success, frame = cap.read()
|
85 |
+
if not success:
|
86 |
+
break
|
87 |
+
|
88 |
+
masked_frame = cv2.bitwise_and(frame, frame, mask=mask)
|
89 |
+
|
90 |
+
# Detection instead of tracking
|
91 |
+
results = model.predict(
|
92 |
+
masked_frame,
|
93 |
+
conf=CONF_THRESH,
|
94 |
+
verbose=False
|
95 |
+
)
|
96 |
+
|
97 |
+
detections = []
|
98 |
+
if results[0].boxes is not None:
|
99 |
+
boxes = results[0].boxes.xywh.cpu().numpy()
|
100 |
+
scores = results[0].boxes.conf.cpu().numpy()
|
101 |
+
|
102 |
+
for box, score in zip(boxes, scores):
|
103 |
+
x, y, w, h = box
|
104 |
+
detections.append({"confidence": float(score), "bbox": [x, y, w, h]})
|
105 |
+
results_list.append({
|
106 |
+
"frame_id": frame_count,
|
107 |
+
"frame_width": frame_width,
|
108 |
+
"frame_height": frame_height,
|
109 |
+
"confidence": float(score),
|
110 |
+
"bbox": [float(x), float(y), float(w), float(h)],
|
111 |
+
"area": float(w * h)
|
112 |
+
})
|
113 |
+
|
114 |
+
# FPS calculation
|
115 |
+
processing_time = time.time() - start_time
|
116 |
+
fps = 1 / processing_time
|
117 |
+
fps_history.append(fps)
|
118 |
+
if len(fps_history) > 10:
|
119 |
+
fps = np.mean(fps_history[-10:])
|
120 |
+
|
121 |
+
# Draw visuals
|
122 |
+
display_frame = draw_visuals_detection(frame.copy(), mask, detections, frame_count, fps)
|
123 |
+
cv2.imshow(win_name, display_frame)
|
124 |
+
if cv2.waitKey(1) & 0xFF == ord('q'):
|
125 |
+
break
|
126 |
+
|
127 |
+
frame_count += 1
|
128 |
+
|
129 |
+
cap.release()
|
130 |
+
cv2.destroyWindow(win_name)
|
131 |
+
|
132 |
+
# Save JSON
|
133 |
+
output_file = output_path / f"{video_path.stem}_detection.json"
|
134 |
+
with open(output_file, 'w') as f:
|
135 |
+
json.dump(results_list, f, indent=2)
|
136 |
+
|
137 |
+
if __name__ == "__main__":
|
138 |
+
input_dir = Path(INPUT_VIDEOS_DIR)
|
139 |
+
output_dir = Path(OUTPUT_DIR)
|
140 |
+
output_dir.mkdir(exist_ok=True)
|
141 |
+
|
142 |
+
for video_file in input_dir.glob("*.mp4"):
|
143 |
+
print(f"Processing {video_file.name}...")
|
144 |
+
process_video(video_file, output_dir)
|
145 |
+
cv2.destroyAllWindows()
|