Spaces:
Build error
Build error
File size: 2,085 Bytes
0d70434 6319516 468ede7 6319516 0d70434 6319516 468ede7 6319516 468ede7 6319516 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | import cv2
from PIL import Image
import numpy as np
from datetime import datetime
class VideoService:
def load_video(self, video_path):
"""Load video and return frames."""
cap = cv2.VideoCapture(video_path)
frames = []
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
frames.append(frame)
cap.release()
return frames
def frame_to_pil(self, frame):
"""Convert OpenCV frame to PIL Image."""
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
return Image.fromarray(frame_rgb)
def draw_detections(self, frame, detections):
"""Draw bounding boxes, labels, and timestamp on frame."""
frame_copy = frame.copy()
# Add timestamp overlay
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
cv2.putText(
frame_copy,
timestamp,
(10, 30),
cv2.FONT_HERSHEY_SIMPLEX,
0.7,
(255, 255, 255),
2
)
# Draw bounding boxes and labels for detections
for detection in detections:
score = detection["score"]
label = detection["label"]
box = detection["box"]
x1, y1, x2, y2 = box["xmin"], box["ymin"], box["xmax"], box["ymax"]
cv2.rectangle(frame_copy, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.putText(
frame_copy,
f"{label}: {score:.2f}",
(x1, y1 - 10),
cv2.FONT_HERSHEY_SIMPLEX,
0.5,
(0, 255, 0),
2
)
return frame_copy
def save_video(self, frames, output_path, fps=30):
"""Save frames as a video."""
if not frames:
return
height, width, _ = frames[0].shape
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
out = cv2.VideoWriter(output_path, fourcc, fps, (width, height))
for frame in frames:
out.write(frame)
out.release() |