cnn0 / space /src /preprocess.py
shyo2's picture
Devin
Add MNIST drawing demo: Flask web app and HF Space source
ac29556
Raw History Blame Contribute Delete
1.2 kB
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