Skip to content

Commit eafe202

Browse files
author
yixu.cui
committed
format document with black
1 parent 2162c0f commit eafe202

File tree

2 files changed

+200
-129
lines changed

2 files changed

+200
-129
lines changed

tools/convert_MOT17_to_yolo.py

Lines changed: 115 additions & 70 deletions
Original file line numberDiff line numberDiff line change
@@ -11,66 +11,80 @@
1111
import numpy as np
1212
import random
1313

14-
DATA_ROOT = '/data/wujiapeng/datasets/MOT17/'
15-
14+
# DATA_ROOT = '/data/wujiapeng/datasets/MOT17/'
15+
DATA_ROOT = "/perception/yixu.cui/datas/tracking/MOT17"
1616
image_wh_dict = {} # seq->(w,h) 字典 用于归一化
1717

18+
1819
def generate_imgs_and_labels(opts):
1920
"""
2021
产生图片路径的txt文件以及yolo格式真值文件
2122
"""
22-
if opts.split == 'test':
23-
seq_list = os.listdir(osp.join(DATA_ROOT, 'test'))
23+
if opts.split == "test":
24+
seq_list = os.listdir(osp.join(DATA_ROOT, "test"))
2425
else:
25-
seq_list = os.listdir(osp.join(DATA_ROOT, 'train'))
26-
seq_list = [item for item in seq_list if 'FRCNN' in item] # 只取一个FRCNN即可
27-
if 'val' in opts.split: opts.half = True # 验证集取训练集的一半
26+
seq_list = os.listdir(osp.join(DATA_ROOT, "train"))
27+
seq_list = [item for item in seq_list if "FRCNN" in item] # 只取一个FRCNN即可
28+
if "val" in opts.split:
29+
opts.half = True # 验证集取训练集的一半
2830

29-
print('--------------------------')
30-
print(f'Total {len(seq_list)} seqs!!')
31+
print("--------------------------")
32+
print(f"Total {len(seq_list)} seqs!!")
3133
print(seq_list)
32-
33-
if opts.random:
34+
35+
if opts.random:
3436
random.shuffle(seq_list)
3537

3638
# 定义类别 MOT只有一类
3739
CATEGOTY_ID = 0 # pedestrian
3840

3941
# 定义帧数范围
40-
frame_range = {'start': 0.0, 'end': 1.0}
42+
frame_range = {"start": 0.0, "end": 1.0}
4143
if opts.half: # half 截取一半
42-
frame_range['end'] = 0.5
44+
frame_range["end"] = 0.5
4345

44-
if opts.split == 'test':
45-
process_train_test(seqs=seq_list, frame_range=frame_range, cat_id=CATEGOTY_ID, split='test')
46+
if opts.split == "test":
47+
process_train_test(
48+
seqs=seq_list, frame_range=frame_range, cat_id=CATEGOTY_ID, split="test"
49+
)
4650
else:
47-
process_train_test(seqs=seq_list, frame_range=frame_range, cat_id=CATEGOTY_ID, split=opts.split)
48-
51+
process_train_test(
52+
seqs=seq_list, frame_range=frame_range, cat_id=CATEGOTY_ID, split=opts.split
53+
)
4954

