visdrone2mot.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import glob
  15. import os
  16. import os.path as osp
  17. import cv2
  18. import argparse
  19. import numpy as np
  20. import random
  21. # The object category indicates the type of annotated object,
  22. # (i.e., ignored regions(0), pedestrian(1), people(2), bicycle(3), car(4), van(5), truck(6), tricycle(7), awning-tricycle(8), bus(9), motor(10),others(11))
  23. # Extract single class or multi class
  24. isExtractMultiClass = False
  25. # The sequence is excluded because there are too few vehicles
  26. exclude_seq = ["uav0000086_00000_v"]
  27. def mkdir_if_missing(d):
  28. if not osp.exists(d):
  29. os.makedirs(d)
  30. def genGtFile(seqPath, outPath, classes=[]):
  31. id_idx = 0
  32. old_idx = -1
  33. with open(seqPath, 'r') as singleSeqFile:
  34. motLine = []
  35. allLines = singleSeqFile.readlines()
  36. for line in allLines:
  37. line = line.replace('\n', '')
  38. line = line.split(',')
  39. # exclude occlusion!='2'
  40. if line[-1] != '2' and line[7] in classes:
  41. if old_idx != int(line[1]):
  42. id_idx += 1
  43. old_idx = int(line[1])
  44. newLine = line[0:6]
  45. newLine[1] = str(id_idx)
  46. newLine.append('1')
  47. if (len(classes) > 1 and isExtractMultiClass):
  48. class_index = str(classes.index(line[7]) + 1)
  49. newLine.append(class_index)
  50. else:
  51. newLine.append('1') # use permenant class '1'
  52. newLine.append('1')
  53. motLine.append(newLine)
  54. mkdir_if_missing(outPath)
  55. gtFilePath = osp.join(outPath, 'gt.txt')
  56. with open(gtFilePath, 'w') as gtFile:
  57. motLine = list(map(lambda x: str.join(',', x), motLine))
  58. motLineStr = str.join('\n', motLine)
  59. gtFile.write(motLineStr)
  60. def genSeqInfo(img1Path, seqName):
  61. imgPaths = glob.glob(img1Path + '/*.jpg')
  62. seqLength = len(imgPaths)
  63. if seqLength > 0:
  64. image1 = cv2.imread(imgPaths[0])
  65. imgHeight = image1.shape[0]
  66. imgWidth = image1.shape[1]
  67. else:
  68. imgHeight = 0
  69. imgWidth = 0
  70. seqInfoStr = f'''[Sequence]\nname={seqName}\nimDir=img1\nframeRate=30\nseqLength={seqLength}\nimWidth={imgWidth}\nimHeight={imgHeight}\nimExt=.jpg'''
  71. seqInfoPath = img1Path.replace('/img1', '')
  72. with open(seqInfoPath + '/seqinfo.ini', 'w') as seqFile:
  73. seqFile.write(seqInfoStr)
  74. def copyImg(img1Path, gtTxtPath, outputFileName):
  75. with open(gtTxtPath, 'r') as gtFile:
  76. allLines = gtFile.readlines()
  77. imgList = []
  78. for line in allLines:
  79. imgIdx = int(line.split(',')[0])
  80. if imgIdx not in imgList:
  81. imgList.append(imgIdx)
  82. seqName = gtTxtPath.replace('./{}/'.format(outputFileName),
  83. '').replace('/gt/gt.txt', '')
  84. sourceImgPath = osp.join('./sequences', seqName,
  85. '{:07d}.jpg'.format(imgIdx))
  86. os.system(f'cp {sourceImgPath} {img1Path}')
  87. def genMotLabels(datasetPath, outputFileName, classes=['2']):
  88. mkdir_if_missing(osp.join(datasetPath, outputFileName))
  89. annotationsPath = osp.join(datasetPath, 'annotations')
  90. annotationsList = glob.glob(osp.join(annotationsPath, '*.txt'))
  91. for annotationPath in annotationsList:
  92. seqName = annotationPath.split('/')[-1].replace('.txt', '')
  93. if seqName in exclude_seq:
  94. continue
  95. mkdir_if_missing(osp.join(datasetPath, outputFileName, seqName, 'gt'))
  96. mkdir_if_missing(osp.join(datasetPath, outputFileName, seqName, 'img1'))
  97. genGtFile(annotationPath,
  98. osp.join(datasetPath, outputFileName, seqName, 'gt'), classes)
  99. img1Path = osp.join(datasetPath, outputFileName, seqName, 'img1')
  100. gtTxtPath = osp.join(datasetPath, outputFileName, seqName, 'gt/gt.txt')
  101. copyImg(img1Path, gtTxtPath, outputFileName)
  102. genSeqInfo(img1Path, seqName)
  103. def deleteFileWhichImg1IsEmpty(mot16Path, dataType='train'):
  104. path = mot16Path
  105. data_images_train = osp.join(path, 'images', f'{dataType}')
  106. data_images_train_seqs = glob.glob(data_images_train + '/*')
  107. if (len(data_images_train_seqs) == 0):
  108. print('dataset is empty!')
  109. for data_images_train_seq in data_images_train_seqs:
  110. data_images_train_seq_img1 = osp.join(data_images_train_seq, 'img1')
  111. if len(glob.glob(data_images_train_seq_img1 + '/*.jpg')) == 0:
  112. print(f"os.system(rm -rf {data_images_train_seq})")
  113. os.system(f'rm -rf {data_images_train_seq}')
  114. def formatMot16Path(dataPath, pathType='train'):
  115. train_path = osp.join(dataPath, 'images', pathType)
  116. mkdir_if_missing(train_path)
  117. os.system(f'mv {dataPath}/* {train_path}')
  118. def VisualGt(dataPath, phase='train'):
  119. seqList = sorted(glob.glob(osp.join(dataPath, 'images', phase) + '/*'))
  120. seqIndex = random.randint(0, len(seqList) - 1)
  121. seqPath = seqList[seqIndex]
  122. gt_path = osp.join(seqPath, 'gt', 'gt.txt')
  123. img_list_path = sorted(glob.glob(osp.join(seqPath, 'img1', '*.jpg')))
  124. imgIndex = random.randint(0, len(img_list_path))
  125. img_Path = img_list_path[imgIndex]
  126. frame_value = int(img_Path.split('/')[-1].replace('.jpg', ''))
  127. gt_value = np.loadtxt(gt_path, dtype=int, delimiter=',')
  128. gt_value = gt_value[gt_value[:, 0] == frame_value]
  129. get_list = gt_value.tolist()
  130. img = cv2.imread(img_Path)
  131. colors = [[255, 0, 0], [255, 255, 0], [255, 0, 255], [0, 255, 0],
  132. [0, 255, 255], [0, 0, 255]]
  133. for seq, _id, pl, pt, w, h, _, bbox_class, _ in get_list:
  134. cv2.putText(img,
  135. str(bbox_class), (pl, pt), cv2.FONT_HERSHEY_PLAIN, 2,
  136. colors[bbox_class - 1])
  137. cv2.rectangle(
  138. img, (pl, pt), (pl + w, pt + h),
  139. colors[bbox_class - 1],
  140. thickness=2)
  141. cv2.imwrite('testGt.jpg', img)
  142. def VisualDataset(datasetPath, phase='train', seqName='', frameId=1):
  143. trainPath = osp.join(datasetPath, 'labels_with_ids', phase)
  144. seq1Paths = osp.join(trainPath, seqName)
  145. seq_img1_path = osp.join(seq1Paths, 'img1')
  146. label_with_idPath = osp.join(seq_img1_path, '%07d' % frameId) + '.txt'
  147. image_path = label_with_idPath.replace('labels_with_ids', 'images').replace(
  148. '.txt', '.jpg')
  149. seqInfoPath = str.join('/', image_path.split('/')[:-2])
  150. seqInfoPath = seqInfoPath + '/seqinfo.ini'
  151. seq_info = open(seqInfoPath).read()
  152. width = int(seq_info[seq_info.find('imWidth=') + 8:seq_info.find(
  153. '\nimHeight')])
  154. height = int(seq_info[seq_info.find('imHeight=') + 9:seq_info.find(
  155. '\nimExt')])
  156. with open(label_with_idPath, 'r') as label:
  157. allLines = label.readlines()
  158. images = cv2.imread(image_path)
  159. for line in allLines:
  160. line = line.split(' ')
  161. line = list(map(lambda x: float(x), line))
  162. c1, c2, w, h = line[2:6]
  163. x1 = c1 - w / 2
  164. x2 = c2 - h / 2
  165. x3 = c1 + w / 2
  166. x4 = c2 + h / 2
  167. cv2.rectangle(
  168. images, (int(x1 * width), int(x2 * height)),
  169. (int(x3 * width), int(x4 * height)), (255, 0, 0),
  170. thickness=2)
  171. cv2.imwrite('test.jpg', images)
  172. def gen_image_list(dataPath, datType):
  173. inputPath = f'{dataPath}/images/{datType}'
  174. pathList = glob.glob(inputPath + '/*')
  175. pathList = sorted(pathList)
  176. allImageList = []
  177. for pathSingle in pathList:
  178. imgList = sorted(glob.glob(osp.join(pathSingle, 'img1', '*.jpg')))
  179. for imgPath in imgList:
  180. allImageList.append(imgPath)
  181. with open(f'{dataPath}.{datType}', 'w') as image_list_file:
  182. allImageListStr = str.join('\n', allImageList)
  183. image_list_file.write(allImageListStr)
  184. def gen_labels_mot(MOT_data, phase='train'):
  185. seq_root = './{}/images/{}'.format(MOT_data, phase)
  186. label_root = './{}/labels_with_ids/{}'.format(MOT_data, phase)
  187. mkdir_if_missing(label_root)
  188. seqs = [s for s in os.listdir(seq_root)]
  189. print('seqs => ', seqs)
  190. tid_curr = 0
  191. tid_last = -1
  192. for seq in seqs:
  193. seq_info = open(osp.join(seq_root, seq, 'seqinfo.ini')).read()
  194. seq_width = int(seq_info[seq_info.find('imWidth=') + 8:seq_info.find(
  195. '\nimHeight')])
  196. seq_height = int(seq_info[seq_info.find('imHeight=') + 9:seq_info.find(
  197. '\nimExt')])
  198. gt_txt = osp.join(seq_root, seq, 'gt', 'gt.txt')
  199. gt = np.loadtxt(gt_txt, dtype=np.float64, delimiter=',')
  200. seq_label_root = osp.join(label_root, seq, 'img1')
  201. mkdir_if_missing(seq_label_root)
  202. for fid, tid, x, y, w, h, mark, label, _ in gt:
  203. # if mark == 0 or not label == 1:
  204. # continue
  205. fid = int(fid)
  206. tid = int(tid)
  207. if not tid == tid_last:
  208. tid_curr += 1
  209. tid_last = tid
  210. x += w / 2
  211. y += h / 2
  212. label_fpath = osp.join(seq_label_root, '{:07d}.txt'.format(fid))
  213. label_str = '0 {:d} {:.6f} {:.6f} {:.6f} {:.6f}\n'.format(
  214. tid_curr, x / seq_width, y / seq_height, w / seq_width,
  215. h / seq_height)
  216. with open(label_fpath, 'a') as f:
  217. f.write(label_str)
  218. def parse_arguments():
  219. parser = argparse.ArgumentParser(description='input method')
  220. parser.add_argument("--transMot", type=bool, default=False)
  221. parser.add_argument("--genMot", type=bool, default=False)
  222. parser.add_argument("--formatMotPath", type=bool, default=False)
  223. parser.add_argument("--deleteEmpty", type=bool, default=False)
  224. parser.add_argument("--genLabelsMot", type=bool, default=False)
  225. parser.add_argument("--genImageList", type=bool, default=False)
  226. parser.add_argument("--visualImg", type=bool, default=False)
  227. parser.add_argument("--visualGt", type=bool, default=False)
  228. parser.add_argument("--data_name", type=str, default='visdrone_vehicle')
  229. parser.add_argument("--phase", type=str, default='train')
  230. parser.add_argument("--classes", type=str, default='4,5,6,9')
  231. return parser.parse_args()
  232. if __name__ == "__main__":
  233. args = parse_arguments()
  234. classes = args.classes.split(',')
  235. datasetPath = './'
  236. dataName = args.data_name
  237. phase = args.phase
  238. if args.transMot:
  239. genMotLabels(datasetPath, dataName, classes)
  240. formatMot16Path(dataName, pathType=phase)
  241. mot16Path = f'./{dataName}'
  242. deleteFileWhichImg1IsEmpty(mot16Path, dataType=phase)
  243. gen_labels_mot(dataName, phase=phase)
  244. gen_image_list(dataName, phase)
  245. if args.genMot:
  246. genMotLabels(datasetPath, dataName, classes)
  247. if args.formatMotPath:
  248. formatMot16Path(dataName, pathType=phase)
  249. if args.deleteEmpty:
  250. mot16Path = f'./{dataName}'
  251. deleteFileWhichImg1IsEmpty(mot16Path, dataType=phase)
  252. if args.genLabelsMot:
  253. gen_labels_mot(dataName, phase=phase)
  254. if args.genImageList:
  255. gen_image_list(dataName, phase)
  256. if args.visualGt:
  257. VisualGt(f'./{dataName}', phase)
  258. if args.visualImg:
  259. seqName = 'uav0000137_00458_v'
  260. frameId = 43
  261. VisualDataset(
  262. f'./{dataName}', phase=phase, seqName=seqName, frameId=frameId)