Skip to content

Commit

Permalink
Merge modification
Browse files Browse the repository at this point in the history
  • Loading branch information
darouwan committed Mar 26, 2024
1 parent 3762c5e commit 21443f1
Showing 1 changed file with 23 additions and 5 deletions.
28 changes: 23 additions & 5 deletions general_json2yolo.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import contextlib
import json
import shutil

import yaml
import cv2
import pandas as pd
from PIL import Image
Expand Down Expand Up @@ -254,13 +256,18 @@ def convert_coco_json(json_dir='../coco/annotations/', use_segments=False, cls91
save_dir = make_dirs() # output directory
coco80 = coco91_to_coco80_class()

categories_dict = {}

# Import json
for json_file in sorted(Path(json_dir).resolve().glob('*.json')):
fn = Path(save_dir) / 'labels' / json_file.stem.replace('instances_', '') # folder name
for json_file in sorted(Path(json_dir).resolve().glob('*coco*.json')):
fn = Path(save_dir) / 'labels' / json_file.stem.replace('instances_', '').replace('_coco','') # folder name
fn.mkdir()
with open(json_file) as f:
data = json.load(f)

# Create categories_dict
categories_dict = {item['id'] - 1: item['name'] for item in data['categories']}

# Create image dict
images = {'%g' % x['id']: x for x in data['images']}
# Create image-annotations dict
Expand Down Expand Up @@ -308,9 +315,20 @@ def convert_coco_json(json_dir='../coco/annotations/', use_segments=False, cls91
line = *(segments[i] if use_segments else bboxes[i]), # cls, box or segments
file.write(('%g ' * len(line)).rstrip() % line + '\n')

yaml_dict = {
"names": {k: v for k, v in categories_dict.items()},
# "path": "yolo_datasets",
"train": "images/train",
"val": "images/val"
}

with open((Path(save_dir) / json_file.stem).with_suffix('.yaml'), "w") as f:
yaml.dump(yaml_dict, f)
shutil.copy((Path(save_dir) / json_file.stem).with_suffix('.yaml'), (Path(save_dir) / 'classes').with_suffix('.yaml'))


def min_index(arr1, arr2):
"""Find a pair of indexes with the shortest distance.
"""Find a pair of indexes with the shortest distance.
Args:
arr1: (N, 2).
arr2: (M, 2).
Expand All @@ -324,12 +342,12 @@ def min_index(arr1, arr2):
def merge_multi_segment(segments):
"""Merge multi segments to one list.
Find the coordinates with min distance between each segment,
then connect these coordinates with one thin line to merge all
then connect these coordinates with one thin line to merge all
segments into one.
Args:
segments(List(List)): original segmentations in coco's json file.
like [segmentation1, segmentation2,...],
like [segmentation1, segmentation2,...],
each segmentation is a list of coordinates.
"""
s = []
Expand Down

0 comments on commit 21443f1

Please sign in to comment.