Skip to content

Commit 21f8541

Browse files
committed
adding competitor code
1 parent e8703f5 commit 21f8541

File tree

209 files changed

+110393
-0
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

209 files changed

+110393
-0
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
.DS_Store

MaksimovKA_solution/.dockerignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
./Dockerfile

MaksimovKA_solution/Dockerfile

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# use with GPU and nvidia-docker2
2+
FROM tensorflow/tensorflow:1.9.0-devel-gpu-py3
3+
RUN add-apt-repository -y ppa:ubuntugis/ppa; \
4+
apt-get update && apt-get -y install mc python-opencv tmux nano python3-tk gdal-bin python3-gdal less; \
5+
pip3 install --upgrade pip
6+
RUN pip3 install h5py scikit-image scipy pillow
7+
RUN pip3 install opencv-python matplotlib tqdm keras==2.1.6
8+
RUN pip3 install keras-resnet six scipy gdal
9+
RUN pip install albumentations
10+
RUN pip install keras-resnet scikit-learn pandas
11+
RUN pip install jupyter
12+
RUN pip install gdal rasterio
13+
RUN pip install shapely
14+
RUN mkdir /project
15+
COPY ./ /project/
16+
RUN chmod +x /project/train.sh
17+
RUN chmod +x /project/test.sh
18+
WORKDIR /project
19+
20+
ENV PYTHONPATH "${PYTHONPATH}:/project"
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
from albumentations import (
2+
Compose,
3+
HorizontalFlip,
4+
ShiftScaleRotate,
5+
OneOf,
6+
RandomContrast,
7+
RandomGamma,
8+
RandomBrightness
9+
10+
)
11+
12+
13+
def augmentations(prob=0.5):
14+
15+
transformer = Compose([
16+
17+
HorizontalFlip(p=prob),
18+
ShiftScaleRotate(p=prob, shift_limit=0.1, scale_limit=.1, rotate_limit=10),
19+
OneOf([RandomContrast(limit=0.1, p=prob),
20+
RandomGamma(gamma_limit=(90, 110), p=prob),
21+
RandomBrightness(limit=0.1, p=prob)],p=prob),
22+
23+
], p=prob)
24+
return transformer
25+
26+
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
import os
2+
import numpy as np
3+
from keras.preprocessing.image import Iterator
4+
import skimage.io
5+
6+
7+
class BaseMaskDatasetIterator(Iterator):
8+
def __init__(self,
9+
images_dir,
10+
masks_dir,
11+
image_ids,
12+
crop_shape,
13+
preprocessing_function,
14+
random_transformer=None,
15+
batch_size=8,
16+
shuffle=True,
17+
image_name_template=None,
18+
mask_name_template=None,
19+
add_contours=True
20+
):
21+
self.images_dir = images_dir
22+
self.masks_dir = masks_dir
23+
self.image_ids = image_ids
24+
self.image_name_template = image_name_template
25+
self.mask_name_template = mask_name_template
26+
self.random_transformer = random_transformer
27+
self.crop_shape = crop_shape
28+
self.preprocessing_function = preprocessing_function
29+
self.add_contours = add_contours
30+
super(BaseMaskDatasetIterator, self).__init__(len(self.image_ids), batch_size, shuffle, None)
31+
32+
def pad_mask_image(self, mask, image, img_id, crop_shape):
33+
# _mask = mask[:, :, 0]
34+
return NotImplementedError
35+
36+
def transform_batch_y(self, batch_y):
37+
return batch_y
38+
39+
def _get_batches_of_transformed_samples(self, index_array):
40+
batch_x = []
41+
batch_y = []
42+
43+
for batch_index, image_index in enumerate(index_array):
44+
_id = self.image_ids[image_index]
45+
# print(_id)
46+
img_name = self.image_name_template.format(id=_id)
47+
mask_name = self.mask_name_template.format(id=_id)
48+
49+
image = skimage.io.imread(os.path.join(self.images_dir, img_name), plugin='tifffile')
50+
mask = skimage.io.imread(os.path.join(self.masks_dir, mask_name), plugin='tifffile')
51+
if self.add_contours:
52+
tmp = np.zeros(mask.shape[:2], dtype=mask.dtype)
53+
mask = np.dstack([mask, tmp])
54+
else:
55+
mask = np.dstack([mask]*3)
56+
57+
crop_mask, crop_image = self.pad_mask_image(mask, image, _id, self.crop_shape)
58+
if self.random_transformer is not None:
59+
data = self.random_transformer(image=crop_image, mask=crop_mask)
60+
crop_image, crop_mask = data['image'], data['mask']
61+
62+
if self.add_contours:
63+
crop_mask = crop_mask / 255.
64+
crop_mask = crop_mask[:, :, :2]
65+
else:
66+
crop_mask = crop_mask / 255.
67+
crop_mask = crop_mask[:, :, 0]
68+
crop_mask = np.expand_dims(crop_mask, -1)
69+
70+
batch_x.append(crop_image)
71+
batch_y.append(crop_mask)
72+
73+
batch_x = np.array(batch_x, dtype="float32")
74+
batch_y = np.array(batch_y, dtype="float32")
75+
if self.preprocessing_function:
76+
batch_x = self.preprocess_input(batch_x)
77+
78+
return self.transform_batch_x(batch_x), self.transform_batch_y(batch_y)
79+
80+
@staticmethod
81+
def preprocess_input(batch_x):
82+
means = [963.0, 805.0, 666.0]
83+
stds = [473.0, 403.0, 395.0]
84+
for i in range(batch_x.shape[3]):
85+
batch_x[:, :, :, i] = (batch_x[:, :, :, i] - means[i]) / stds[i]
86+
return batch_x
87+
88+
def transform_batch_x(self, batch_x):
89+
return batch_x
90+
91+
def next(self):
92+
93+
with self.lock:
94+
index_array = next(self.index_generator)
95+
return self._get_batches_of_transformed_samples(index_array)
96+
97+
Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
import numpy as np
2+
import pandas as pd
3+
from .base_dataset import BaseMaskDatasetIterator
4+
from albumentations import RandomCrop, Compose, PadIfNeeded
5+
6+
class SpacenetBinaryDataset:
7+
def __init__(self,
8+
images_dir,
9+
masks_dir,
10+
folds_file,
11+
fold=0,
12+
fold_num=5,
13+
add_contours=False
14+
):
15+
super().__init__()
16+
self.fold = fold
17+
self.folds_file = folds_file
18+
self.fold_num = fold_num
19+
self.images_dir = images_dir
20+
self.masks_dir = masks_dir
21+
self.add_contours = add_contours
22+
self.train_ids, self.val_ids = self.generate_ids()
23+
print("Found {} train images".format(len(self.train_ids)))
24+
print("Found {} val images".format(len(self.val_ids)))
25+
26+
def get_generator(self, image_ids, crop_shape, preprocessing_function=1,
27+
random_transformer=None, batch_size=16, shuffle=True):
28+
return SpacenetDatasetIterator(
29+
self.images_dir,
30+
self.masks_dir,
31+
image_ids,
32+
crop_shape,
33+
preprocessing_function,
34+
random_transformer,
35+
batch_size,
36+
shuffle=shuffle,
37+
image_name_template="{id}.tif",
38+
mask_name_template="{id}.tif",
39+
add_contours=self.add_contours
40+
)
41+
42+
def train_generator(self, crop_shape, preprocessing_function=1, random_transformer=None, batch_size=16):
43+
return self.get_generator(self.train_ids, crop_shape, preprocessing_function,
44+
random_transformer, batch_size, True)
45+
46+
def val_generator(self, preprocessing_function=1, batch_size=1):
47+
return self.get_generator(self.val_ids, (928, 928), preprocessing_function, None, batch_size, False)
48+
49+
def generate_ids(self):
50+
51+
df = pd.read_csv(self.folds_file)
52+
53+
df['angle'] = df['img_id'].apply(lambda x: int(x.split('_')[1][5:]))
54+
# df = df[(df['angle'] > 25) & (df['angle'] <= 40)]
55+
# df = df[df['angle'] > 40]
56+
val_ids = df[(df['fold_on_train'] == self.fold)]['img_id'].values
57+
train_ids = np.sort(df[(df['fold_on_predict'] != self.fold)]['img_id'].values)
58+
return train_ids, val_ids
59+
60+
61+
class SpacenetDatasetIterator(BaseMaskDatasetIterator):
62+
63+
def __init__(self,
64+
images_dir,
65+
masks_dir,
66+
image_ids,
67+
crop_shape,
68+
preprocessing_function,
69+
random_transformer=None,
70+
batch_size=8,
71+
shuffle=True,
72+
image_name_template=None,
73+
mask_name_template=None,
74+
add_contours=False):
75+
super().__init__(images_dir,
76+
masks_dir,
77+
image_ids,
78+
crop_shape,
79+
preprocessing_function,
80+
random_transformer,
81+
batch_size,
82+
shuffle,
83+
image_name_template,
84+
mask_name_template,
85+
add_contours)
86+
87+
def pad_mask_image(self, mask, image, img_id, crop_shape):
88+
composed = Compose([PadIfNeeded(crop_shape[0], crop_shape[1], p=1),
89+
RandomCrop(crop_shape[0], crop_shape[1], p=1)], p=1)
90+
91+
if np.sum(mask) != 0:
92+
93+
s = 0
94+
tries = 0
95+
while s == 0:
96+
# crop = composed(crop_shape[0], crop_shape[1])
97+
croped = composed(image=image, mask=mask)
98+
99+
image_padded = croped['image']
100+
mask_padded = croped['mask']
101+
# print(mask_padded.shape)
102+
s = np.sum(mask_padded)
103+
tries += 1
104+
if tries > 5:
105+
break
106+
else:
107+
108+
croped = composed(image=image, mask=mask)
109+
image_padded = croped['image']
110+
mask_padded = croped['mask']
111+
112+
return mask_padded, image_padded

0 commit comments

Comments
 (0)