102 lines
3.0 KiB
Python
102 lines
3.0 KiB
Python
import argparse
|
|
import os
|
|
|
|
from inference.models.utils import get_roboflow_model
|
|
from tqdm import tqdm
|
|
|
|
import supervision as sv
|
|
|
|
|
|
def process_video(
|
|
roboflow_api_key: str,
|
|
model_id: str,
|
|
source_video_path: str,
|
|
target_video_path: str,
|
|
confidence_threshold: float = 0.3,
|
|
iou_threshold: float = 0.7,
|
|
) -> None:
|
|
model = get_roboflow_model(model_id=model_id, api_key=roboflow_api_key)
|
|
|
|
tracker = sv.ByteTrack()
|
|
box_annotator = sv.BoundingBoxAnnotator()
|
|
label_annotator = sv.LabelAnnotator()
|
|
frame_generator = sv.get_video_frames_generator(source_path=source_video_path)
|
|
video_info = sv.VideoInfo.from_video_path(video_path=source_video_path)
|
|
|
|
with sv.VideoSink(target_path=target_video_path, video_info=video_info) as sink:
|
|
for frame in tqdm(frame_generator, total=video_info.total_frames):
|
|
results = model.infer(
|
|
frame, confidence=confidence_threshold, iou_threshold=iou_threshold
|
|
)[0]
|
|
detections = sv.Detections.from_inference(results)
|
|
detections = tracker.update_with_detections(detections)
|
|
|
|
annotated_frame = box_annotator.annotate(
|
|
scene=frame.copy(), detections=detections
|
|
)
|
|
|
|
annotated_labeled_frame = label_annotator.annotate(
|
|
scene=annotated_frame, detections=detections
|
|
)
|
|
|
|
sink.write_frame(frame=annotated_labeled_frame)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
parser = argparse.ArgumentParser(
|
|
description="Video Processing with Inference and ByteTrack"
|
|
)
|
|
parser.add_argument(
|
|
"--model_id",
|
|
default="yolov8x-1280",
|
|
help="Roboflow model ID",
|
|
type=str,
|
|
)
|
|
parser.add_argument(
|
|
"--source_video_path",
|
|
required=True,
|
|
help="Path to the source video file",
|
|
type=str,
|
|
)
|
|
parser.add_argument(
|
|
"--target_video_path",
|
|
required=True,
|
|
help="Path to the target video file (output)",
|
|
type=str,
|
|
)
|
|
parser.add_argument(
|
|
"--confidence_threshold",
|
|
default=0.3,
|
|
help="Confidence threshold for the model",
|
|
type=float,
|
|
)
|
|
parser.add_argument(
|
|
"--iou_threshold", default=0.7, help="IOU threshold for the model", type=float
|
|
)
|
|
parser.add_argument(
|
|
"--roboflow_api_key",
|
|
default=None,
|
|
help="Roboflow API key",
|
|
type=str,
|
|
)
|
|
|
|
args = parser.parse_args()
|
|
|
|
api_key = args.roboflow_api_key
|
|
api_key = os.environ.get("ROBOFLOW_API_KEY", api_key)
|
|
if api_key is None:
|
|
raise ValueError(
|
|
"Roboflow API key is missing. Please provide it as an argument or set the "
|
|
"ROBOFLOW_API_KEY environment variable."
|
|
)
|
|
args.roboflow_api_key = api_key
|
|
|
|
process_video(
|
|
roboflow_api_key=args.roboflow_api_key,
|
|
model_id=args.model_id,
|
|
source_video_path=args.source_video_path,
|
|
target_video_path=args.target_video_path,
|
|
confidence_threshold=args.confidence_threshold,
|
|
iou_threshold=args.iou_threshold,
|
|
)
|