-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.py
206 lines (152 loc) · 5.65 KB
/
test.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
import glob
from PIL import Image
import os
import numpy as np
import random
import re
import json
import torch
from torch.utils.data import Dataset
import torchvision
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
def show_img(img, transpose=True):
# img = img / 2 + 0.5 # unnormalize
npimg = img.numpy()
if transpose:
npimg = npimg.transpose(1, 2, 0)
plt.imshow(npimg)
plt.show()
# #### The code from last post
POINTS = re.compile('POLYGON\s*\(\((.+)\)\)', re.I)
def polygon(building):
poly = building['wkt']
poly = POINTS.match(poly).group(1)
poly = [coord.split(' ') for coord in poly.split(', ')]
poly = [(float(x), float(y)) for x, y in poly]
return poly
# Code from this post
def clip(value, lower, upper):
return lower if value < lower else upper if value > upper else value
def bbox(poly, padding = 20):
xmin, ymin = poly[0] # top-left
xmax, ymax = poly[0] # bottom-right
for x, y in poly[1:]:
if x < xmin:
xmin = x
elif x > xmax:
xmax = x
if y < ymin:
ymin = y
elif y > ymax:
ymax = y
xmin -= padding
ymin -= padding
xmax += padding
ymax += padding
return [(xmin, ymin), (xmax, ymax)]
def norm_bbox(bbox, image_width, image_height = None):
if not image_height:
image_height = image_width
xmin, ymin = bbox[0] # top-left
xmax, ymax = bbox[1] # bottom-right
# Clip x-values
xmin = clip(xmin, 0, image_width)
xmax = clip(xmax, 0, image_width)
# Clip y-values
ymin = clip(ymin, 0, image_height)
ymax = clip(ymax, 0, image_height)
return [(xmin, ymin), (xmax, ymax)]
def draw_bbox(ax, bbox, damage_value):
x, y = bbox[0] # top-left corner
width = bbox[1][0] - x
height = bbox[1][1] - y
box = Rectangle((x, y), width, height, True, color=(1, 0, 0, 0.3),
linewidth=4)
ax.text(x, y, str(damage_value), size=8)
ax.add_patch(box)
class DamageNetDataset(Dataset):
"""xView2 dataset.
Parameters
----------
images_dir: str
Directory with all the images.
labels_dir: str
Directory with all the labels as JSON files.
transform: callable, optional
Optional transform to be applied on a sample. Transform receives
the current image **and** target! Default is `None`.
"""
def __init__(self, images_dir, labels_dir, transform=None):
self.images_list = sorted(glob.glob(images_dir + '/*_post_disaster.png'))
self.labels_list = sorted(glob.glob(labels_dir + '/*_post_disaster.json'))
self.transform = transform
def __len__(self):
return len(self.images_list)
def __getitem__(self, idx):
if torch.is_tensor(idx):
idx = idx.tolist()
print('idx', idx)
# Check to see if buildings is None
with open(self.labels_list[idx]) as f:
label = json.load(f)
buildings = label['features']['xy']
# Choose a random builing and get its damage_value
if buildings:
chosen_building = random.choice(buildings)
damage_value = chosen_building['properties']['subtype']
while not buildings or damage_value == 'un-classified':
idx = random.randint(0, self.__len__())
with open(self.labels_list[idx]) as f:
label = json.load(f)
buildings = label['features']['xy']
# Choose a random builing and get its damage_value
if buildings:
chosen_building = random.choice(buildings)
damage_value = chosen_building['properties']['subtype']
# Do get_data with working values
image, label = self.get_data(idx, chosen_building)
return image, label
def get_data(self, idx, chosen_building):
image = Image.open(self.images_list[idx])
coords = polygon(chosen_building)
box = bbox(coords)
box = norm_bbox(box, image.width, image.height)
cropped_bbox_image = image.crop((box[0][0], box[0][1], box[1][0], box[1][1]))
# plt.imshow(cropped_bbox_image)
# plt.show()
damage_value = chosen_building['properties']['subtype']
print(damage_value)
# Convert str in damage_value to a pytorch tensor
# label = torch.Tensor([0, 0, 0])
if damage_value == 'no-damage':
label = torch.Tensor([0, 0, 0])
elif damage_value == 'minor-damage':
label = torch.Tensor([1, 0, 0])
elif damage_value == 'major-damage':
label = torch.Tensor([1, 1, 0])
elif damage_value == 'destroyed':
label = torch.Tensor([1, 1, 1])
image = cropped_bbox_image
if self.transform:
image = self.transform(image)
return image, label
def main():
# Instantiate the new Dataset class to test it
dataset = DamageNetDataset(images_dir='train/images', labels_dir='train/labels',
transform=torchvision.transforms.Compose([
torchvision.transforms.Resize((75, 75)),
torchvision.transforms.ToTensor()]))
# The Dataloader
dataloader = torch.utils.data.DataLoader(
dataset, batch_size=64, shuffle=True, num_workers=0
)
for i in range(0, 100):
dataiter = iter(dataloader)
images, labels = next(dataiter)
print(images.shape)
print(labels)
# show_img(images[0])
# Weird windows multiprocessing sh*t
if __name__ == '__main__':
main()