本文主要是介绍【实例分割】转换YOLO格式标注至COCO格式JSON,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
yolo2coco代码:
import json
import glob
import os
import cv2
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
from PIL import Image, ImageDraw, ImageFont
import numpy as npdef calculate_polygon_area(polygon):x = polygon[:, 0]y = polygon[:, 1]return 0.5 * np.abs(np.dot(x, np.roll(y, 1)) - np.dot(y, np.roll(x, 1)))def calculate_bounding_box(polygon):x_min = np.min(polygon[:, 0])y_min = np.min(polygon[:, 1])x_max = np.max(polygon[:, 0])y_max = np.max(polygon[:, 1])width = x_max - x_minheight = y_max - y_minreturn [x_min, y_min, width, height]def text_to_json_segmentation(in_labels, in_images, out_json):"""Convert instance segmentation dataset from text files generated by the function 'json_to_text_segmentation'(for YOLO) to a JSON file (for MMdet). This can be applied for Level 0/1/2 (must modify the last code):param in_labels: input folder containing the label text files:param in_images: input folder containing the image files (just for getting the image size):param out_json: output JSON file"""# Initialize the output JSON filedata = dict()data['annotations'] = []data['images'] = []# Initial the number of annotationsnum_annotations = 1 # index starts from 1# Process the text filestxt_files = glob.glob(in_labels + '/*.txt')for k in range(len(txt_files)):# Read the image to get image width and heightimg = Image.open(in_images + '/' + os.path.basename(txt_files[k]).replace('txt', 'jpg'))image_width, image_height = img.size# Creates annotation items of the image and append them to the listwith open(txt_files[k]) as f:for line in f:# Get annotation information of each line in the text fileline = [float(x) for x in line.strip().split()]class_id = int(line[0]) + 1 # index starts from 1coordinates = line[1:]polygon = np.array(coordinates).reshape(-1, 2)polygon[:, 0] = polygon[:, 0] * image_widthpolygon[:, 1] = polygon[:, 1] * image_heightarea = calculate_polygon_area(polygon)bbox = calculate_bounding_box(polygon)# Create a new annotation itemann_item = dict()ann_item['segmentation'] = [polygon.flatten().tolist()]ann_item['area'] = areaann_item['iscrowd'] = 0ann_item['image_id'] = k + 1 # index starts from 1ann_item['bbox'] = bboxann_item['category_id'] = class_idann_item['id'] = num_annotationsdata['annotations'].append(ann_item)num_annotations += 1# Create a new image item and append it to the listimg_item = dict()img_item['id'] = k + 1 # index starts from 1img_item['file_name'] = os.path.basename(txt_files[k]).replace('txt', 'jpg')img_item['height'] = image_heightimg_item['width'] = image_widthdata['images'].append(img_item)print(os.path.basename(txt_files[k]) + ' done')data['categories'] = [{'supercategory': 'class1', 'id': 1, 'name': 'class1'}]# Write the dictionary to a JSON fileprint('Writing the data to a JSON file')with open(out_json, 'w') as f:# json.dump(data, f, cls=NpEncoder)# f.write(json.dumps(data, cls=NpEncoder, indent=4))f.write(json.dumps(data, default=int, indent=4))if __name__ == '__main__':# Convert the segmentation text files to JSON text_to_json_segmentation(in_labels='labels/test',in_images='images/test',out_json='instances_test2017.json')
这篇关于【实例分割】转换YOLO格式标注至COCO格式JSON的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!