forked from finger-monkey/Data-Augmentation
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrans_gray.py
More file actions
50 lines (35 loc) · 1.52 KB
/
trans_gray.py
File metadata and controls
50 lines (35 loc) · 1.52 KB
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
# encoding: utf-8
import math
from PIL import Image
import random
import numpy as np
import random
# This is the code of Local Grayscale Transfomation
class LGT(object):
def __init__(self, probability=0.2, sl=0.02, sh=0.4, r1=0.3):
self.probability = probability
self.sl = sl
self.sh = sh
self.r1 = r1
def __call__(self, img):
new = img.convert("L") # Convert from here to the corresponding grayscale image
np_img = np.array(new, dtype=np.uint8)
img_gray = np.dstack([np_img, np_img, np_img])
if random.uniform(0, 1) >= self.probability:
return img
for attempt in range(100):
area = img.size[0] * img.size[1]
target_area = random.uniform(self.sl, self.sh) * area
aspect_ratio = random.uniform(self.r1, 1 / self.r1)
h = int(round(math.sqrt(target_area * aspect_ratio)))
w = int(round(math.sqrt(target_area / aspect_ratio)))
if w < img.size[1] and h < img.size[0]:
x1 = random.randint(0, img.size[0] - h)
y1 = random.randint(0, img.size[1] - w)
img = np.asarray(img).astype('float')
img[y1:y1 + h, x1:x1 + w, 0] = img_gray[y1:y1 + h, x1:x1 + w, 0]
img[y1:y1 + h, x1:x1 + w, 1] = img_gray[y1:y1 + h, x1:x1 + w, 1]
img[y1:y1 + h, x1:x1 + w, 2] = img_gray[y1:y1 + h, x1:x1 + w, 2]
img = Image.fromarray(img.astype('uint8'))
return img
return img