Diff of /Segmentation/utils.py [000000] .. [e698c9]

Switch to unified view

a b/Segmentation/utils.py
1
import random
2
import cv2
3
import numpy as np
4
5
def gaussian_noise(img, mean=0, sigma=0.03):
6
    img = img.copy()
7
    noise = np.random.normal(mean, sigma, img.shape)
8
    mask_overflow_upper = img+noise >= 1.0
9
    mask_overflow_lower = img+noise < 0
10
    noise[mask_overflow_upper] = 1.0
11
    noise[mask_overflow_lower] = 0
12
    img += noise
13
    return img
14
15
def brightness(img, low, high):
16
    value = random.uniform(low, high)
17
    hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
18
    hsv = np.array(hsv, dtype = np.float64)
19
    hsv[:,:,1] = hsv[:,:,1]*value
20
    hsv[:,:,1][hsv[:,:,1]>255]  = 255
21
    hsv[:,:,2] = hsv[:,:,2]*value 
22
    hsv[:,:,2][hsv[:,:,2]>255]  = 255
23
    hsv = np.array(hsv, dtype = np.uint8)
24
    img = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)
25
    return img
26
27
def fill(img, h, w):
28
    img = img.astype('float32')
29
    img = cv2.resize(img, (h, w), cv2.INTER_CUBIC)
30
    return img
31
def zoom(img, mask, value):
32
    if value > 1 or value < 0:
33
        print('Value for zoom should be less than 1 and greater than 0')
34
        return img, mask
35
    value = random.uniform(value, 1)
36
    h, w = img.shape[:2]
37
    h_taken = int(value*h)
38
    w_taken = int(value*w)
39
    h_start = random.randint(0, h-h_taken)
40
    w_start = random.randint(0, w-w_taken)
41
    img = img[h_start:h_start+h_taken, w_start:w_start+w_taken, :]
42
    img = fill(img, h, w)
43
    mask = mask[h_start:h_start+h_taken, w_start:w_start+w_taken, :]
44
    mask = fill(mask, h, w)
45
    return img, mask
46
47
def vertical_shift(img, mask, ratio=0.0):
48
    if ratio > 1 or ratio < 0:
49
        print('Value should be less than 1 and greater than 0')
50
        return img, mask
51
    ratio = random.uniform(-ratio, ratio)
52
    h, w = img.shape[:2]
53
    to_shift = h*ratio
54
    if ratio > 0:
55
        img = img[:, :int(w-to_shift), :]
56
        mask = mask[:, :int(w-to_shift), :]
57
    if ratio < 0:
58
        img = img[:, int(-1*to_shift):, :]
59
        mask = mask[:, int(-1*to_shift):, :]
60
    img = fill(img, h, w)
61
    mask = fill(mask, h, w)
62
    return img, mask
63
64
def horizontal_shift(img, mask, ratio=0.0):
65
    if ratio > 1 or ratio < 0:
66
        print('Value should be less than 1 and greater than 0')
67
        return img, mask
68
    ratio = random.uniform(-ratio, ratio)
69
    h, w = img.shape[:2]
70
    to_shift = w*ratio
71
    if ratio > 0:
72
        img = img[:, :int(w-to_shift), :]
73
        mask = mask[:, :int(w-to_shift), :]
74
    if ratio < 0:
75
        img = img[:, int(-1*to_shift):, :]
76
        mask = mask[:, int(-1*to_shift):, :]
77
    img = fill(img, h, w)
78
    mask = fill(mask, h, w)
79
    return img,mask