INRIAPerson数据集转化为yolo训练格式并可视化

记录贴:将inria行人检测数据集转化为YOLO可以训练的txt格式

inria行人检测数据集解压后有train和test文件,将里面的标注信息提取出来

转化代码

# coding=UTF-8

import os
import re
from PIL import Image

sets=['train']
#需要填写变量image_path、annotations_path、full_path
image_path = r"D:\BaiduNetdiskDownload\59_INRIA Person Dataset\shuju1/"                          # 图片存放路径,路径固定
annotations_path = r"D:\BaiduNetdiskDownload\59_INRIA Person Dataset\INRIAPerson\Test\annotations/" #文件夹目录                                          # INRIA标签存放路径
annotations= os.listdir(annotations_path) #得到文件夹下的所有文件名称

# 获取文件夹下所有图片的图片名
def get_name(file_dir):
   list_file=[]
   for root, dirs, files in os.walk(file_dir):
      for file in files:
         # splitext()将路径拆分为文件名+扩展名,例如os.path.splitext(“E:/lena.jpg”)将得到”E:/lena“+".jpg"
         if os.path.splitext(file)[1] == '.jpg':
            list_file.append(os.path.join(root, file))
   return list_file

# 在labels目录下创建每个图片的标签txt文档
def text_create(name,bnd):
   full_path = r"D:\BaiduNetdiskDownload\59_INRIA Person Dataset\labels1/%s.txt"%(name)
   size = get_size(name + '.png')
   convert_size = convert(size, bnd)
   file = open(full_path, 'a')
   file.write('0 ' + str(convert_size[0]) + ' ' + str(convert_size[1]) + ' ' + str(convert_size[2]) + ' ' + str(convert_size[3]) )
   file.write('\n')

# 获取要查询的图片的w,h
def get_size(image_id):
   im = Image.open(r'D:\BaiduNetdiskDownload\59_INRIA Person Dataset\INRIAPerson\Test\pos/%s'%(image_id))       # 源图片存放路径
   size = im.size
   w = size[0]
   h = size[1]
   return (w,h)

# 将Tagphoto的x,y,w,h格式转换成yolo的X,Y,W,H
def convert(size, box):
   dw = 1./size[0]
   dh = 1./size[1]
   x = (box[0] + box[2])/2.0
   y = (box[1] + box[3])/2.0
   w = box[2] - box[0]
   h = box[3] - box[1]
   x = x*dw
   w = w*dw
   y = y*dh
   h = h*dh
   return (x,y,w,h)

# 将处理的图片路径放入一个txt文件夹中
for image_set in sets:
   if not os.path.exists(r'D:\BaiduNetdiskDownload\59_INRIA Person Dataset\labels1'):
      os.makedirs(r'D:\BaiduNetdiskDownload\59_INRIA Person Dataset\labels1')                     # 生成的yolo3标签存放路径,路径固定
   image_names = get_name(image_path)
   list_file = open('2007_%s.txt'%(image_set), 'w')
   for image_name in image_names:
      list_file.write('%s\n'%(image_name))
   list_file.close()

s = []
for file in annotations: #遍历文件夹
   str_name = file.replace('.txt', '')

   if not os.path.isdir(file): #判断是否是文件夹,不是文件夹才打开
      with open(annotations_path+"/"+file) as f : #打开文件
         iter_f = iter(f); #创建迭代器
         for line in iter_f: #遍历文件,一行行遍历,读取文本
            str_XY = "(Xmax, Ymax)"
            if str_XY in line:
               strlist = line.split(str_XY)
               strlist1 = "".join(strlist[1:])    # 把list转为str
               strlist1 = strlist1.replace(':', '')
               strlist1 = strlist1.replace('-', '')
               strlist1 = strlist1.replace('(', '')
               strlist1 = strlist1.replace(')', '')
               strlist1 = strlist1.replace(',', '')
               b = strlist1.split()
               bnd = (float(b[0]) ,float(b[1]) ,float(b[2]) ,float(b[3]))
               text_create(str_name, bnd)
            else:
               continue

可视化一下

判断转化是否正确,写了一个可视化代码


import os
import cv2
img_path = r'D:\BaiduNetdiskDownload\59_INRIA Person Dataset\INRIAPerson\Train\pos/'
label_path = r'D:\BaiduNetdiskDownload\59_INRIA Person Dataset\labels/'
f = os.listdir(img_path)
def paint(label_file, img_file):
    #读取照片
    img = cv2.imread(img_file)
    img_h, img_w, _ = img.shape
    with open(label_file, 'r') as f:
        obj_lines = [l.strip() for l in f.readlines()]
    for obj_line in obj_lines:
        cls, cx, cy, nw, nh = [float(item) for item in obj_line.split(' ')]
        color = (0, 0, 255) if cls == 0.0 else (0, 255, 0)
        x_min = int((cx - (nw / 2.0)) * img_w)
        y_min = int((cy - (nh / 2.0)) * img_h)
        x_max = int((cx + (nw / 2.0)) * img_w)
        y_max = int((cy + (nh / 2.0)) * img_h)
        cv2.rectangle(img, (x_min, y_min), (x_max, y_max), color, 2)
    cv2.imshow('Ima', img)
    cv2.waitKey(0)
for i in f:
    label_path_name = label_path + i.replace('png','txt')
    img_path_name = img_path + i
    print(label_path_name)
    print(img_path_name)
    paint(label_path_name,img_path_name)

在这里插入图片描述
发现这个数据集的多人场景下只标注了几个人

  • 5
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 9
    评论
你可以使用OpenCV库来可视化YOLO格式数据集并绘制边界框。下面是一个简单的示例代码,可以帮助你完成这个任务: ```python import cv2 import numpy as np def visualize_dataset(image_path, label_path, class_names): image = cv2.imread(image_path) height, width, _ = image.shape with open(label_path, 'r') as f: lines = f.readlines() for line in lines: # 解析边界框信息 class_id, x, y, w, h = map(float, line.split()) class_id = int(class_id) x = int((x - w/2) * width) y = int((y - h/2) * height) w = int(w * width) h = int(h * height) # 绘制边界框 cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2) cv2.putText(image, class_names[class_id], (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2) cv2.imshow('Image', image) cv2.waitKey(0) cv2.destroyAllWindows() # 设置类别名称和标签路径 class_names = ['person', 'car', 'cat'] # 替换成你的类别名称 label_path = 'path/to/labels.txt' # 替换成你的标签文件路径 image_path = 'path/to/image.jpg' # 替换成你的图像文件路径 # 可视化数据集 visualize_dataset(image_path, label_path, class_names) ``` 在这个示例中,你需要将类别名称、标签文件路径和图像文件路径替换成你自己的路径。确保标签文件的格式YOLO格式一致,每行包含了一个边界框的类别ID和边界框的中心坐标、宽度和高度。 运行这段代码后,你会看到一个显示了边界框的图像窗口。边界框使用绿色线条绘制在图像上,并显示了对应的类别名称。你可以使用键盘上的任意按键来关闭图像窗口。 希望这个示例能帮助到你!如果有任何疑问,请随时提问。
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

一休哥※

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

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

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

打赏作者

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

抵扣说明:

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

余额充值