Opencv画出红底白字标准中文显示框

链接:https://pan.baidu.com/s/1iEJKpqt-z_5yBJdenUABbA 
提取码:uoox 
先把这个文件拿了,这个文件是一个ttf的字体,用于显示中文。

核心代码👑

    def cv2AddChineseText(self, img_ori, text, p1, box_color, textColor=(255, 255, 255), textSize=17):
        if (isinstance(img_ori, np.ndarray)):  # 判断是否OpenCV图片类型
            img = Image.fromarray(cv2.cvtColor(img_ori, cv2.COLOR_BGR2RGB))
        # 创建一个可以在给定图像上绘图的对象
        draw = ImageDraw.Draw(img)
        # 字体的格式
        fontStyle = ImageFont.truetype(
            "simsun.ttc", textSize, encoding="utf-8")
        # 绘制文本
        text_width, text_height = draw.textsize(text, font=fontStyle)
        position = []
        outside_x = p1[0] + text_width + 3 < img.width
        outside_y = p1[1] - text_height - 3 >= 0
        position.append(p1[0] + 3 if outside_x else img.width - text_width)
        position.append(p1[1] - text_height - 3 if outside_y else p1[1] + 3)
        p2 = (position[0] + text_width, position[1] +  text_height)
        image = cv2.rectangle(img_ori, position, p2, box_color, -1, cv2.LINE_AA)  # filled
        img = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
        draw = ImageDraw.Draw(img)
        draw.text((position[0], position[1]), text, textColor, font=fontStyle)
        # 转换回OpenCV格式
        return cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)
 
    def draw_boxs(self, boxes, image):
        for res in boxes:
            box = [res[0], res[1], res[2]+res[0], res[3]+res[1]]
            label = self.labels[res[4]]
            conf = round(res[5], 4)
 
            box = np.array(box[:4], dtype=np.int32)  # xyxy
 
            line_width = int(3)
            txt_color = (255, 255, 255)
            box_color = (58, 56, 255)
 
            p1, p2 = (box[0], box[1]), (box[2], box[3])
            image = cv2.rectangle(image, p1, p2, box_color, line_width)
 
            tf = max(line_width - 1, 1)  # font thickness
            box_label = '%s: %.2f' % (self.get_desc(label), conf)
            image = self.cv2AddChineseText(image, box_label, p1, box_color, txt_color)
        return image

        一共两个函数def draw_boxs和def cv2AddChineseText,主函数是def draw_boxs,传入参数是boxes和image,不必多说

①boxes->预测结果[xmin, ymin, w, h,conf, cls]->[左上角坐标x,左上角坐标y,宽度,长度,置信度,类别]

②image->原图[cv2/numpy.array]。

两个函数的作用以及他们之间的关联如下:        

NOTE:代码中的self.label是一个映射字典,代码中没有给出,只是调用了,需要自行补充。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

大气层煮月亮

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

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

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

打赏作者

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

抵扣说明:

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

余额充值