Skip to content

Instantly share code, notes, and snippets.

@trigeorgis
Forked from alexmic/pixel_count.py
Last active January 2, 2016 19:29
Show Gist options
  • Save trigeorgis/8351025 to your computer and use it in GitHub Desktop.
Save trigeorgis/8351025 to your computer and use it in GitHub Desktop.
from operator import itemgetter
from PIL import Image, ImageDraw, ImageFont
from matplotlib import font_manager
from multiprocessing import Pool
import numpy as np
import os.path
# Make a lowercase + uppercase alphabet.
alphabet = 'abcdefghijklmnopqrstuvwxyz'
alphabet += str.upper(alphabet)
size = (100, 100)
def draw_letter(letter, font):
img = Image.new('RGB', size, 'white')
draw = ImageDraw.Draw(img)
draw.text((0,0), letter, font=font, fill='#000000')
return img
def count_font_width(img):
letter_img = np.array(img.getdata()).reshape(size[0], size[1], 3).mean(axis=2)
black_pixels_in_one_dimension = np.where(letter_img.min(axis=0) == 0)[0]
return black_pixels_in_one_dimension[-1] - black_pixels_in_one_dimension[0]
def get_counts_for_font(font_path):
try:
name = os.path.basename(font_path)
font_img = ImageFont.truetype(font_path, size[0])
counts = [
count_font_width(draw_letter(letter, font_img))
for letter in alphabet
]
except:
return None
return counts
if __name__ == '__main__':
p = Pool(processes=8)
fonts = font_manager.OSXInstalledFonts()
all_counts = np.array(filter(None, p.map(get_counts_for_font, fonts)))
mean_count = all_counts.mean(axis=0)
std_count = all_counts.std(axis=0)
results = sorted(
zip(alphabet, mean_count, std_count),
key=itemgetter(1),
reverse=True
)
for res in results:
print '%s: %.2f +/- %.2f' % res
W: 80.27 +/- 17.01
M: 73.69 +/- 16.38
m: 67.25 +/- 13.86
w: 64.17 +/- 13.67
N: 62.43 +/- 14.01
H: 62.11 +/- 14.86
Q: 61.55 +/- 12.73
X: 60.28 +/- 11.60
K: 59.78 +/- 12.86
V: 59.62 +/- 11.31
A: 59.53 +/- 11.11
U: 59.28 +/- 12.45
D: 58.58 +/- 12.13
O: 58.53 +/- 11.16
G: 58.32 +/- 11.72
Y: 57.40 +/- 11.41
R: 55.60 +/- 11.29
T: 54.65 +/- 11.41
C: 54.42 +/- 10.42
Z: 53.47 +/- 10.91
B: 51.44 +/- 10.42
E: 50.95 +/- 11.57
P: 50.17 +/- 10.59
F: 49.09 +/- 11.91
L: 47.19 +/- 11.31
d: 47.00 +/- 10.28
y: 45.63 +/- 9.83
S: 45.48 +/- 11.01
k: 45.38 +/- 10.27
h: 45.34 +/- 10.30
n: 45.33 +/- 10.41
x: 45.26 +/- 9.40
p: 45.12 +/- 9.24
g: 45.05 +/- 9.71
v: 45.00 +/- 10.30
u: 44.97 +/- 10.08
q: 44.58 +/- 10.55
b: 44.07 +/- 9.47
o: 42.57 +/- 10.38
a: 42.24 +/- 10.21
J: 40.32 +/- 12.88
z: 40.20 +/- 9.56
e: 39.32 +/- 10.29
c: 38.44 +/- 10.58
f: 36.73 +/- 10.47
s: 35.24 +/- 10.79
r: 34.80 +/- 11.71
t: 31.13 +/- 11.41
I: 28.05 +/- 15.45
l: 23.10 +/- 13.41
j: 22.32 +/- 11.80
i: 21.78 +/- 12.89
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment