-
Notifications
You must be signed in to change notification settings - Fork 2
/
img2json.py
214 lines (162 loc) · 5.54 KB
/
img2json.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
import os
import copy
import cv2
from collections import OrderedDict
import json
import gt2coco
from tqdm import tqdm
# allCategoryList = ['bottle', 'plastic']
# allCategoryList = list(gt2coco.labelIdx.keys())
path = "./"
allgttxt = []
fileNumber = {}
idUniq = 1
def imgID(fileList):
global fileNumber
for idx, file in enumerate(iterable=fileList, start=1):
toJpg = file.split(".")[0]
fileNumber[toJpg] = idx
# get gt txt list
def getfilelist(pathDir):
filelist = os.listdir(pathDir)
file_list_txt = [file for file in filelist]
return file_list_txt
#read_gt_file
def readgtfile(pathdir, filename):
f = open(pathdir + filename, 'r')
while True:
line = f.readline()
if not line: break
allgttxt.append(line)
f.close()
return allgttxt
#split allgttxt
def splitgttxt(allgttxt):
splitlist = allgttxt.split(",")
return splitlist
# make info
def makeInfo():
info = OrderedDict()
info["description"] = "DSL"
info["url"] = "https://supercom.korea.ac.kr/"
info["version"] = "0.2"
info["date_created"] = "2021/07/13"
return info
# make images
# full screen image
def makeImages(pathDir):
print('make images annotations ...')
global idUniq
allFileList = os.listdir(pathDir)
imgExt = ['.jpg', '.jpeg', '.JPG', '.JPEG', 'png', 'PNG']
fileList = [f for f in allFileList if f.endswith(tuple(imgExt))]
images = []
licenses = OrderedDict()
for i in tqdm(fileList):
if i.split('.')[-1] is not 'json':
imgShape = cv2.imread(os.path.join(pathDir, i)).shape
licenses["license"] = 1
licenses["file_name"] = i
licenses["coco_url"] = "None"
licenses["height"] = imgShape[0]
licenses["width"] = imgShape[1]
licenses["date_captured"] = "2020-03-10 15:00:00"
licenses["flickr_rul"] = "None"
licenses["id"] = idUniq
idUniq += 1
images.append(copy.deepcopy(licenses))
licenses.clear()
return images
def makeLicenses():
licenseList = []
licenseButton = OrderedDict()
licenseButton["url"] = "https://supercom.korea.ac.kr/"
licenseButton["id"] = 1
licenseButton["name"] = "Attribution-NonCommercial License"
licenseList.append(licenseButton)
return licenseList
# make categories
def makeCategories():
categoryList = []
category = OrderedDict()
idNum = 1
# do not change order
# supercatetory text
# supercatetory Switch
allCategoryList = list(gt2coco.labelIdx.keys())
for name in allCategoryList:
category["supercategory"] = name
category["id"] = idNum
idNum += 1
category["name"] = name
categoryList.append(copy.deepcopy(category))
category.clear()
return categoryList
def jsonSave(jsonObj, fileName):
with open(fileName, 'w', encoding='utf-8') as make_file: # "./" +
json.dump(jsonObj, make_file, indent="\t")
def writeJson(jsonObj, dir, fileName):
jsonObj["categories"] = makeCategories()
jsonSave(jsonObj, os.path.join(dir, fileName))
print('\n----------write json file----------\n')
# make one annotation
def makeAnnotation(allgttxt, number, annotationsID):
annotation = OrderedDict()
splitgttxt = allgttxt.split(",")
x = int(splitgttxt[0])
y = int(splitgttxt[1])
w = int(splitgttxt[2]) - int(splitgttxt[0]) # x
h = int(splitgttxt[5]) - int(splitgttxt[1]) # y
segeList = [[x, y, x+w, y, x+w, y+h, x, y+h]]
catrgoryName = splitgttxt[-1].split("\n")[0][0]
categoryID = gt2coco.labelIdx[catrgoryName]
print(catrgoryName, categoryID)
# if catrgoryName == 'bottle':
# categoryID = 1
# # elif catrgoryName == 'can':
# # categoryID = 2
# # elif catrgoryName == 'general':
# # categoryID = 3
# # elif catrgoryName == 'iron':
# # categoryID = 3
# # elif catrgoryName == 'paper':
# # categoryID = 4
# elif catrgoryName == 'plastic':
# categoryID = 2
# # elif catrgoryName == 'strofoam':
# # categoryID = 6
# # elif catrgoryName == 'vinyl':
# # categoryID = 7
annotation["segmentation"] = segeList
annotation["area"] = w * h
annotation["iscrowd"] = 0
annotation["image_id"] = int(number)
annotation["bbox"] = [x, y, w, h]
annotation["category_id"] = categoryID
annotation["id"] = annotationsID
return annotation
def main(txtdir, imgdir, jsonDir, annoName):
jsonWhole = OrderedDict()
annotations = []
count = 0
annotationsID = 1
jsonFileName = annoName + ".json"
# jsonDir = "./annotations/"
filelist = getfilelist(txtdir) # txt file read
imgID(filelist)
jsonWhole["info"] = makeInfo()
jsonWhole["licenses"] = makeLicenses()
print("make images ...")
jsonWhole["images"] = makeImages(imgdir)
jsonWhole["categories"] = makeCategories()
#json
print("write json about images")
writeJson(jsonWhole, jsonDir, jsonFileName)
if __name__ == '__main__':
serverSourceDir = "E:/dataset/save_gt/"
serverResultDir = "E:/dataset/save_img/"
localSourceDir = "E:/dataset/"
localResultDir = "instances_train2017"
labelPath = "./jinOut/labels/"
jsonPath = "./jinOut/" + localResultDir + ".json"
main(serverSourceDir, serverResultDir, localSourceDir, localResultDir)