forked from Chrpe17/BorMastersThesis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdata_clean.py
182 lines (156 loc) · 5.93 KB
/
data_clean.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 19 20:55:03 2022
@author: Carl Johan Danbjørg
Code to allign imagedata:
- from .png to .jpg
- rename s A=austria and I=Italy
Analyze for label frequency
Distribute labels equally to Train, Validation and Test
"""
import os
import shutil
import json
from PIL import Image
import pandas as pd
import random
#dictionary for all images
all_img={}
#get all files from Portugal and rename
def rename(directory):
a=0
for x in os.listdir(directory):
if x.startswith("image"):
a+=1
z=x[5:len(x)]
prefix='I'
os.rename(directory+x,directory+prefix+z)
print(f'{a} images in {directory} renamed')
return
#get all files with format .png and replace with a .jpg version
def convert_png(directory,error_directory):
#make err directory if not available
os.makedirs(error_directory,exist_ok=True)
b=0; c=0; d=0
for y in os.listdir(directory):
if y.endswith('.png'):
b+=1
#beneath will err if there is no .json associated with the image
#i.e. images without labels
try:
#b+=1
image_png = Image.open(directory+y)
#get the filename without suffix
v=directory+y[0:len(y)-4]
#correct the imagefilename in the json file
linebyline=[]
with open(v+'.json', 'r') as j:
#path={'imagePath':y+".jpg"}
js=json.load(j)
#js['image_id']=y[0:len(y)-4]+'.jpg'
linebyline.append(js)
#js['imagePath']=y[0:len(y)-4]+'.jpg'
for line in linebyline:
#print(line['imagePath'])
line['imagePath']=y[0:len(y)-4]+'.jpg'
line['image_id']=y[0:len(y)-4]+'.jpg'
with open(v+'.json', 'w') as j:
json.dump(linebyline[0],j)
#save a .jpg version
image_png.save(v+'.jpg')
#delete the .png file
os.remove(directory+y)
d+=1
except:
c+=1
shutil.move(directory+y,error_directory+y)
print(f'Convertionerror with image{y}')
print(f'{b} png-files found')
print(f'{c} png-files had err')
print(f'{d} png-files was converted')
return
#build dictionary for images
def json_collection(img_dir):
global all_img
files=os.scandir(img_dir)
#with os.scandir(img_dir) as dirs:
#print(dirs)
for entry in files:
split=os.path.splitext(entry)
if split[1]=='.json':
#print(entry)
one_img={}
#filetype=split[1]
with open(entry.path) as json_file:
one_img=json.load(json_file)
#print(one_img)
en=entry.name
all_img[en]=one_img
json_file.close()
else:
continue
return
#Function to compile all labels in dataframe for analytical purposes
all_img_df=pd.DataFrame(columns=['Image', 'Label', 'Points'])
def labelsdataframe():
global all_img_df
#Iterating all json listed in dictionary of images
for image in all_img:
img = all_img[image]['imagePath']
#Iterating all shapes/labels for each image
for shape in all_img[image]['shapes']:
i={}
i['Image']=img
i['Label']= shape['label']
i['Points']= [shape['points']]
df_temp=pd.DataFrame(i)
all_img_df=pd.concat([all_img_df,df_temp],ignore_index=True)
return
def statistics():
all_img_df['Country']=all_img_df['Image'].str.split('_',expand=True)[0]
labels=all_img_df.groupby(['Country','Label'])['Image'].count()
print(labels)
return
def filesplit(path):
with os.scandir(path) as dirs: #skanning the folder for images
for entry in dirs: #iterating through the list of files
if entry.is_file(): #avoiding manipulation of folders
try:
b=os.path.basename(entry)
print(f'B is: {b}')
split=os.path.splitext(b)
print(f'Split is: {split}')
if split[1]=='.jpg':
print(f'Entry is: {entry}')
#establish segments
pools = ['train','valid','test']
for p in pools:
os.makedirs(path+r'/'+p,exist_ok=True)
#setting weights for distribution of files
distribution = [80,20,0]
#assign a pool to the specific file
pool = random.choices(pools, weights = distribution,k=1)
#separate according to labels
oldpath=path+split[0]+'.jpg'
newpath=path+r'/'+pool[0]+r'/'+split[0]+'.jpg'
shutil.move(oldpath,newpath)
oldpath=path+split[0]+'.json'
newpath=path+r'/'+pool[0]+r'/'+split[0]+'.json'
shutil.move(oldpath,newpath)
else:
print('Else')
continue
except:
continue
return
#folder that contains full imageset
allimagefolder='/Users/Data/Blue_ocean/Dataset/Labelled_images 5/'
#folder to caontain images that err (due to laking notations)
errfolder=allimagefolder+'Err/'
rename(allimagefolder)
convert_png(allimagefolder,errfolder)
json_collection(allimagefolder)
labelsdataframe()
filesplit(allimagefolder)
print(statistics())