python+yolov3 输出中文标签

利用yolo进行目标识别时,输出的是英文标签,如下图,不便于用户阅读,因此需要转换为中文标签,我采取的办法是对yolo predefined的80类进行了“汉化”,以实现输出中文标签。
不知道是否有更便捷的方法,只是提供了一种思路,供大家参考。
在这里插入图片描述

首先获取LOYO中label名称

打开LOYO文件coco.nameslabel,获取这80类label名称,并译为中文
在这里插入图片描述

    predefined_En=['person','bicycle','car','motorbike','aeroplane','bus','train','truck','boat','traffic light',
                   'fire hydrant','stop sign','parking meter','bench','bird','cat','dog','horse','sheep','cow',
                   'elephant','bear','zebra','giraffe','backpack','umbrella','handbag','tie','suitcase','frisbee',
                   'skis','snowboard','sports ball','kite','baseball bat','baseball glove','skateboard','surfboard','tennis racket','bottle',
                   'wine glass','cup','fork','knife','spoon','bowl','banana','apple','sandwich','orange',
                   'broccoli','carrot','hot dog','pizza','donut','cake','chair','sofa','pottedplant','bed',
                   'diningtable','toilet','tvmonitor','laptop','mouse','remote','keyboard','cell phone','microwave','oven',
                   'toaster','sink','refrigerator','book','clock','vase','scissors','teddy bear','hair drier','toothbrush']
    predefined_CN=['人','自行车','汽车','摩托车','飞机','公共汽车','火车','卡车','船','红绿灯',
                   '消防栓','停止标志','停车收费表','板凳','鸟','猫','狗','马','羊','牛',
                   '大象','熊','斑马','长颈鹿','背包','雨伞','手提包','领带','手提箱','飞盘',
                   '滑雪板','单板滑雪','运动球类','风筝','棒球棒','棒球手套','滑板','冲浪板','网球拍','瓶子',
                   '红酒杯','杯子','叉子','刀','勺子','碗','香蕉','苹果','三明治','橘子',
                   '西兰花','胡萝卜','热狗','比萨','甜甜圈','蛋糕','椅子','沙发','盆栽','床',
                   '餐桌','厕所','电视监视器','笔记本电脑','老鼠','遥控器','键盘','手机','微波炉','烤箱',
                   '烤面包机','水槽','冰箱','书','时钟','花瓶','剪刀','泰迪熊','吹风机','牙刷']		

输出中文标签

OpenCV中可以利用putText()在图片上添加英文,但是添加中文则会出现乱码,因此需要:
1)将OpenCV图片格式转换成PIL的图片格式;
2)使用PIL绘制文字;
3)PIL图片格式转换成OpenCV的图片格式;

def cv2ImgAddText(img, text, left, top, textColor=(255, 0, 0), textSize=20):
    if (isinstance(img, np.ndarray)):  # 判断是否OpenCV图片类型
        img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
    # 创建一个可以在给定图像上绘图的对象
    draw = ImageDraw.Draw(img)
    # 字体的格式
    fontStyle = ImageFont.truetype(
        "font/simsun.ttc", textSize, encoding="utf-8")
    # 绘制文本
    draw.text((left, top), text, textColor, font=fontStyle)
    # 转换回OpenCV格式
    result=cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)
    return result
    

此方法转载自:https://blog.csdn.net/baidu_37366055/article/details/81627185

完整代码

from test import video_demo 
import cv2
import numpy as np
from PIL import Image, ImageDraw, ImageFont

def E2C(label):
    predefined_En=['person','bicycle','car','motorbike','aeroplane','bus','train','truck','boat','traffic light',
                   'fire hydrant','stop sign','parking meter','bench','bird','cat','dog','horse','sheep','cow',
                   'elephant','bear','zebra','giraffe','backpack','umbrella','handbag','tie','suitcase','frisbee',
                   'skis','snowboard','sports ball','kite','baseball bat','baseball glove','skateboard','surfboard','tennis racket','bottle',
                   'wine glass','cup','fork','knife','spoon','bowl','banana','apple','sandwich','orange',
                   'broccoli','carrot','hot dog','pizza','donut','cake','chair','sofa','pottedplant','bed',
                   'diningtable','toilet','tvmonitor','laptop','mouse','remote','keyboard','cell phone','microwave','oven',
                   'toaster','sink','refrigerator','book','clock','vase','scissors','teddy bear','hair drier','toothbrush']
    predefined_CN=['人','自行车','汽车','摩托车','飞机','公共汽车','火车','卡车','船','红绿灯',
                   '消防栓','停止标志','停车收费表','板凳','鸟','猫','狗','马','羊','牛',
                   '大象','熊','斑马','长颈鹿','背包','雨伞','手提包','领带','手提箱','飞盘',
                   '滑雪板','单板滑雪','运动球类','风筝','棒球棒','棒球手套','滑板','冲浪板','网球拍','瓶子',
                   '红酒杯','杯子','叉子','刀','勺子','碗','香蕉','苹果','三明治','橘子',
                   '西兰花','胡萝卜','热狗','比萨','甜甜圈','蛋糕','椅子','沙发','盆栽','床',
                   '餐桌','厕所','电视监视器','笔记本电脑','老鼠','遥控器','键盘','手机','微波炉','烤箱',
                   '烤面包机','水槽','冰箱','书','时钟','花瓶','剪刀','泰迪熊','吹风机','牙刷']
    #找到英文label名称在list中的位置
    loc = predefined_En.index(label)
    #显示对应位置的中文名称
    label_CN=predefined_CN[loc]
    return label_CN


