coco_to_yolo.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. import os
  2. import json
  3. import shutil
  4. import random
  5. import click
  6. import yaml
  7. from shapely.geometry import Polygon
  8. from shapely.affinity import rotate
  9. from ImageElement import ImageElement
  10. def preprocessing_for_yolov8_obb_model(coco_json: str, lang_ru=False):
  11. """
  12. Checks for Oriented Bounding Boxes in COCO format. If found,
  13. replaces the bbox and rotation of each object with the coordinates of four points in the segmentation section.
  14. Args:
  15. - coco_json (str): Path to the file containing COCO data in JSON format.
  16. - lang_ru (bool): If True, all comments will be in Russian (otherwise in English).
  17. """
  18. # Loading COCO data from file
  19. with open(coco_json, 'r') as f:
  20. coco_data = json.load(f)
  21. # Getting the list of annotations from COCO
  22. annotations = coco_data['annotations']
  23. changes = 0
  24. # Iterating through the annotations
  25. for annotation in annotations:
  26. segmentation = annotation['segmentation']
  27. # If segmentation is empty and bbox contains information, perform the operation
  28. if not segmentation and annotation['bbox']:
  29. bbox = annotation['bbox']
  30. rotation_angle = annotation['attributes']['rotation'] # Assumes rotation information is available
  31. # Converting bbox to x, y, width, height format
  32. x, y, width, height = bbox
  33. # Creating a rotated rectangle
  34. rectangle = Polygon([(x, y), (x + width, y), (x + width, y + height), (x, y + height)])
  35. # Rotating the rectangle
  36. rotated_rectangle = rotate(rectangle, rotation_angle, origin='center')
  37. # Getting the coordinates of the vertices of the rotated rectangle
  38. new_segmentation = list(rotated_rectangle.exterior.coords)
  39. # Keeping only the vertex coordinates (first 4 elements)
  40. new_segmentation = new_segmentation[:4]
  41. # Converting the list of vertices into the desired format
  42. flattened_segmentation = [coord for point in new_segmentation for coord in point]
  43. # Updating the value in the annotation
  44. annotation['segmentation'] = [flattened_segmentation]
  45. changes += 1
  46. if changes > 0:
  47. if lang_ru:
  48. print(f'Было обнаружено {changes} Oriented Bounding Boxes в файле {coco_json}')
  49. else:
  50. print(f'Found {changes} Oriented Bounding Boxes in the file {coco_json}')
  51. # Saving the updated data to the file
  52. with open(coco_json, 'w') as f:
  53. json.dump(coco_data, f)
  54. @click.command()
  55. @click.option(
  56. "--coco_dataset",
  57. default="COCO_dataset",
  58. help="Folder with COCO 1.0 format dataset (can be exported from CVAT). Default is COCO_dataset",
  59. type=str,
  60. )
  61. @click.option(
  62. "--yolo_dataset",
  63. default="YOLO_dataset",
  64. help="Folder with the resulting YOLOv8 format dataset. Default is YOLO_dataset",
  65. type=str,
  66. )
  67. @click.option(
  68. "--print_info",
  69. default=False,
  70. help="Enable/Disable processing log output mode. Default is disabled",
  71. type=bool,
  72. )
  73. @click.option(
  74. "--autosplit",
  75. help="Enable/Disable automatic split into train/val. Default is disabled (uses the CVAT annotations)",
  76. default=False,
  77. type=bool,
  78. )
  79. @click.option(
  80. "--percent_val",
  81. help="Percentage of data for validation when using autosplit=True. Default is 25%",
  82. default=25,
  83. type=float,
  84. )
  85. @click.option(
  86. "--lang_ru",
  87. help="Sets the Russian language of comments, if selected value is True. English by default",
  88. default=False,
  89. type=bool,
  90. )
  91. def main(**kwargs):
  92. # ------------------ ARG parse ------------------
  93. coco_dataset_path = kwargs["coco_dataset"]
  94. yolo_dataset_path = kwargs["yolo_dataset"]
  95. print_info = kwargs["print_info"]
  96. autosplit = kwargs["autosplit"]
  97. percent_val = kwargs["percent_val"]
  98. lang_ru = kwargs["lang_ru"]
  99. coco_annotations_path = os.path.join(coco_dataset_path, 'annotations')
  100. coco_images_path = os.path.join(coco_dataset_path, 'images')
  101. # Check the presence of the dataset
  102. if not os.path.exists(coco_dataset_path):
  103. if lang_ru:
  104. raise FileNotFoundError(f"Папка с COCO датасетом '{coco_images_path}' не найдена.")
  105. else:
  106. raise FileNotFoundError(f"The COCO dataset folder '{coco_images_path}' was not found.")
  107. # Check the presence of the images folder
  108. if not os.path.exists(coco_images_path):
  109. if lang_ru:
  110. raise FileNotFoundError(f"Папка с изображениями '{coco_images_path}' не найдена. "
  111. f"Убедитесь, что вы загрузили разметку COCO так, чтобы имелась папка со всеми изображениями.")
  112. else:
  113. raise FileNotFoundError(f"The images folder '{coco_images_path}' was not found. "
  114. f"Make sure you have uploaded COCO annotations so that there is a folder with all images.")
  115. # Check if the annotations folder exists
  116. if not os.path.exists(coco_annotations_path):
  117. if lang_ru:
  118. raise FileNotFoundError(f"The folder with json files '{coco_annotations_path}' was not found.")
  119. else:
  120. raise FileNotFoundError(f"Папка с json файлами '{coco_annotations_path}' не найдена.")
  121. list_of_image_elements = []
  122. list_of_images_path = []
  123. # Get a list of all files in the annotations folder
  124. annotation_files = os.listdir(coco_annotations_path)
  125. shutil.rmtree(yolo_dataset_path, ignore_errors=True) # Clear old data in the folder
  126. if autosplit:
  127. for folder_path in ['images', 'labels']:
  128. for type in ['validation', 'train']:
  129. path_create=os.path.join(yolo_dataset_path, type, folder_path)
  130. os.makedirs(path_create, exist_ok=True)
  131. ### Check for duplicates in different subsets ###
  132. # Create a dictionary to store files and their corresponding JSON files
  133. file_json_mapping = {}
  134. # Iterate through annotation files
  135. for annotation_file in annotation_files:
  136. json_file_path = os.path.join(coco_annotations_path, annotation_file)
  137. with open(json_file_path, 'r') as f:
  138. coco_data = json.load(f)
  139. # Get the list of images from JSON
  140. images = coco_data['images']
  141. # Iterate through images and update the file_json_mapping dictionary
  142. for image in images:
  143. file_name = image['file_name']
  144. if file_name not in file_json_mapping:
  145. file_json_mapping[file_name] = [annotation_file]
  146. else:
  147. file_json_mapping[file_name].append(annotation_file)
  148. # Check if any file has more than one occurrence
  149. for file_name, json_files in file_json_mapping.items():
  150. if len(json_files) > 1:
  151. if lang_ru:
  152. print(f"Файл {file_name} встречается в следующих JSON файлах: {json_files}")
  153. print(f'В каком-либо из JSON файлов удалите в разделе "images" словарь ' \
  154. f'с описанием этой фотографии, иначе будет ошибка при выполнении кода')
  155. raise SystemExit
  156. else:
  157. print(f"The file {file_name} appears in the following JSON files: {json_files}")
  158. print(f"Remove the dictionary describing this photo from the 'images' section in " \
  159. f"one of the JSON files, otherwise there will be an error when running the code.")
  160. raise SystemExit
  161. ### Run the main code: ###
  162. # Iterate through annotation files
  163. for annotation_file in annotation_files:
  164. # Parse the image file name from the annotation file
  165. type_data = os.path.splitext(annotation_file)[0].split('_')[-1]
  166. json_file_path = os.path.join(coco_annotations_path, annotation_file) # path to the json file
  167. # Preprocessing for YOLOv8-obb
  168. preprocessing_for_yolov8_obb_model(coco_json=json_file_path, lang_ru=lang_ru)
  169. # Create folder if it doesn't exist
  170. if not autosplit:
  171. for folder_path in ['images', 'labels']:
  172. path_create=os.path.join(yolo_dataset_path, type_data.lower(), folder_path)
  173. os.makedirs(path_create, exist_ok=True)
  174. # Open coco json
  175. with open(json_file_path, 'r') as f:
  176. coco_data = json.load(f)
  177. # Get the list of images from JSON
  178. images = coco_data['images']
  179. # Create a dictionary with class information
  180. coco_categories = coco_data['categories']
  181. categories_dict = {category['id']-1: category['name'] for category in coco_categories}
  182. # Print information
  183. if print_info:
  184. if lang_ru:
  185. print(f'Осуществляется обработка {annotation_file}')
  186. print(f'Имеющиеся классы: {categories_dict}')
  187. else:
  188. print(f'Processing {annotation_file}')
  189. print(f'Available classes: {categories_dict}')
  190. print('-----------------\n')
  191. #### Additional check for the presence of all image files
  192. # Get the list of image files with annotations in COCO
  193. annotated_images = set([entry['file_name'] for entry in coco_data['images']])
  194. # Get the list of files in the images folder
  195. all_images = set(os.listdir(coco_images_path))
  196. # Check that all images from COCO are annotated
  197. if not annotated_images.issubset(all_images):
  198. missing_images = annotated_images - all_images
  199. if lang_ru:
  200. raise FileNotFoundError(f"Некоторые изображения, для которых есть разметка в {json_file_path}, отсутствуют в папке с изображениями. "
  201. f"Отсутствующие изображения: {missing_images}")
  202. else:
  203. raise FileNotFoundError(f"Some images annotated in {json_file_path} are missing from the images folder. "
  204. f"Missing images: {missing_images}")
  205. # Iterate through images and read annotations
  206. for image in images:
  207. image_id = image['id']
  208. file_name = image['file_name']
  209. path_image_initial = os.path.join(coco_images_path, file_name)
  210. # Find corresponding annotations for the image
  211. list_of_lists_annotations = [ann['segmentation'] for ann in coco_data['annotations'] if ann['image_id'] == image_id]
  212. try:
  213. annotations = [sublist[0] for sublist in list_of_lists_annotations]
  214. except:
  215. if lang_ru:
  216. print(f"В разметке фотографии {file_name} имеются объекты, не являющиеся полигонами. "\
  217. f"\nНеобходимо, чтобы все объекты для обучения YOLOv8-seg были размечены как полигоны! "\
  218. f"\nИсправьте это и заново выгрузите датасет.")
  219. else:
  220. print(f"The annotations for the image {file_name} contain objects that are not polygons. "\
  221. f"\nAll objects for training YOLOv8-seg must be annotated as polygons! "\
  222. f"\nPlease correct this and reload the dataset.")
  223. raise SystemExit
  224. classes = [ann['category_id']-1 for ann in coco_data['annotations'] if ann['image_id'] == image_id]
  225. if autosplit:
  226. # Generate a random number from 1 to 100
  227. random_number = random.randint(1, 100)
  228. # If the random number <= percent_val, then type_dataset = "validation", otherwise "train"
  229. type_dataset = "validation" if random_number <= percent_val else "train"
  230. else:
  231. type_dataset = type_data.lower()
  232. # Create an instance of the ImageElement class:
  233. element = ImageElement(
  234. path_image_initial=path_image_initial,
  235. path_label_initial=json_file_path,
  236. img_width=image['width'],
  237. img_height=image['height'],
  238. image_id=image_id,
  239. type_data=type_dataset,
  240. path_label_final=os.path.join(yolo_dataset_path, type_dataset,
  241. 'labels', os.path.splitext(file_name)[0]+'.txt'),
  242. path_image_final=os.path.join(yolo_dataset_path, type_dataset,
  243. 'images', file_name),
  244. classes_names=[categories_dict[cl] for cl in classes],
  245. classes_ids=classes,
  246. point_list=annotations,
  247. )
  248. list_of_image_elements.append(element)
  249. list_of_images_path.append(file_name)
  250. # Print information about ImageElement if necessary
  251. if print_info:
  252. print(element)
  253. ### Check for the presence of all images in the images folder
  254. # Get the list of files in the folder
  255. files_in_folder = set(os.listdir(coco_images_path))
  256. # Check that all files from the list are present in the folder
  257. missing_files = set(list_of_images_path) - files_in_folder
  258. extra_files = files_in_folder - set(list_of_images_path)
  259. # Display notification
  260. if missing_files:
  261. if lang_ru:
  262. print(f"Отсутствующие файлы в папке {coco_images_path}: {missing_files}")
  263. else:
  264. print(f"Missing files in the folder {coco_images_path}: {missing_files}")
  265. if extra_files:
  266. if lang_ru:
  267. print(f"Лишние файлы в папке {coco_images_path}: {extra_files}")
  268. else:
  269. print(f"Extra files in the folder {coco_images_path}: {extra_files}")
  270. # Creating data.yaml configuration:
  271. # Create a data structure for writing to data.yaml
  272. data_dict = {
  273. 'names': list(categories_dict.values()),
  274. 'nc': len(categories_dict),
  275. 'test': 'test/images',
  276. 'train': 'train/images',
  277. 'val': 'validation/images'
  278. }
  279. if autosplit:
  280. data_dict['test'] = 'validation/images'
  281. # Path to the data.yaml file
  282. data_yaml_path = f"{yolo_dataset_path}/data.yaml"
  283. # Write data to the data.yaml file
  284. with open(data_yaml_path, 'w') as file:
  285. yaml.dump(data_dict, file, default_flow_style=False)
  286. # Creating labels and copying images to folders:
  287. for element in list_of_image_elements:
  288. # Copying the image
  289. shutil.copy(element.path_image_initial, element.path_image_final)
  290. # Creating a YOLO annotation file
  291. with open(element.path_label_final, 'w') as yolo_label_file:
  292. for i in range(len(element.classes_ids)):
  293. class_id = element.classes_ids[i]
  294. class_name = element.classes_names[i]
  295. points = element.point_list[i]
  296. output_string = f'{class_id}'
  297. for i, point in enumerate(points):
  298. if i % 2 == 0:
  299. result = round(point / element.img_width, 9)
  300. else:
  301. result = round(point / element.img_height, 9)
  302. output_string += f' {result:.6f}'
  303. # Writing data to the file
  304. yolo_label_file.write(output_string+'\n')
  305. if lang_ru:
  306. print(f"Итоговая разметка в формате YOLOv8 расположена в папке - {yolo_dataset_path}.")
  307. else:
  308. print(f"The final YOLOv8 format annotations are located in the folder - {yolo_dataset_path}.")
  309. if __name__ == "__main__":
  310. main()