real-time-vision-scripts / real-time-det.py
ariG23498's picture
ariG23498 HF Staff
Update real-time-det.py
4b16a70 verified
Raw
History Blame Contribute Delete
1.56 kB
# /// script
# dependencies = [
# "transformers",
# "torch",
# "opencv-python",
# "Pillow",
# ]
# ///
import time
import cv2
import torch
from transformers import AutoImageProcessor, RTDetrForObjectDetection
device = "mps"
model_id = "PekingU/rtdetr_r50vd_coco_o365"
threshold = 0.4
scale = 0.5
processor = AutoImageProcessor.from_pretrained(model_id)
model = RTDetrForObjectDetection.from_pretrained(model_id).to(device)
model.eval()
def draw_boxes(frame, boxes):
for (x1, y1, x2, y2) in boxes:
cv2.rectangle(frame, (int(x1), int(y1)), (int(x2), int(y2)), (0, 255, 255), 2)
cap = cv2.VideoCapture(0)
while True:
start_time = time.time()
ret, frame = cap.read()
if not ret:
break
frame = cv2.resize(frame, None, fx=scale, fy=scale)
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
inputs = processor(images=rgb, return_tensors="pt").to(device)
with torch.no_grad():
outputs = model(**inputs)
h, w = frame.shape[:2]
results = processor.post_process_object_detection(
outputs,
target_sizes=torch.tensor([(h, w)]),
threshold=threshold,
)[0]
person_boxes = results["boxes"][results["labels"] == 0].cpu().numpy()
draw_boxes(frame, person_boxes)
fps = 1.0 / (time.time() - start_time)
cv2.putText(frame, f"FPS: {fps:.1f}", (10, 30),
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2)
cv2.imshow("Person Detection", frame)
if cv2.waitKey(1) & 0xFF in [27, ord("q")]:
break
cap.release()
cv2.destroyAllWindows()