Skip to content

Instantly share code, notes, and snippets.

@iKrishneel
Last active June 5, 2024 06:40
Show Gist options
  • Save iKrishneel/e6f08b9766ba34ca69bfd067e92c6077 to your computer and use it in GitHub Desktop.
Save iKrishneel/e6f08b9766ba34ca69bfd067e92c6077 to your computer and use it in GitHub Desktop.
import os
import json
from PIL import Image
def labelme_to_coco(labelme_json_folder, output_json_file):
# Create the basic structure for COCO
coco_output = {
"info": {},
"licenses": [],
"images": [],
"annotations": [],
"categories": []
}
# Initialize counters and maps
annotation_id = 1
category_id = 1
category_map = {}
# Read each LabelMe JSON file
for json_file in os.listdir(labelme_json_folder):
if not json_file.endswith('.json'):
continue
json_path = os.path.join(labelme_json_folder, json_file)
with open(json_path) as f:
labelme_data = json.load(f)
# Process image info
image_path = os.path.join(labelme_json_folder, labelme_data['imagePath'])
image = Image.open(image_path)
width, height = image.size
image_info = {
"id": len(coco_output["images"]) + 1,
"file_name": labelme_data['imagePath'],
"width": width,
"height": height
}
coco_output["images"].append(image_info)
# Process annotations
for shape in labelme_data['shapes']:
label = shape['label']
if label not in category_map:
category_map[label] = category_id
coco_output["categories"].append({
"id": category_id,
"name": label,
"supercategory": "none"
})
category_id += 1
polygon = shape['points']
segmentation = [point for sublist in polygon for point in sublist]
min_x = min([p[0] for p in polygon])
max_x = max([p[0] for p in polygon])
min_y = min([p[1] for p in polygon])
max_y = max([p[1] for p in polygon])
bbox = [min_x, min_y, max_x - min_x, max_y - min_y]
annotation = {
"id": annotation_id,
"image_id": image_info["id"],
"category_id": category_map[label],
"segmentation": [segmentation],
"area": bbox[2] * bbox[3],
"bbox": bbox,
"iscrowd": 0
}
coco_output["annotations"].append(annotation)
annotation_id += 1
# Save to COCO JSON file
with open(output_json_file, 'w') as f:
json.dump(coco_output, f, indent=4)
# Example usage:
labelme_json_folder = 'data/'
output_json_file = 'data/coco_annotations.json'
labelme_to_coco(labelme_json_folder, output_json_file)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment