【python】在原图中显示标签(yolo格式)的检测框bbox

主要流程:

读取标签文件数据,打开图像,利用opencv-python库,在原图中画出标签的bbox检测框,并可以保存。

先说明一下我们的文件结构:
训练集:我们在案例中将训练集目录命名为images
然后训练集目录内全部都是jpg图像。
例如:

 |-- images
         |   |-- 000000000009.jpg
         |   |-- 000000000025.jpg
         |   |-- 000000000030.jpg
         |   |-- ... 

训练集标签:我们在案例中将训练集目录命名为labels
然后训练集标签目录内全部都是txt文件。

 |-- labels
         |   |-- 000000000009.txt
         |   |-- 000000000025.txt
         |   |-- 000000000030.txt
         |   |-- ... 

本问代码读取的标签格式是yolo格式的
txt标签内容格式例如:

0 0.3125 0.179104 0.0453125 0.0985075

简单介绍:
每行一共5个数据,数据与数据之间空格隔开。
第一个数据0表示分类的类别序号
第二个数据0.3125表示x_center/width,即检测框中点的x坐标除以图像宽度。
第三个数据0.179104表示y_center/height,即检测框中点的y坐标除以图像高度。
第四个数据0.0453125表示roi_width/width。即检测框的宽度除以图像宽度。
第五个数据 0.0985075表示roi_width/width。即检测框的高度除以图像高度。

然后我们的代码如下:
具体路径根据实际情况而定

import os
import cv2


def main():
	# 总的检测根目录
    path_root_labels = './test_data/label'
    # 总的检测根目录
    path_root_imgs ='./test_data/img'
    type_object = '.txt'


    for ii in os.walk(path_root_imgs):
        for j in ii[2]:
            type = j.split(".")[1]
            if type != 'jpg':
                continue
            path_img = os.path.join(path_root_imgs, j)
            print(path_img)
            label_name = j[:-4]+type_object
            path_label = os.path.join(path_root_labels, label_name)
            # print(path_label)
            f = open(path_label, 'r+', encoding='utf-8')
            if os.path.exists(path_label) == True:

                img = cv2.imread(path_img)
                w = img.shape[1]
                h = img.shape[0]
                new_lines = []
                img_tmp = img.copy()
                while True:
                    line = f.readline()
                    if line:
                        msg = line.split(" ")
                        # print(x_center,",",y_center,",",width,",",height)
                        x1 = int((float(msg[1]) - float(msg[3]) / 2) * w)  # x_center - width/2
                        y1 = int((float(msg[2]) - float(msg[4]) / 2) * h)  # y_center - height/2
                        x2 = int((float(msg[1]) + float(msg[3]) / 2) * w)  # x_center + width/2
                        y2 = int((float(msg[2]) + float(msg[4]) / 2) * h)  # y_center + height/2
                        print(x1,",",y1,",",x2,",",y2)
                        cv2.rectangle(img_tmp,(x1,y1),(x2,y2),(0,0,255),5)
                    else :
                        break
            cv2.imshow("show", img_tmp)
            c = cv2.waitKey(0)



if __name__ == '__main__':
    main()


  • 8
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 12
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值