-
Notifications
You must be signed in to change notification settings - Fork 101
/
Copy pathcustom_data_aug.py
62 lines (47 loc) · 2.41 KB
/
custom_data_aug.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
'''
Capsules for Object Segmentation (SegCaps)
Original Paper by Rodney LaLonde and Ulas Bagci (https://arxiv.org/abs/1804.04241)
Code written by: Rodney LaLonde
If you use significant portions of this code or the ideas from our paper, please cite it :)
If you have any questions, please email me at [email protected].
This file contains the custom data augmentation functions.
'''
import numpy as np
import cv2
from scipy.ndimage.interpolation import map_coordinates
# Function to distort image
def elastic_transform(image, alpha=2000, sigma=40, alpha_affine=40, random_state=None):
if random_state is None:
random_state = np.random.RandomState(None)
shape = image.shape
shape_size = shape[:2]
# Random affine
center_square = np.float32(shape_size) // 2
square_size = min(shape_size) // 3
pts1 = np.float32([center_square + square_size, [center_square[0]+square_size, center_square[1]-square_size], center_square - square_size])
pts2 = pts1 + random_state.uniform(-alpha_affine, alpha_affine, size=pts1.shape).astype(np.float32)
M = cv2.getAffineTransform(pts1, pts2)
for i in range(shape[2]):
image[:,:,i] = cv2.warpAffine(image[:,:,i], M, shape_size[::-1], borderMode=cv2.BORDER_REFLECT_101)
image = image.reshape(shape)
blur_size = int(4*sigma) | 1
dx = cv2.GaussianBlur((random_state.rand(*shape_size) * 2 - 1), ksize=(blur_size, blur_size), sigmaX=sigma) * alpha
dy = cv2.GaussianBlur((random_state.rand(*shape_size) * 2 - 1), ksize=(blur_size, blur_size), sigmaX=sigma) * alpha
x, y = np.meshgrid(np.arange(shape[1]), np.arange(shape[0]))
indices = np.reshape(y+dy, (-1, 1)), np.reshape(x+dx, (-1, 1))
def_img = np.zeros_like(image)
for i in range(shape[2]):
def_img[:,:,i] = map_coordinates(image[:,:,i], indices, order=1).reshape(shape_size)
return def_img
def salt_pepper_noise(image, salt=0.2, amount=0.004):
row, col, chan = image.shape
num_salt = np.ceil(amount * row * salt)
num_pepper = np.ceil(amount * row * (1.0 - salt))
for n in range(chan//2): # //2 so we don't augment the mask
# Add Salt noise
coords = [np.random.randint(0, i - 1, int(num_salt)) for i in image.shape[0:2]]
image[coords[0], coords[1], n] = 1
# Add Pepper noise
coords = [np.random.randint(0, i - 1, int(num_pepper)) for i in image.shape[0:2]]
image[coords[0], coords[1], n] = 0
return image