Update services/stream_object_detection_service.py
Browse files
services/stream_object_detection_service.py
CHANGED
|
@@ -1,19 +1,24 @@
|
|
| 1 |
-
from PIL import ImageDraw, ImageFont
|
| 2 |
-
import spaces
|
| 3 |
import cv2
|
| 4 |
-
from PIL import Image
|
| 5 |
-
import numpy as np
|
| 6 |
import torch
|
|
|
|
| 7 |
import uuid
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
-
SUBSAMPLE = 2 # giảm
|
| 10 |
|
| 11 |
|
| 12 |
-
class StreamObjectDetection
|
|
|
|
| 13 |
def draw_bounding_boxes(image, boxes, model, conf_threshold):
|
| 14 |
draw = ImageDraw.Draw(image)
|
| 15 |
font = ImageFont.load_default()
|
| 16 |
-
|
| 17 |
for score, label, box in zip(boxes["scores"], boxes["labels"], boxes["boxes"]):
|
| 18 |
if score < conf_threshold:
|
| 19 |
continue
|
|
@@ -21,52 +26,58 @@ class StreamObjectDetection :
|
|
| 21 |
label_text = f"{model.config.id2label[label.item()]}: {score:.2f}"
|
| 22 |
draw.rectangle([x0, y0, x1, y1], outline="red", width=3)
|
| 23 |
draw.text((x0 + 3, y0 + 3), label_text, fill="white", font=font)
|
| 24 |
-
|
| 25 |
return image
|
| 26 |
-
|
| 27 |
-
@
|
| 28 |
-
|
|
|
|
| 29 |
cap = cv2.VideoCapture(video)
|
| 30 |
video_codec = cv2.VideoWriter_fourcc(*"mp4v")
|
| 31 |
-
fps = int(cap.get(cv2.CAP_PROP_FPS))
|
| 32 |
-
desired_fps = fps // SUBSAMPLE
|
| 33 |
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) // 2
|
| 34 |
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) // 2
|
| 35 |
-
|
| 36 |
iterating, frame = cap.read()
|
| 37 |
n_frames = 0
|
| 38 |
output_video_name = f"output_{uuid.uuid4()}.mp4"
|
| 39 |
output_video = cv2.VideoWriter(output_video_name, video_codec, desired_fps, (width, height))
|
| 40 |
batch = []
|
| 41 |
-
|
| 42 |
while iterating:
|
| 43 |
frame = cv2.resize(frame, (0, 0), fx=0.5, fy=0.5)
|
| 44 |
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
| 45 |
-
|
| 46 |
if n_frames % SUBSAMPLE == 0:
|
| 47 |
batch.append(frame)
|
| 48 |
-
|
| 49 |
-
|
|
|
|
| 50 |
inputs = image_processor(images=batch, return_tensors="pt").to(model.device)
|
|
|
|
| 51 |
with torch.no_grad():
|
| 52 |
outputs = model(**inputs)
|
| 53 |
-
|
| 54 |
boxes = image_processor.post_process_object_detection(
|
| 55 |
outputs,
|
| 56 |
target_sizes=torch.tensor([(height, width)] * len(batch)).to(model.device),
|
| 57 |
threshold=conf_threshold,
|
| 58 |
)
|
| 59 |
-
|
| 60 |
for img, box in zip(batch, boxes):
|
| 61 |
-
pil_image = draw_bounding_boxes(Image.fromarray(img), box, model, conf_threshold)
|
| 62 |
-
|
| 63 |
-
output_video.write(
|
| 64 |
-
|
| 65 |
batch = []
|
| 66 |
output_video.release()
|
| 67 |
-
yield output_video_name #
|
| 68 |
output_video_name = f"output_{uuid.uuid4()}.mp4"
|
| 69 |
output_video = cv2.VideoWriter(output_video_name, video_codec, desired_fps, (width, height))
|
| 70 |
-
|
| 71 |
iterating, frame = cap.read()
|
| 72 |
-
n_frames += 1
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from PIL import ImageDraw, ImageFont, Image
|
|
|
|
| 2 |
import cv2
|
|
|
|
|
|
|
| 3 |
import torch
|
| 4 |
+
import numpy as np
|
| 5 |
import uuid
|
| 6 |
+
import spaces
|
| 7 |
+
from transformers import RTDetrForObjectDetection, RTDetrImageProcessor
|
| 8 |
+
|
| 9 |
+
# === Load model (chỉ load 1 lần khi khởi động Space) ===
|
| 10 |
+
image_processor = RTDetrImageProcessor.from_pretrained("PekingU/rtdetr_r50vd")
|
| 11 |
+
model = RTDetrForObjectDetection.from_pretrained("PekingU/rtdetr_r50vd").to("cuda" if torch.cuda.is_available() else "cpu")
|
| 12 |
|
| 13 |
+
SUBSAMPLE = 2 # giảm FPS để tiết kiệm tài nguyên
|
| 14 |
|
| 15 |
|
| 16 |
+
class StreamObjectDetection:
|
| 17 |
+
@staticmethod
|
| 18 |
def draw_bounding_boxes(image, boxes, model, conf_threshold):
|
| 19 |
draw = ImageDraw.Draw(image)
|
| 20 |
font = ImageFont.load_default()
|
| 21 |
+
|
| 22 |
for score, label, box in zip(boxes["scores"], boxes["labels"], boxes["boxes"]):
|
| 23 |
if score < conf_threshold:
|
| 24 |
continue
|
|
|
|
| 26 |
label_text = f"{model.config.id2label[label.item()]}: {score:.2f}"
|
| 27 |
draw.rectangle([x0, y0, x1, y1], outline="red", width=3)
|
| 28 |
draw.text((x0 + 3, y0 + 3), label_text, fill="white", font=font)
|
| 29 |
+
|
| 30 |
return image
|
| 31 |
+
|
| 32 |
+
@staticmethod
|
| 33 |
+
@spaces.GPU # Dùng GPU nếu có (ZeroGPU, GPU Cluster, v.v.)
|
| 34 |
+
def stream_object_detection(video, conf_threshold=0.3):
|
| 35 |
cap = cv2.VideoCapture(video)
|
| 36 |
video_codec = cv2.VideoWriter_fourcc(*"mp4v")
|
| 37 |
+
fps = int(cap.get(cv2.CAP_PROP_FPS)) or 24
|
| 38 |
+
desired_fps = max(1, fps // SUBSAMPLE)
|
| 39 |
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) // 2
|
| 40 |
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) // 2
|
| 41 |
+
|
| 42 |
iterating, frame = cap.read()
|
| 43 |
n_frames = 0
|
| 44 |
output_video_name = f"output_{uuid.uuid4()}.mp4"
|
| 45 |
output_video = cv2.VideoWriter(output_video_name, video_codec, desired_fps, (width, height))
|
| 46 |
batch = []
|
| 47 |
+
|
| 48 |
while iterating:
|
| 49 |
frame = cv2.resize(frame, (0, 0), fx=0.5, fy=0.5)
|
| 50 |
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
| 51 |
+
|
| 52 |
if n_frames % SUBSAMPLE == 0:
|
| 53 |
batch.append(frame)
|
| 54 |
+
|
| 55 |
+
# Mỗi 2 giây xử lý một lần
|
| 56 |
+
if len(batch) == 2 * desired_fps:
|
| 57 |
inputs = image_processor(images=batch, return_tensors="pt").to(model.device)
|
| 58 |
+
|
| 59 |
with torch.no_grad():
|
| 60 |
outputs = model(**inputs)
|
| 61 |
+
|
| 62 |
boxes = image_processor.post_process_object_detection(
|
| 63 |
outputs,
|
| 64 |
target_sizes=torch.tensor([(height, width)] * len(batch)).to(model.device),
|
| 65 |
threshold=conf_threshold,
|
| 66 |
)
|
| 67 |
+
|
| 68 |
for img, box in zip(batch, boxes):
|
| 69 |
+
pil_image = StreamObjectDetection.draw_bounding_boxes(Image.fromarray(img), box, model, conf_threshold)
|
| 70 |
+
frame_bgr = np.array(pil_image)[:, :, ::-1]
|
| 71 |
+
output_video.write(frame_bgr)
|
| 72 |
+
|
| 73 |
batch = []
|
| 74 |
output_video.release()
|
| 75 |
+
yield output_video_name # Gửi video xử lý từng phần cho Gradio
|
| 76 |
output_video_name = f"output_{uuid.uuid4()}.mp4"
|
| 77 |
output_video = cv2.VideoWriter(output_video_name, video_codec, desired_fps, (width, height))
|
| 78 |
+
|
| 79 |
iterating, frame = cap.read()
|
| 80 |
+
n_frames += 1
|
| 81 |
+
|
| 82 |
+
cap.release()
|
| 83 |
+
output_video.release()
|