def cv2ImgAddText(img, text, left, top, textColor=(255, 0, 0), textSize=20):
    if (isinstance(img, np.ndarray)):  # 判断是否OpenCV图片类型
        img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
    # 创建一个可以在给定图像上绘图的对象
    draw = ImageDraw.Draw(img)
    # 字体的格式
    fontStyle = ImageFont.truetype(
        "font/simsun.ttc", textSize, encoding="utf-8")
    # 绘制文本
    draw.text((left, top), text, textColor, font=fontStyle)
    # 转换回OpenCV格式
    result=cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)
    return result


if __name__ == '__main__':
    #待检测的图片
    file='H:/dog.jpg'
    #进行LOYO识别
    image, info = video_demo(file)
    imgA=cv2.imread(file)
    #YOLO返回的坐标值和标签、置信度
    locx1 = [q1['xtop'] for q1 in info]  # 左上角x坐标
    locx2 = [q2['ytop'] for q2 in info]  # 左上角y坐标
    locy1 = [q3['xbottom'] for q3 in info]  # 右下角x坐标
    locy2 = [q4['ybottom'] for q4 in info]  # 右下角y坐标
    lable_str = [q5['label'] for q5 in info]  # 标签
    confidence = [q6['confidence'] for q6 in info]  # 置信度

    B = len(locx1)
    for l in range(0, B):
        x2 = (locx1[l], locx2[l])
        y2 = (locy1[l], locy2[l])
        #英文标签转换为中文标签
        label_CN = E2C(lable_str[l])
        #输出中文标签和置信度
        text = "{}: {}".format(label_CN, confidence[l])
        #在imgA上画出矩形
        cv2.rectangle(imgA, x2, y2, (0, 0, 255), 2)
        #在imgA上显示中文标签+置信度
        imgA = cv2ImgAddText(imgA, text, locx1[l], locx2[l])

    cv2.imshow('Image', imgA)
    cv2.waitKey(0)
    

运行结果

在这里插入图片描述

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
要使用Python获取yolov8的输出,您需要先安装yolov8和相关的Python库。然后,您可以通过以下步骤获取yolov8的输出: 1. 导入必要的库: ```python import cv2 import numpy as np ``` 2. 加载模型: ```python net = cv2.dnn.readNetFromDarknet('path/to/yolov8.cfg', 'path/to/yolov8.weights') ``` 确保将路径替换为您yolov8配置文件权重文件的实际路径。 3. 加载类别标签: ```python classes = [] with open('path/to/labels.txt', 'r') as f: classes = [line.strip() for line in f.readlines()] ``` 确保将路径替换为包含类别标签的文本文件的实际路径。 4. 加载图像并进行预处理: ```python image = cv2.imread('path/to/image.jpg') blob = cv2.dnn.blobFromImage(image, 1/255, (416, 416), swapRB=True, crop=False) ``` 确保将路径替换为您要检测的图像的实际路径。这里使用了416x416的输入尺寸,如果您的模型使用不同的尺寸,请相应地进行调整。 5. 将blob输入到网络中,并获取输出层: ```python net.setInput(blob) layer_names = net.getLayerNames() output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()] outputs = net.forward(output_layers) ``` 6. 解析输出并提取检测结果: ```python for output in outputs: for detection in output: scores = detection[5:] class_id = np.argmax(scores) confidence = scores[class_id] if confidence > 0.5: # 设置置信度阈值 center_x = int(detection[0] * image.shape[1]) center_y = int(detection[1] * image.shape[0]) width = int(detection[2] * image.shape[1]) height = int(detection[3] * image.shape[0]) x = int(center_x - width / 2) y = int(center_y - height / 2) cv2.rectangle(image, (x, y), (x + width, y + height), (0, 255, 0), 2) cv2.putText(image, classes[class_id], (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2) ``` 在解析输出时,我们首先找到具有最高置信度的类别,然后根据检测框的坐标将其绘制到原始图像上。 7. 显示或保存结果图像: ```python cv2.imshow('Output', image) cv2.waitKey(0) cv2.destroyAllWindows() ``` 您可以使用`cv2.imshow`显示结果图像,也可以使用`cv2.imwrite`将其保存为文件。 这就是使用Python获取yolov8输出的基本步骤。请确保安装了正确的库和模型文件,并根据您的需求进行相应的调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Rena要努力

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值