-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathJSON_to_txt.py
56 lines (49 loc) · 2.19 KB
/
JSON_to_txt.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# -*- coding: utf-8 -*-
"""
Created on Sun May 31 00:44:00 2020
@author: nikhi
"""
import os
import json
from os import listdir, getcwd
from os.path import join
classes = ["person","bicycle","car","motorcycle","airplane","bus","train",
"truck","boat","traffic light","fire hydrant","stop sign","parking meter",
"bench","bird","cat","dog","horse","sheep","cow","elephant","bear","zebra",
"giraffe","backpack","umbrella","handbag","tie","suitcase","frisbee","skis",
"snowboard","sports ball","kite","baseball bat","baseball glove","skateboard",
"surfboard","tennis racket","bottle","wine glass","cup","fork","knife","spoon",
"bowl","banana","apple","sandwich","orange","broccoli","carrot","hot dog","pizza",
"donut","cake","chair","couch","potted plant","bed","dining table","toilet","tv",
"laptop","mouse","remote","keyboard","cell phone","microwave","oven","toaster","sink",
"refrigerator","book","clock","vase","scissors","teddy bear","hair drier","toothbrush"]
#box form[x,y,w,h]
def convert(size,box):
#dw = 1./size[0]
#dh = 1./size[1]
x = box[0]
y = box[1]
w = box[2]
h = box[3]
return (x,y,w,h)
def convert_annotation():
with open('G:\My Drive\ML_DL_Stuff\Object Detection\MSCOCO_data\instances_val2017.json','r') as f:
data = json.load(f)
for item in data['images']:
image_id = item['id']
file_name = item['file_name']
width = item['width']
height = item['height']
value = filter(lambda item1: item1['image_id'] == image_id,data['annotations'])
outfile = open('G:\My Drive\ML_DL_Stuff\Object Detection\MSCOCO_data/val2017_yolo_GT_text_files/%s.txt'%(file_name[:-4]), 'a+')
for item2 in value:
category_id = item2['category_id']
value1 = list(filter(lambda item3: item3['id'] == category_id,data['categories']))
name = value1[0]['name']
class_id = classes.index(name)
box = item2['bbox']
bb = convert((width,height),box)
outfile.write(str(class_id)+" "+" ".join([str(a) for a in bb]) + '\n')
outfile.close()
if __name__ == '__main__':
convert_annotation()