Skip to main content

Why I love Python

I was reading "The remarkable inefficiency of word recognition" (Pelli et al. 2003) and I wanted to generate some of the stimuli they were using. In Python it took me a few hours total, starting cold using the Python Imaging Library. The code is below....
"""This contains routines to generate degraded letter stimuli"""

import Image #The PIL
import ImageDraw
import ImageFont

import numpy

def generate_letter(contrast_energy = .01, #michelson contrast energy
noise = 30.,
bg_luminance = 128.,
letter = "a",
letter_size = 400):
N = 300 #size of image in pixels

#first figure out what is the ink-area of the letter

font = ImageFont.truetype("Data/arial.ttf", letter_size)
#we copy the .ttf file to the local directory to avoid problems

im_temp = Image.new("1", (1,1), 0)
draw = ImageDraw.Draw(im_temp)
#now we can draw on this

sz = draw.textsize(letter, font=font)
#this tells us the size of the letter

im_temp = Image.new("1", sz, 0)
#this is a temporary binary image created solely for the purpose of computing
#the ink-area of the letter
draw = ImageDraw.Draw(im_temp)
#now we can draw on this
draw.text((0,0), letter, font=font, fill=1)
pix = im_temp.load()
#pix is now an addressable array of pixel values
area_in_pixels = 0.
for row in xrange(sz[0]):
for col in xrange(sz[1]):
area_in_pixels += pix[row,col]

#since contrast_energy = contrast^2 * pixel_area
contrast = (contrast_energy/area_in_pixels)**0.5
fg_luminance = bg_luminance*(1+contrast)/(1-contrast)
print area_in_pixels
print contrast
print fg_luminance


im = Image.new("L", (N,N), bg_luminance)
#im is now a NxN luminance image with luminance set to bg_luminance

draw = ImageDraw.Draw(im)
#now we can draw on this

draw.text(((N-sz[0])/2, (N-sz[1])/2), letter, font=font, fill=fg_luminance)
#this centers the letter

if noise > 0:
pix = im.load()
#pix is now an addressable array of pixel values

rd = numpy.random.normal(scale=noise, size=(N,N))
for row in xrange(N):
for col in xrange(N):
pix[row,col] += rd[row,col]

im.show()

Comments

Popular posts from this blog

A note on Python's __exit__() and errors

Python's context managers are a very neat way of handling code that needs a teardown once you are done. Python objects have do have a destructor method ( __del__ ) called right before the last instance of the object is about to be destroyed. You can do a teardown there. However there is a lot of fine print to the __del__ method. A cleaner way of doing tear-downs is through Python's context manager , manifested as the with keyword. class CrushMe: def __init__(self): self.f = open('test.txt', 'w') def foo(self, a, b): self.f.write(str(a - b)) def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.f.close() return True with CrushMe() as c: c.foo(2, 3) One thing that is important, and that got me just now, is error handling. I made the mistake of ignoring all those 'junk' arguments ( exc_type, exc_val, exc_tb ). I just skimmed the docs and what popped out is that you need to return True or...

Store numpy arrays in sqlite

Use numpy.getbuffer (or sqlite3.Binary ) in combination with numpy.frombuffer to lug numpy data in and out of the sqlite3 database: import sqlite3, numpy r1d = numpy.random.randn(10) con = sqlite3.connect(':memory:') con.execute("CREATE TABLE eye(id INTEGER PRIMARY KEY, desc TEXT, data BLOB)") con.execute("INSERT INTO eye(desc,data) VALUES(?,?)", ("1d", sqlite3.Binary(r1d))) con.execute("INSERT INTO eye(desc,data) VALUES(?,?)", ("1d", numpy.getbuffer(r1d))) res = con.execute("SELECT * FROM eye").fetchall() con.close() #res -> #[(1, u'1d', <read-write buffer ptr 0x10371b220, size 80 at 0x10371b1e0>), # (2, u'1d', <read-write buffer ptr 0x10371b190, size 80 at 0x10371b150>)] print r1d - numpy.frombuffer(res[0][2]) #->[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] print r1d - numpy.frombuffer(res[1][2]) #->[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] Note that for work where data ty...