Views
No views yet
1from huggingface_hub import hf_hub_download
2from ultralytics import YOLO
3import json
4import cv2
5import matplotlib.pyplot as plt
6
7
8# plot function
9def visualize_bbox(img_path, predictions, conf_thres=0.8, font=cv2.FONT_HERSHEY_SIMPLEX):
10 img = cv2.imread(img_path)
11
12 for prediction in predictions:
13 conf_score = prediction["confidence"]
14 if conf_score < conf_thres:
15 continue
16 bbox = prediction["box"]
17 xmin = int(bbox["x1"])
18 ymin = int(bbox["y1"])
19 xmax = int(bbox["x2"])
20 ymax = int(bbox["y2"])
21 cv2.rectangle(img, (xmin, ymin), (xmax, ymax), (0, 255, 0), 3)
22 text = f"{conf_score:.2f}"
23 (text_width, text_height), _ = cv2.getTextSize(text, font, 1, 2)
24 cv2.rectangle(
25 img,
26 (xmin, ymin - text_height - 5),
27 (xmin + text_width, ymin),
28 (0, 255, 0),
29 -1,
30 )
31 cv2.putText(img, text, (xmin, ymin - 5), font, 1, (0, 0, 0), 2)
32 return img
33
34
35# download model and sample
36model_path = hf_hub_download(
37 repo_id="huytqvn/text-detection-str-pipeline",
38 filename="best.pt"
39)
40sample_path = hf_hub_download(
41 repo_id="huytqvn/text-detection-str-pipeline",
42 filename="sample.JPG"
43)
44
45# load model
46model = YOLO(model_path)
47
48# inference
49results = model(sample_path)
50predict = json.loads(results[0].to_json())
51
52# visualize
53visualize_img = visualize_bbox(sample_path, predict, conf_thres=0.75)
54visualize_img = cv2.cvtColor(visualize_img, cv2.COLOR_BGR2RGB)
55plt.imshow(visualize_img)
56plt.axis("off")
57plt.show()