Last active
August 29, 2015 14:02
-
-
Save rainbyte/d42afbd80818ded9ac2f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from PIL import Image | |
import numpy | |
import os | |
DIR = "images_good" | |
W, H = 16, 16 | |
MNIST_NORM = (20, 20) | |
MNIST_SIZE = (28, 28) | |
WHITE = (255, 255, 255) | |
def tokens_to_img(tokens): | |
np_arr = numpy.empty((W,H), numpy.uint8) | |
#np_arr.shape=H,W | |
for i in range(len(tokens) - 11): | |
row = i // W | |
col = i % H | |
np_arr[row, col] = (1-float(tokens[i])) * 255 | |
return Image.fromarray(np_arr) | |
def tokens_to_num(tokens): | |
le = len(tokens) | |
num = 0 | |
for i in range(le - 11, le): | |
if tokens[i] == '1': | |
return num | |
else: | |
num = num + 1 | |
def normalize_img(img): | |
img = img.resize(MNIST_NORM) | |
background = Image.new('RGB', MNIST_SIZE, WHITE) | |
bg_w, bg_h = background.size | |
img_w, img_h = img.size | |
offset = ((bg_w - img_h) / 2, (bg_h - img_h) / 2) | |
background.paste(img, offset) | |
return background | |
if not os.path.exists(DIR): | |
os.makedirs(DIR) | |
with open("semeion.data") as f: | |
idx = 0 | |
for line in f: | |
idx = idx + 1 | |
tokens = line.split(' ') | |
img = tokens_to_img(tokens) | |
img_normalized = normalize_img(img) | |
num = tokens_to_num(tokens) | |
filename = "{DIR}/image{idx}_{num}.png".format(DIR=DIR, idx=idx, num=num) | |
img_normalized.save(filename) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment