1、Mot17转Yolov5、Yolov6、Yolov7等数据集

'''
创建以下四个目录,用于存放图片和标签
images/train
images/val
labels/train
labels/val
'''
import os
import shutil
import numpy as np
import configparser
if not os.path.exists('images'):
    os.makedirs('images/train')
    os.makedirs('images/val')
if not os.path.exists('labels'):
    os.makedirs('labels/train')
    os.makedirs('labels/val')
def convert(imgWidth, imgHeight, left, top, width, height):
    x = (left + width / 2.0) / imgWidth
    y = (top + height / 2.0) / imgHeight
    w = width / imgWidth
    h = height / imgHeight
    return ('%.6f'%x, '%.6f'%y, '%.6f'%w, '%.6f'%h) # 保留6位小数

list_mot17=['train','test']
for dir in list_mot17:
    for mot_dir in os.listdir(dir):  # mot_dir是例如MOT17-02-FRCNN这种
        det_path = os.path.join(dir, mot_dir, 'det/det.txt')  # det.txt路径
        dets = np.loadtxt(det_path, delimiter=',')  # 读取det.txt文件
        ini_path = os.path.join(dir, mot_dir, 'seqinfo.ini')  # seqinfo.ini路径
        conf = configparser.ConfigParser()
        conf.read(ini_path)  # 读取seqinfo.ini文件
        seqLength = int(conf['Sequence']['seqLength'])  # MOT17-02-FRCNN序列的长度
        imgWidth = int(conf['Sequence']['imWidth'])  # 图片宽度
        imgHeight = int(conf['Sequence']['imHeight'])  # 图片长度
        for det in dets:
            frame_id, _, left, top, width, height = int(det[0]), det[1], det[2], det[3], det[4], det[5]
            box = convert(imgWidth, imgHeight, left, top, width, height)
            if '-' in ''.join(box) or float(box[0]) > 1.0 or float(box[1]) > 1.0 or float(box[2]) > 1.0 or float(
                    box[3]) > 1.0:
                print(imgWidth, imgHeight, left, top, width, height)
                print(box)
                continue
            image_name = mot_dir + '-' + '%06d' % frame_id + '.jpg'  # MOT17-02-FRCNN-000001.jpg
            label_name = mot_dir + '-' + '%06d' % frame_id + '.txt'  # MOT17-02-FRCNN-000001.txt
            oldimgpath = os.path.join(dir, mot_dir, 'img1',
                                      '%06d' % frame_id + '.jpg')  # train/MOT17-02-FRCNN/img1/000001.jpg

            newimgpath = os.path.join('images', 'train', image_name)  # images/train/MOT17-02-FRCNN-000001.jpg
            labelpath = os.path.join('labels', 'train', label_name)  # labels/train/MOT17-02-FRCNN-000001.txt

            if not os.path.exists(newimgpath):  # 如果图片没复制过去,就复制,
                shutil.copyfile(oldimgpath, newimgpath)  # 把旧图片复制到新的地方
            with open(labelpath, 'a') as f:  # 写label文件
                f.write(f'0 {box[0]} {box[1]} {box[2]} {box[3]}\n')

2、显示转化后的图片。

import cv2
import os

def draw_box_in_single_image(image_path, txt_path):
    # 读取图像
    image = cv2.imread(image_path)

    # 读取txt文件信息
    def read_list(txt_path):
        pos = []
        with open(txt_path, 'r') as file_to_read:
            while True:
                lines = file_to_read.readline()  # 整行读取数据
                if not lines:
                    break
                # 将整行数据分割处理,如果分割符是空格,括号里就不用传入参数,如果是逗号, 则传入‘,'字符。
                p_tmp = [float(i) for i in lines.split(' ')]
                pos.append(p_tmp)  # 添加新读取的数据
                # Efield.append(E_tmp)
                pass
        return pos


    # txt转换为box
    def convert(size, box):
        xmin = (box[1]-box[3]/2.)*size[1]
        xmax = (box[1]+box[3]/2.)*size[1]
        ymin = (box[2]-box[4]/2.)*size[0]
        ymax = (box[2]+box[4]/2.)*size[0]
        box = (int(xmin), int(ymin), int(xmax), int(ymax))
        return box

    pos = read_list(txt_path)
    print(pos)
    tl = int((image.shape[0]+image.shape[1])/2)
    lf = max(tl-1,1)
    for i in range(len(pos)):
        label = str(int(pos[i][0]))
        print('label is '+label)
        box = convert(image.shape, pos[i])
        image = cv2.rectangle(image,(box[0], box[1]),(box[2],box[3]),(0,0,255),2)
        cv2.putText(image,label,(box[0],box[1]-2), 0, 1, [0,0,255], thickness=2, lineType=cv2.LINE_AA)
        pass

    if pos:
        cv2.imwrite('./VOCData/see_images/{}.png'.format(image_path.split('\\')[-1][:-4]), image)
    else:
        print('None')

    print('./VOCData/see_images/{}.png'.format(image_path.split('\\')[-1][:-4]))
    # cv2.imshow("images", image)
    # cv2.waitKey(0)
    # cv2.destroyAllWindows()


img_folder = "./images/train"
img_list = os.listdir(img_folder)
img_list.sort()

label_folder = "./labels/train"
label_list = os.listdir(label_folder)
label_list.sort()
if not os.path.exists('./VOCData/see_images'):
    os.makedirs('./VOCData/see_images')
for i in range(len(img_list)):
    image_path = img_folder + "\\" + img_list[i]
    txt_path = label_folder + "\\" + label_list[i]
    draw_box_in_single_image(image_path, txt_path)

在这里插入图片描述

MOT17里面很多框标错了,服了!


转载自:https://wanghao.blog.csdn.net/article/details/127383567