This chapter is based on the changes of the yolov5-fastapi-demo project
WelkinU/yolov5-fastapi-demo: FastAPI Wrapper of YOLOv5 (github.com)
First of all, because the labels set during training are in English, switching to Chinese requires retraining, and training in Chinese is cumbersome and requires many changes, so you can use English labels during training directly, and then make a judgment when recognizing drawings Just replace the label. as follows
if bbox["class_name"] =="Old English name":
bbox["class_name"] = "New Chinese name"
In the plot_one_box of server.py, the label is the label passed in
Then after changing to a Chinese label, it turned out to be garbled characters? ? ? ?
It turns out that OpenCV does not support Chinese, so we change to draw.text to draw
First download the font package msyh
Drop it directly into the root directory
Then import the package
from PIL import ImageFont, ImageDraw, Image
Modify the content under the if label of plot_one_box:
if label:
tf = max(tl - 1, 1) # font thickness
t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]
font_size = t_size[1]
font = ImageFont.truetype('msyh.ttc', font_size)
t_size = font.getsize(label)
c2 = c1[0] + t_size[0], c1[1] - t_size[1]
cv2.rectangle(im, c1, c2, color, -1, cv2.LINE_AA) # filled
img_PIL = Image.fromarray(cv2.cvtColor(im, cv2.COLOR_BGR2RGB))
draw = ImageDraw.Draw(img_PIL)
draw.text((c1[0], c2[1] - 2), label, fill=(255, 255, 255), font=font)
cv2.cvtColor(np.array(img_PIL), cv2.COLOR_RGB2BGR)
return cv2.cvtColor(np.array(img_PIL), cv2.COLOR_RGB2BGR)
At this point, the label has been successfully replaced with Chinese