-
Notifications
You must be signed in to change notification settings - Fork 0
/
convertImg.py
71 lines (49 loc) · 1.63 KB
/
convertImg.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
import PIL
from PIL import Image
import numpy as np
im = Image.open("train/cats/cat.115.jpg")
# im.show()
print (np.array(im).shape)
def norm_image(img):
"""
Normalize PIL image
Normalizes luminance to (mean,std)=(0,1), and applies a [1%, 99%] contrast stretch
"""
img_y, img_b, img_r = img.convert('YCbCr').split()
img_y_np = np.asarray(img_y).astype(float)
img_y_np /= 255
img_y_np -= img_y_np.mean()
img_y_np /= img_y_np.std()
scale = np.max([np.abs(np.percentile(img_y_np, 1.0)),
np.abs(np.percentile(img_y_np, 99.0))])
img_y_np = img_y_np / scale
img_y_np = np.clip(img_y_np, -1.0, 1.0)
img_y_np = (img_y_np + 1.0) / 2.0
img_y_np = (img_y_np * 255 + 0.5).astype(np.uint8)
img_y = Image.fromarray(img_y_np)
img_ybr = Image.merge('YCbCr', (img_y, img_b, img_r))
img_nrm = img_ybr.convert('RGB')
return img_nrm
def resize_image(img, size):
"""
Resize PIL image
Resizes image to be square with sidelength size. Pads with black if needed.
"""
# Resize
n_x, n_y = img.size
if n_y > n_x:
n_y_new = size
n_x_new = int(size * n_x / n_y + 0.5)
else:
n_x_new = size
n_y_new = int(size * n_y / n_x + 0.5)
img_res = img.resize((n_x_new, n_y_new), resample=PIL.Image.BICUBIC)
# Pad the borders to create a square image
img_pad = Image.new('RGB', (size, size), (128, 128, 128))
ulc = ((size - n_x_new) // 2, (size - n_y_new) // 2)
img_pad.paste(img_res, ulc)
return img_pad
red_img = resize_image(im, 128)
print (np.array(red_img).shape)
# red_img.show()
norm_image(red_img).show()