目標檢測在影像上bbox繪製與添加類別(可添加中文)
在 目標檢測中,得到結果之後往往需要在影像上添加bbox和預測類別與概率可視化顯示,使用opencv可以簡單實現這一功能(遇到中文label會出現亂碼,下文解決)
1. opencv繪製bbox並且添加類別概率
# 採用隨即生成所有類別的邊框與字體的顏色
colors = [[random.randint(0, 255) for _ in range(3)] for _ in range(num_classes)]
# cv2.rectangle(img, (x,y), (x+w,y+h), (B,G,R), Thickness)
cv2.rectangle(img, (x1,y1), (x2, y2), colors[category_id], 2)
text = str(category_id)
Font = cv2.FONT_HERSHEY_SIMPLEX
# cv2.putText(img, text, (x,y), Font, Size, (B,G,R), Thickness)
cv2.putText(img, text, (x1,y1-10), Font, 1.5, colors[category_id], 2)
上邊的方法所採用的類別的方式為數字表示,可視化看起來不直觀,如果直接採用中文label,則會出現亂碼,需要進行額外的處理
2. 利用PIL解決中文字體顯示的問題
在終端中輸入如下的語句,查看在/usr/share/fonts中有什麼字體。
locate *.ttc
然後採用如下的程式碼:
from PIL import Image, ImageDraw, ImageFont
def drawOneBox(img, bbox, color, label):
'''對於給定的影像與給定的與類別標註資訊,在圖片上繪製出bbox並且標註上指定的類別
'''
img_PIL = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
# locate *.ttc
font = ImageFont.truetype("NotoSansCJK-Bold.ttc", 20, encoding='utf-8')
x1, y1, x2, y2 = bbox
draw = ImageDraw.Draw(img_PIL)
position = (x1, y1 - 30)
draw.text(position, label, tuple(color), font=font)
img = cv2.cvtColor(np.asarray(img_PIL),cv2.COLOR_RGB2BGR)
cv2.rectangle(img, (x1,y1), (x2, y2), colors[category_id], 2)
return img
親測可用,這裡記錄一下,防止隨後有需要的時候再到處找方法。