-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimgprocess.py
More file actions
51 lines (48 loc) · 1.47 KB
/
imgprocess.py
File metadata and controls
51 lines (48 loc) · 1.47 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
50
51
from __future__ import print_function
from PIL import Image
from os.path import isfile
import numpy as np
import sys
class IMGProcess(object):
def __init__(self,fn,size):
self.fn = fn
if not isfile(fn):
print("File not exist",file=sys.stderr)
exit(1)
self.img = Image.open(fn)
self.size = size
def getVec(self):
# convert to grayscale
gs = self.img.convert('L')
# convert img to array
gs = np.array(gs)
# find char
pixels = []
sx, sy = self.img.size
for x in range(sx):
for y in range(sy):
if gs[y][x] != 255:
pixels.append([x,y])
pixels = np.array(pixels)
xmin, ymin = pixels.min(axis=0)
xmax, ymax = pixels.max(axis=0)
# crop
c = self.img.crop((xmin,ymin,xmax,ymax))
c.thumbnail(self.size,Image.ANTIALIAS)
# resize
r = Image.new("L",self.size,"white")
offset = (
int((self.size[0]-c.size[0])/2),
int((self.size[1]-c.size[1])/2)
)
r.paste(c,offset)
r = np.array(r.convert("L"))
# convert to vector
v = np.zeros((1,self.size[0]*self.size[1]))
for i in range(self.size[0]):
for j in range(self.size[1]):
if r[i][j] < 128:
v[0,self.size[0]*i+j] = 1
else:
v[0,self.size[0]*i+j] = 0
return v[0]