File size: 1,199 Bytes
ac29556
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import numpy as np
from PIL import Image

MEAN, STD = 0.1307, 0.3081


def center_of_mass(img):
    """MNIST-style preprocessing: bbox crop -> resize to 20x20 ->
    center of mass placed at center of 28x28."""
    ys, xs = np.where(img > 0.05)
    if len(xs) == 0:
        return np.zeros((28, 28), dtype=np.float32)
    crop = img[ys.min():ys.max() + 1, xs.min():xs.max() + 1]

    small = np.array(
        Image.fromarray((crop * 255).astype(np.uint8)).resize((20, 20), Image.BILINEAR),
        dtype=np.float32) / 255.0

    yy, xx = np.mgrid[0:20, 0:20]
    total = small.sum()
    if total <= 0:
        return np.zeros((28, 28), dtype=np.float32)
    com_y = float((small * yy).sum() / total)
    com_x = float((small * xx).sum() / total)

    out = np.zeros((28, 28), dtype=np.float32)
    top = int(round(14 - com_y))
    left = int(round(14 - com_x))
    top = min(max(top, 0), 8)
    left = min(max(left, 0), 8)
    out[top:top + 20, left:left + 20] = small
    return out


def preprocess(img):
    """img: HxW float array in [0,1], ink = bright on dark.
    Returns normalized 28x28 tensor-ready array."""
    arr = center_of_mass(img.astype(np.float32))
    return (arr - MEAN) / STD