[PYTHON] Convert json format data to txt (using yolo)

I want to convert json format data to txt format data to use yolo.

What i did

The code to convert json to txt was on the net, but I didn't know how to use it, so I decided to create it myself. (I may have seen it because I cut and pasted a part of various codes)

Code below

import json
import glob

data_path = glob.glob("train_json/*.json")
img_data_path = glob.glob("train_img/*.jpg ")
cate_list = ["Car","Pedestrian","Truck","Signal","Signs","Bicycle","Motorbike","Bus","Svehicle","Train"]
box_list  = ["x1","x2","y1","y2"]
input_shape = [640,640]
img_output = "train_img_data"

with open("voc_classes.txt","w") as f:
    f.write('\n'.join(cate_list))

list_file = open("2007_train.txt","w")

def class_encord(class_name):
    cate_id = {"Car":0,"Pedestrian":1,"Truck":2,"Signal":3,"Signs":4,"Bicycle":5,"Motorbike":6,"Bus":7,"SVehicle":8,"Train":9}
    return cate_id[class_name]

def img_box_resize(img_path,input_shape,label_box):
    img = Image.open(img_path)
    iw , ih = img.size
    w, h = input_shape
    scale = min(w/iw,h/ih)
    nw = int(scale*iw)
    nh = int(scale*ih)
    dx = (w-nw)//2
    dy = (h-nh)//2
    img_data = 0 
    image = img.resize((nw,nh),Image.BICUBIC)
    new_image = Image.new("RGB", (w,h), (128,128,128))
    new_image.paste(image, (dx, dy))    
    bax_lx = label_box[0]
    box_ly = label_box[1]
    box_rx = label_box[2]
    box_ry = label_box[3]
    
    new_box_lx = int(box_lx*scale) + int(dx)
    new_box_ly = int(box_ly*scale) + int(dy)
    new_box_rx = int(box_rx*scale) - int(dx)
    new_box_ry = int(box_ry*scale) - int(dy)
    box_list = []
    box_list.append(new_box_lx)
    box_list.append(new_box_ly)
    box_list.append(new_box_rx)
    box_list.append(new_box_ry)
    return new_image , box_list

def convert(data_file,list_file,input_img_path,output_img_path):
    with open(data_file) as j_f:
        load_json = json.load(j_f)
        datas = load_json["labels"]  
        for data in datas:
            box = data["box2d"]
            json_box = []  
            new_img , box_list = img_box_resize(img_path,input_shape,box)
            for i in range(4):
                json_box.append(box_list[i])
            category = data["category"]
            category_num = class_encord(category)
            list_file.write(" "+",".join([str(a) for a in json_box])+","+str(category_num))
            new_img.save(output_img_path+"/"+input_img_path)
            

for data_file in data_path:
    for img_path in img_data_path:
        data = data_file
        list_file.write(output_img_path+"/"+input_img_path)
        convert(data_file,list_file,img_path,img_output)
        list_file.write("\n")

list_file.close()

Please change according to the environment where the above variables are used. It will be converted according to the size of input_shape.

Should work: sweat_smile: (I worked with this)

Recommended Posts

Convert json format data to txt (using yolo)
Convert xml format data to txt format data (yolov3)
Convert Excel data to JSON with python
[Introduction to Python] How to handle JSON format data
I convert AWS JSON data to CSV like this
Convert / return class object to JSON format in Python
How to convert Json file to CSV format or EXCEL format
Try writing JSON format data to object storage Cloudian/S3
Convert Pascal VOC format xml file to COCO format json file
Convert Tweepy Status object to JSON
Export DB data in json format
Parsing CSV format data using SQL
Convert from pdf to txt 2 [pyocr]
Merge JSON format data with Ansible
Convert matplotlib graphs to emf file format
Convert XML document stored in XML database (BaseX) to CSV format (using Python)
Convert (compress) formatted JSON string to 1-line JSON
[MNIST] Convert data to PNG for keras
Use pandas to convert grid data to row-holding (?) Data
Convert FX 1-minute data to 5-minute data with Python
Convert PDF attached to email to text format
Convert array (struct) to json with golang
How to convert DateTimeField format in Django
Try to extract specific data from JSON format data in object storage Cloudian/S3
Convert csv, tsv data to matrix with python --using MovieLens as an example
Convert Mobile Suica usage history PDF to pandas Data Frame format with tabula-py
[Tensorflowjs_converter] How to convert Tensorflow model to Tensorflow.js format
Convert data with shape (number of data, 1) to (number of data,) with numpy.
Just add the python array to the json data
Anyway, I want to check JSON data easily
Convert voice to text using Azure Speech SDK
100 language processing knock-20 (using pandas): reading JSON data
Convert STL to Voxel mesh using Python VTK
How to search HTML data using Beautiful Soup
Convert binary packages for windows to wheel format
Convert strings to character-by-character list format with python
Convert to HSV
100 language processing knock-92 (using Gensim): application to analogy data
How to scrape horse racing data using pandas read_html
How to convert horizontally held data to vertically held data with pandas
Convert Qiita articles to Jekyll post format for backup
How to convert JSON file to CSV file with Python Pandas
Write data to KINTONE using the Python requests module
Aggregate event data into one-user, one-line format using pandas
Convert translation resource files (.po) to XLIFF format (.xlf)
[Technical book] Introduction to data analysis using Python -1 Chapter Introduction-
Convert mesh data exported from SpriteUV2 to a format that can be imported by Spine