datbkpro commited on
Commit
df27322
·
verified ·
1 Parent(s): 1067054

Create stream_object_detection_service.py

Browse files
services/stream_object_detection_service.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 tốc độ khung hình để tăng tốc độ xử lý
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
20
+ x0, y0, x1, y1 = box
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
+ @spaces.CPU # dùng GPU nếu chạy trên Hugging Face
28
+ def stream_object_detection(video, conf_threshold):
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
+ if len(batch) == 2 * desired_fps: # mỗi 2s xử lý 1 lần
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
+ frame = np.array(pil_image)[:, :, ::-1]
63
+ output_video.write(frame)
64
+
65
+ batch = []
66
+ output_video.release()
67
+ yield output_video_name # stream ra video đã xử lý
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