Saturday, January 30, 2010

Checkerboard in Numpy

Here's a question on SO about how to make a checkerboard in Numpy (like you see on pdfs when as "the classic representation for "no pixels", or transparent." I have no doubt that I had the correct answer, but I could not buy a vote. Even from a guy with 22.9 K rep. Sheesh.

We use hstack and vstack to stack "unit" squares of solid color:

>>> import numpy as np
>>> u = 15
>>> b = np.zeros(u**2)
>>> b.shape = (u,u)
>>> w = b + 0x99
>>>
>>> width = 20 # squares across of a single type
>>> row1 = np.hstack([w,b]*width)
>>> row2 = np.hstack([b,w]*width)
>>> board = np.vstack([row1,row2]*width)
>>> board.shape
(600, 600)


Now just slice it down to what's needed

>>> width_actual = 357
>>> height_actual = 239
>>> board = board[:height_actual,:width_actual]
>>> board.shape
(239, 357)