-
Notifications
You must be signed in to change notification settings - Fork 15
/
read_CFPD_data.py
249 lines (205 loc) · 8.46 KB
/
read_CFPD_data.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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
# Hide the warning messages about CPU/GPU
import TensorflowUtils as utils
import glob
from tensorflow.python.platform import gfile
from six.moves import cPickle as pickle
import random
import numpy as np
from tqdm import tqdm
import os
import h5py
import pandas as pd
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
# from FCN, which trained on PASCAL VOC 2011
image_mean = [104.00699, 116.66877, 122.67892]
# image_mean = [0.6073780437240768, 0.5761329233683282, 0.5329315454579794]; # from Calculation
def read_dataset(data_dir):
# sample record: {'image': f, 'annotation': annotation_file,
# 'filename': filename}
training_records = []
traindir = "D:/Datasets/CFPD/trainimages/"
print("## Training dir:", traindir)
for filename in glob.glob(traindir + '*.jpg'): # assuming jpg files
record = {'image': None, 'annotation': None, 'filename': None}
record['image'] = filename
record['filename'] = filename
record['annotation'] = filename.replace(
"jpg", "png")
record['label'] = filename.replace(
"jpg", "png")
training_records.append(record)
validation_records = []
validationdir = "D:/Datasets/CFPD/valimages/"
print("## Validation dir:", validationdir)
for filename in glob.glob(
validationdir + '*.jpg'): # assuming jpg files
record = {'image': None, 'annotation': None, 'filename': None}
record['image'] = filename
record['filename'] = filename
record['annotation'] = filename.replace(
"jpg", "png")
record['label'] = filename.replace(
"jpg", "png")
validation_records.append(record)
testing_records = []
testdir = "D:/Datasets/CFPD/testimages/"
print("## Testing dir:", testdir)
for filename in glob.glob(
testdir + '*.jpg'): # assuming jpg files
record = {'image': None, 'annotation': None, 'filename': None}
record['image'] = filename
record['filename'] = filename
record['annotation'] = filename.replace(
"jpg", "png")
record['label'] = filename.replace(
"jpg", "png")
testing_records.append(record)
return training_records, validation_records, testing_records
def read_dataset_from_mat_file(data_dir):
# sample record: {'image': f, 'annotation': annotation_file,
# 'filename': filename}
training_records = []
validation_records = []
testing_records = []
all_records = []
data_dir = "D:/Datasets/CFPD/"
image_dir = data_dir + "image/"
annotation_file_path = data_dir + "fashion_parsing_data.mat"
print("## Image dir:", image_dir)
image_list = os.listdir(image_dir)
# fashion_dataset = read_mat(annotation_file_path)
fashion_dataset = convert_mat_to_dict(annotation_file_path)
for i, each in enumerate(image_list):
filename = image_dir + each
record = {'image': None, 'annotation': None, 'filename': None,
'category_label': None, 'color_label': None, 'img_name': None}
record['image'] = filename
record['filename'] = filename
# record['category_label'] = fashion_dataset[i][0]
# record['color_label'] = fashion_dataset[i][1]
# record['img_name'] = fashion_dataset[i][2]
# record['annotation'] = fashion_dataset[i][3]
record['category_label'] = fashion_dataset[i]['category_label']
record['color_label'] = fashion_dataset[i]['color_label']
record['img_name'] = fashion_dataset[i]['img_name']
record['annotation'] = fashion_dataset[i]['segmentation']
all_records.append(record)
np.random.shuffle(all_records)
num_records = len(all_records)
training_records = all_records[0:int(num_records*0.78)]
validation_records = all_records[int(
num_records*0.78):int(num_records*0.8)]
testing_records = all_records[int(num_records*0.8):num_records]
return training_records, validation_records, testing_records
def read_mat(annotation_file_path):
fashion_dataset = []
with h5py.File(annotation_file_path, 'r') as file:
print(list(file.keys()))
# print(file)
# ['#refs#', 'all_category_name', 'all_colors_name', 'fashion_dataset']
fashion_data = file['fashion_dataset']
# ['category_label', 'color_label', 'img_name', 'segmentation']
for each in tqdm(fashion_data):
temp = [hdf5_to_list(file[each[0]]['category_label']), hdf5_to_list(file[each[0]]['color_label']),
hdf5_to_list(file[each[0]]['img_name']), hdf5_to_list(file[each[0]]['segmentation'])]
fashion_dataset.append(temp)
return fashion_dataset
def hdf5_to_list(data):
x = data[:]
# x = x.tolist()
return x
def convert_mat_to_dict(mat_file='fashion_parsing_data.mat'):
f = h5py.File(mat_file, 'r')
all_ctgs = get_all_ctgs(f)
iter_ = iter(f.get('#refs#').values())
df = pd.DataFrame()
for outfit in tqdm(iter_, total=len(f.get('#refs#'))):
try:
# img_name
ascii_codes = list(outfit.get('img_name').value[:, 0])
img_name = ''.join([chr(code) for code in ascii_codes])
print(img_name)
# super pix 2 category
spix2ctg = outfit.get('category_label').value[0]
# pd.Series(spix2ctg).value_counts().plot(kind='bar')
# print(spix2ctg.shape)
# plt.plot(spix2ctg)
# plt.show()
# super pix 2 color
spix2clr = outfit.get('color_label').value[0]
# print(spix2clr.shape)
# plt.plot(spix2clr)
# plt.show()
# super pix
spixseg = outfit.get('segmentation').value.T
# print(spixseg.shape)
# plt.imshow(spixseg)
# plt.plot(spixseg)
# plt.show()
# plt.savefig('image.png')
# super pix -> semantic segmentation
semseg = np.zeros(spixseg.shape)
for i, c in enumerate(spix2ctg):
semseg[spixseg == i] = c-1
# semseg -> bbox
items = []
for i, ctg in enumerate(all_ctgs):
region = np.argwhere(semseg == i)
if region.size != 0:
bbox = {
'ymin': int(region.min(0)[0]),
'xmin': int(region.min(0)[1]),
'ymax': int(region.max(0)[0]),
'xmax': int(region.max(0)[1]),
}
items.append({
'bbox': bbox,
'category': ctg,
})
df = df.append({
'img_name': img_name,
'category_label': category_label,
'color_label': color_label,
'segmentation': segmentation,
'items': items,
}, ignore_index=True)
except AttributeError:
pass
d = df.to_dict(orient='records')
return d
"""
create image filename list for training and validation data (input and annotation)
"""
def create_image_lists(image_dir):
if not gfile.Exists(image_dir):
print("Image directory '" + image_dir + "' not found.")
return None
directories = ['training', 'validation']
image_list = {}
for directory in directories:
file_list = []
image_list[directory] = []
file_glob = os.path.join(image_dir, "images", directory, '*.' + 'jpg')
file_list.extend(glob.glob(file_glob))
if not file_list:
print('No files found')
else:
for f in file_list:
filename = os.path.splitext(f.split("/")[-1])[0] # Linux
# filename = os.path.splitext(f.split("\\")[-1])[0] # windows
annotation_file = os.path.join(
image_dir, "annotations", directory, filename + '.png')
if os.path.exists(annotation_file):
record = {
'image': f,
'annotation': annotation_file,
'filename': filename}
image_list[directory].append(record)
else:
print(
"Annotation file not found for %s - Skipping: %s" %
(filename, annotation_file))
random.shuffle(image_list[directory])
no_of_images = len(image_list[directory])
print('No. of %s files: %d' % (directory, no_of_images))
return image_list