50-
def process_train_test(seqs: list, frame_range: dict, cat_id: int = 0, split: str = 'trian') -> None:
55+
56+
def process_train_test(
57+
seqs: list, frame_range: dict, cat_id: int = 0, split: str = "trian"
58+
) -> None:
5159
"""
5260
处理MOT17的train 或 test
5361
由于操作相似 故另写函数
5462
55-
"""
63+
"""
5664

5765
for seq in seqs:
58-
print(f'Dealing with {split} dataset...')
66+
print(f"Dealing with {split} dataset...")
5967

60-
img_dir = osp.join(DATA_ROOT, 'train', seq, 'img1') if split != 'test' else osp.join(DATA_ROOT, 'test', seq, 'img1') # 图片路径
68+
img_dir = (
69+
osp.join(DATA_ROOT, "train", seq, "img1")
70+
if split != "test"
71+
else osp.join(DATA_ROOT, "test", seq, "img1")
72+
) # 图片路径
6173
imgs = sorted(os.listdir(img_dir)) # 所有图片的相对路径
6274
seq_length = len(imgs) # 序列长度
6375

64-
if split != 'test':
76+
if split != "test":
6577

6678
# 求解图片高宽
6779
img_eg = cv2.imread(osp.join(img_dir, imgs[0]))
6880
w0, h0 = img_eg.shape[1], img_eg.shape[0] # 原始高宽
6981

70-
ann_of_seq_path = os.path.join(img_dir, '../', 'gt', 'gt.txt') # GT文件路径
71-
ann_of_seq = np.loadtxt(ann_of_seq_path, dtype=np.float32, delimiter=',') # GT内容
82+
ann_of_seq_path = os.path.join(img_dir, "../", "gt", "gt.txt") # GT文件路径
83+
ann_of_seq = np.loadtxt(
84+
ann_of_seq_path, dtype=np.float32, delimiter=","
85+
) # GT内容
7286

73-
gt_to_path = osp.join(DATA_ROOT, 'labels', split, seq) # 要写入的真值文件夹
87+
gt_to_path = osp.join(DATA_ROOT, "labels", split, seq) # 要写入的真值文件夹
7488
# 如果不存在就创建
7589
if not osp.exists(gt_to_path):
7690
os.makedirs(gt_to_path)
@@ -80,35 +94,47 @@ def process_train_test(seqs: list, frame_range: dict, cat_id: int = 0, split: st
8094

8195
for idx, img in enumerate(imgs):
8296
# img 形如: img000001.jpg
83-
if idx < int(seq_length * frame_range['start']) or idx > int(seq_length * frame_range['end']):
97+
if idx < int(seq_length * frame_range["start"]) or idx > int(
98+
seq_length * frame_range["end"]
99+
):
84100
continue
85-
101+
86102
# 第一步 产生图片软链接
87103
# print('step1, creating imgs symlink...')
88104
if opts.generate_imgs:
89-
img_to_path = osp.join(DATA_ROOT, 'images', split, seq) # 该序列图片存储位置
105+
img_to_path = osp.join(DATA_ROOT, "images", split, seq) # 该序列图片存储位置
90106

91107
if not osp.exists(img_to_path):
92108
os.makedirs(img_to_path)
93109

94-
os.symlink(osp.join(img_dir, img),
95-
osp.join(img_to_path, img)) # 创建软链接
96-
110+
os.symlink(
111+
osp.join(img_dir, img), osp.join(img_to_path, img)
112+
) # 创建软链接
113+
97114
# 第二步 产生真值文件
98115
# print('step2, generating gt files...')
99-
ann_of_current_frame = ann_of_seq[ann_of_seq[:, 0] == float(idx + 1), :] # 筛选真值文件里本帧的目标信息
116+
ann_of_current_frame = ann_of_seq[
117+
ann_of_seq[:, 0] == float(idx + 1), :
118+
] # 筛选真值文件里本帧的目标信息
100119
exist_gts.append(True if ann_of_current_frame.shape[0] != 0 else False)
101120

102-
gt_to_file = osp.join(gt_to_path, img[: -4] + '.txt')
103-
104-
with open(gt_to_file, 'w') as f_gt:
105-
for i in range(ann_of_current_frame.shape[0]):
106-
if int(ann_of_current_frame[i][6]) == 1 and int(ann_of_current_frame[i][7]) == 1 \
107-
and float(ann_of_current_frame[i][8]) > 0.25:
108-
# bbox xywh
109-
x0, y0 = int(ann_of_current_frame[i][2]), int(ann_of_current_frame[i][3])
121+
gt_to_file = osp.join(gt_to_path, img[:-4] + ".txt")
122+
123+
with open(gt_to_file, "w") as f_gt:
124+
for i in range(ann_of_current_frame.shape[0]):
125+
if (
126+
int(ann_of_current_frame[i][6]) == 1
127+
and int(ann_of_current_frame[i][7]) == 1
128+
and float(ann_of_current_frame[i][8]) > 0.25
129+
):
130+
# bbox xywh
131+
x0, y0 = int(ann_of_current_frame[i][2]), int(
132+
ann_of_current_frame[i][3]
133+
)
110134
x0, y0 = max(x0, 0), max(y0, 0)
111-
w, h = int(ann_of_current_frame[i][4]), int(ann_of_current_frame[i][5])
135+
w, h = int(ann_of_current_frame[i][4]), int(
136+
ann_of_current_frame[i][5]
137+
)
112138

113139
xc, yc = x0 + w // 2, y0 + h // 2 # 中心点 x y
114140

@@ -117,13 +143,16 @@ def process_train_test(seqs: list, frame_range: dict, cat_id: int = 0, split: st
117143
xc, yc = min(xc, 1.0), min(yc, 1.0)
118144
w, h = w / w0, h / h0
119145
w, h = min(w, 1.0), min(h, 1.0)
120-
assert w <= 1 and h <= 1, f'{w}, {h} must be normed, original size{w0}, {h0}'
121-
assert xc >= 0 and yc >= 0, f'{x0}, {y0} must be positve'
122-
assert xc <= 1 and yc <= 1, f'{x0}, {y0} must be le than 1'
146+
assert (
147+
w <= 1 and h <= 1
148+
), f"{w}, {h} must be normed, original size{w0}, {h0}"
149+
assert xc >= 0 and yc >= 0, f"{x0}, {y0} must be positve"
150+
assert xc <= 1 and yc <= 1, f"{x0}, {y0} must be le than 1"
123151
category_id = cat_id
124152

125-
write_line = '{:d} {:.6f} {:.6f} {:.6f} {:.6f}\n'.format(
126-
category_id, xc, yc, w, h)
153+
write_line = "{:d} {:.6f} {:.6f} {:.6f} {:.6f}\n".format(
154+
category_id, xc, yc, w, h
155+
)
127156

128157
f_gt.write(write_line)
129158

@@ -132,49 +161,65 @@ def process_train_test(seqs: list, frame_range: dict, cat_id: int = 0, split: st
132161
else: # test 只产生图片软链接
133162
for idx, img in enumerate(imgs):
134163
# img 形如: img000001.jpg
135-
if idx < int(seq_length * frame_range['start']) or idx > int(seq_length * frame_range['end']):
164+
if idx < int(seq_length * frame_range["start"]) or idx > int(
165+
seq_length * frame_range["end"]
166+
):
136167
continue
137-
168+
138169
# 第一步 产生图片软链接
139170
# print('step1, creating imgs symlink...')
140171
if opts.generate_imgs:
141-
img_to_path = osp.join(DATA_ROOT, 'images', split, seq) # 该序列图片存储位置
172+
img_to_path = osp.join(DATA_ROOT, "images", split, seq) # 该序列图片存储位置
142173

143174
if not osp.exists(img_to_path):
144175
os.makedirs(img_to_path)
145176

146-
os.symlink(osp.join(img_dir, img),
147-
osp.join(img_to_path, img)) # 创建软链接
177+
os.symlink(
178+
osp.join(img_dir, img), osp.join(img_to_path, img)
179+
) # 创建软链接
148180

149181
# 第三步 产生图片索引train.txt等
150-
print(f'generating img index file of {seq}')
151-
to_file = os.path.join('./mot17/', split + '.txt')
152-
with open(to_file, 'a') as f:
182+
print(f"generating img index file of {seq}")
183+
to_file = os.path.join("./mot17/", split + ".txt")
184+
with open(to_file, "a") as f:
153185
for idx, img in enumerate(imgs):
154-
if idx < int(seq_length * frame_range['start']) or idx > int(seq_length * frame_range['end']):
186+
if idx < int(seq_length * frame_range["start"]) or idx > int(
187+
seq_length * frame_range["end"]
188+
):
155189
continue
156-
157-
if split == 'test' or exist_gts[idx]:
158-
f.write('MOT17/' + 'images/' + split + '/' \
159-
+ seq + '/' + img + '\n')
190+
191+
if split == "test" or exist_gts[idx]:
192+
f.write("MOT17/" + "images/" + split + "/" + seq + "/" + img + "\n")
160193

161194
f.close()
162195

163-
164196

165-
if __name__ == '__main__':
166-
if not osp.exists('./mot17'):
167-
os.system('mkdir mot17')
197+
if __name__ == "__main__":
198+
if not osp.exists("./mot17"):
199+
os.system("mkdir mot17")
168200

169201
parser = argparse.ArgumentParser()
170-
parser.add_argument('--split', type=str, default='train', help='train, test or val')
171-
parser.add_argument('--generate_imgs', action='store_true', help='whether generate soft link of imgs')
172-
parser.add_argument('--certain_seqs', action='store_true', help='for debug')
173-
parser.add_argument('--half', action='store_true', help='half frames')
174-
parser.add_argument('--ratio', type=float, default=0.8, help='ratio of test dataset devide train dataset')
175-
parser.add_argument('--random', action='store_true', help='random split train and test')
202+
parser.add_argument("--split", type=str, default="train", help="train, test or val")
203+
parser.add_argument(
204+
"--generate_imgs",
205+
action="store_true",
206+
help="whether generate soft link of imgs",
207+
)
208+
parser.add_argument("--certain_seqs", action="store_true", help="for debug")
209+
parser.add_argument("--half", action="store_true", help="half frames")
210+
parser.add_argument(
211+
"--ratio",
212+
type=float,
213+
default=0.8,
214+
help="ratio of test dataset devide train dataset",
215+
)
216+
parser.add_argument(
217+
"--random",
218+
action="store_true",
219+
help="random split train and test",
220+
)
176221

177222
opts = parser.parse_args()
178223

179224
generate_imgs_and_labels(opts)
180-
# python tools/convert_MOT17_to_yolo.py --split train --generate_imgs
225+
# python tools/convert_MOT17_to_yolo.py --split train --generate_imgs

0 commit comments

Comments
 (0)