Gilt_tracking_dataset / code /yolo_detection.py
anilbhujel's picture
Updated code
52d6f05
raw
history blame
5.02 kB
import cv2
import numpy as np
from pathlib import Path
from ultralytics import YOLO
from collections import defaultdict
import time
import json
# Configuration
INPUT_VIDEOS_DIR = "datasets/usplf/tracking/pen2_cam2" # Directory containing input videos
OUTPUT_DIR = "datasets/usplf/tracking/detected_json/pen2_cam2"
# 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
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
CONF_THRESH = 0.55 # Confidence threshold
# TRACKER_CONFIG = "custom_bytetrack.yaml" # Built-in tracker config
# Visualization settings
SHOW_MASK_OVERLAY = True
MASK_ALPHA = 0.3 # Transparency for polygon mask
BOX_COLOR = (0, 255, 0) # Green
TEXT_COLOR = (255, 255, 255) # White
FONT_SCALE = 0.8
THICKNESS = 2
def create_mask(frame_shape):
mask = np.zeros(frame_shape[:2], dtype=np.uint8)
cv2.fillPoly(mask, [POLYGON_VERTICES], 255)
return mask
def draw_visuals_detection(frame, mask, detections, frame_count, fps):
if SHOW_MASK_OVERLAY:
overlay = frame.copy()
cv2.fillPoly(overlay, [POLYGON_VERTICES], (0, 100, 0))
cv2.addWeighted(overlay, MASK_ALPHA, frame, 1 - MASK_ALPHA, 0, frame)
for det in detections:
x, y, w, h = det['bbox']
conf = det['confidence']
# Draw bounding box
cv2.rectangle(
frame,
(int(x - w / 2), int(y - h / 2)),
(int(x + w / 2), int(y + h / 2)),
BOX_COLOR, THICKNESS
)
# Display confidence
cv2.putText(frame, f"{conf:.2f}",
(int(x - w / 2), int(y - h / 2) - 10),
cv2.FONT_HERSHEY_SIMPLEX, FONT_SCALE, TEXT_COLOR, THICKNESS)
# Overlay info
cv2.putText(frame, f"Frame: {frame_count}", (10, 30),
cv2.FONT_HERSHEY_SIMPLEX, FONT_SCALE, TEXT_COLOR, THICKNESS)
cv2.putText(frame, f"FPS: {fps:.1f}", (10, 60),
cv2.FONT_HERSHEY_SIMPLEX, FONT_SCALE, TEXT_COLOR, THICKNESS)
cv2.putText(frame, f"Pigs: {len(detections)}", (10, 90),
cv2.FONT_HERSHEY_SIMPLEX, FONT_SCALE, TEXT_COLOR, THICKNESS)
return frame
def process_video(video_path, output_path):
model = YOLO("trained_model_weight/pig_detect/yolo/pig_detect_pen2_best.pt")
cap = cv2.VideoCapture(str(video_path))
frame_count = 0
results_list = []
fps_history = []
# Video properties
frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
mask = create_mask((frame_height, frame_width))
win_name = f"Pig Detection - {video_path.name}"
cv2.namedWindow(win_name, cv2.WINDOW_NORMAL)
while cap.isOpened():
start_time = time.time()
success, frame = cap.read()
if not success:
break
masked_frame = cv2.bitwise_and(frame, frame, mask=mask)
# Detection instead of tracking
results = model.predict(
masked_frame,
conf=CONF_THRESH,
verbose=False
)
detections = []
if results[0].boxes is not None:
boxes = results[0].boxes.xywh.cpu().numpy()
scores = results[0].boxes.conf.cpu().numpy()
for box, score in zip(boxes, scores):
x, y, w, h = box
detections.append({"confidence": float(score), "bbox": [x, y, w, h]})
results_list.append({
"frame_id": frame_count,
"frame_width": frame_width,
"frame_height": frame_height,
"confidence": float(score),
"bbox": [float(x), float(y), float(w), float(h)],
"area": float(w * h)
})
# FPS calculation
processing_time = time.time() - start_time
fps = 1 / processing_time
fps_history.append(fps)
if len(fps_history) > 10:
fps = np.mean(fps_history[-10:])
# Draw visuals
display_frame = draw_visuals_detection(frame.copy(), mask, detections, frame_count, fps)
cv2.imshow(win_name, display_frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
frame_count += 1
cap.release()
cv2.destroyWindow(win_name)
# Save JSON
output_file = output_path / f"{video_path.stem}_detection.json"
with open(output_file, 'w') as f:
json.dump(results_list, f, indent=2)
if __name__ == "__main__":
input_dir = Path(INPUT_VIDEOS_DIR)
output_dir = Path(OUTPUT_DIR)
output_dir.mkdir(exist_ok=True)
for video_file in input_dir.glob("*.mp4"):
print(f"Processing {video_file.name}...")
process_video(video_file, output_dir)
cv2.destroyAllWindows()