|
| 1 | +import numpy as np |
| 2 | +import cv2 |
| 3 | +from scipy import ndimage |
| 4 | +import math |
| 5 | + |
| 6 | +def getBestShift(img): |
| 7 | + cy,cx = ndimage.measurements.center_of_mass(img) |
| 8 | + |
| 9 | + rows,cols = img.shape |
| 10 | + shiftx = np.round(cols/2.0-cx).astype(int) |
| 11 | + shifty = np.round(rows/2.0-cy).astype(int) |
| 12 | + |
| 13 | + return shiftx,shifty |
| 14 | + |
| 15 | +def shift(img,sx,sy): |
| 16 | + rows,cols = img.shape |
| 17 | + M = np.float32([[1,0,sx],[0,1,sy]]) |
| 18 | + shifted = cv2.warpAffine(img,M,(cols,rows)) |
| 19 | + return shifted |
| 20 | + |
| 21 | + |
| 22 | + |
| 23 | +def preprocess(img): |
| 24 | + img=255-np.array(img).reshape(28,28).astype(np.uint8) |
| 25 | + (thresh, gray) = cv2.threshold(img, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU) |
| 26 | + |
| 27 | + while np.sum(gray[0]) == 0: |
| 28 | + gray = gray[1:] |
| 29 | + |
| 30 | + while np.sum(gray[:,0]) == 0: |
| 31 | + gray = np.delete(gray,0,1) |
| 32 | + |
| 33 | + while np.sum(gray[-1]) == 0: |
| 34 | + gray = gray[:-1] |
| 35 | + |
| 36 | + while np.sum(gray[:,-1]) == 0: |
| 37 | + gray = np.delete(gray,-1,1) |
| 38 | + |
| 39 | + rows,cols = gray.shape |
| 40 | + |
| 41 | + if rows > cols: |
| 42 | + factor = 20.0/rows |
| 43 | + rows = 20 |
| 44 | + cols = int(round(cols*factor)) |
| 45 | + gray = cv2.resize(gray, (cols,rows)) |
| 46 | + else: |
| 47 | + factor = 20.0/cols |
| 48 | + cols = 20 |
| 49 | + rows = int(round(rows*factor)) |
| 50 | + gray = cv2.resize(gray, (cols, rows)) |
| 51 | + |
| 52 | + colsPadding = (int(math.ceil((28-cols)/2.0)),int(math.floor((28-cols)/2.0))) |
| 53 | + rowsPadding = (int(math.ceil((28-rows)/2.0)),int(math.floor((28-rows)/2.0))) |
| 54 | + gray = np.lib.pad(gray,(rowsPadding,colsPadding),'constant') |
| 55 | + |
| 56 | + shiftx,shifty = getBestShift(gray) |
| 57 | + shifted = shift(gray,shiftx,shifty) |
| 58 | + gray = shifted |
| 59 | + |
| 60 | + img = gray.reshape(1,28,28).astype(np.float32) |
| 61 | + |
| 62 | + img-= int(33.3952) |
| 63 | + img/= int(78.6662) |
| 64 | + return img |
0 commit comments