-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathconverter.py
47 lines (40 loc) · 1.94 KB
/
converter.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
import cv2
from PIL import Image, ImageFilter
def imageprepare(argv):
"""
This function returns the pixel values.
The imput is a png file location.
"""
im = Image.open(argv).convert('L')
width = float(im.size[0])
height = float(im.size[1])
newImage = Image.new('L', (28, 28), (255)) # creates white canvas of 28x28 pixels
if width > height: # check which dimension is bigger
# Width is bigger. Width becomes 20 pixels
kwidth = 20
nheight = int(round((float(kwidth) / width * height), 0)) # resize height according to ratio width
if (nheight == 0): # rare case but minimum is 1 pixel
nheight = 1
# resize and sharpen
img = im.resize((kwidth, nheight), Image.ANTIALIAS).filter(ImageFilter.SHARPEN)
wleft = int(round(((28 - kwidth) / 2), 0))
wtop = int(round(((28 - nheight) / 2), 0)) # calculate horizontal position
newImage.paste(img, (6, wtop)) # paste resized image on white canvas
else:
# Height is bigger. Heigth becomes 20 pixels.
kheight = 20
nwidth = int(round((float(kheight) / height * width), 0)) # resize width according to ratio height
if (nwidth == 0): # rare case but minimum is 1 pixel
nwidth = 1
# resize and sharpen
img = im.resize((nwidth, kheight), Image.ANTIALIAS).filter(ImageFilter.SHARPEN)
wtop = int(round(((28 - kheight) / 2), 0))
wleft = int(round(((28 - nwidth) / 2), 0)) # caculate vertical pozition
newImage.paste(img, (wleft, wtop)) # paste resized image on white canvas
# newImage.save("sample.png
tv = list(newImage.getdata()) # get pixel values
# normalize pixels to 0 and 1. 0 is pure white, 1 is pure black.
tva = [(255 - x) for x in tv]
return tva
#x=imageprepare('./pic94.png')#file path here
#print(len(x))# mnist IMAGES are 28x28=784 pixels