-
Notifications
You must be signed in to change notification settings - Fork 0
/
DataAugmentation.py
73 lines (63 loc) · 2.1 KB
/
DataAugmentation.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 2 22:50:17 2019
@author: deepakchoudhary
"""
from PIL import Image, ImageEnhance, ImageFilter
import random
import numpy as np
class DataAugmentation:
def __call__(self, image):
image = self.gaussian_noise(image)
image = self.contrast(image)
image = self.brightness(image)
image = self.blur(image)
#image = self.rotate(image)
return image
def checkProb(self):
prob = random.random()
if prob > 0.7:
return True
else:
return False
def gaussian_noise(self, image):
if self.checkProb() == False:
return image
mean = 0
var = 5
std_dev = var**0.5
image = np.asarray(image)
gauss = np.random.normal(mean, std_dev, image.shape)
noisy = image + gauss
noisy = np.clip(noisy, 0, 255).astype("uint8")
noisy = Image.fromarray(noisy)
return noisy
#difference in luminance or colour that makes object distinguishable
def contrast(self, image):
if self.checkProb() == False:
return image
scale = np.random.rand()*1.5 + 0.5
return ImageEnhance.Contrast(image).enhance(scale)
def brightness(self, image):
if self.checkProb() == False:
return image
scale = np.random.rand()*1.5 + 0.5
return ImageEnhance.Brightness(image).enhance(scale)
def blur(self, image):
if self.checkProb() == False:
return image
return image.filter(ImageFilter.BLUR)
def rotate(self, image):
if self.checkProb() == False:
return image
rotateDegrees = [0, 180]
return image.rotate(np.random.choice(rotateDegrees))
"""
if __name__ == "__main__":
obj = DataAugmentation()
imagePath = "/Users/deepakchoudhary/Desktop/Work/Kaggle/jbm-crack/YE358311_Fender_apron/YE358311_defects/IMG20180905143750.jpg"
img = Image.open(imagePath)
a = obj.rotate(img)
a.show()
"""