How to make a checkerboard in numpy?

I'm using numpy to initialize a pixel array to a gray checkerboard (the classic representation for "no pixels", or transparent). It seems like there ought to be a whizzy way to do it with numpy's amazing array assignment/slicing/dicing operations, but this is the best I've come up with:

w, h = 600, 800
sq = 15    # width of each checker-square
self.pix = numpy.zeros((w, h, 3), dtype=numpy.uint8)
# Make a checkerboard
row = [[(0x99,0x99,0x99),(0xAA,0xAA,0xAA)][(i//sq)%2] for i in range(w)]
self.pix[[i for i in range(h) if (i//sq)%2 == 0]] = row
row = [[(0xAA,0xAA,0xAA),(0x99,0x99,0x99)][(i//sq)%2] for i in range(w)]
self.pix[[i for i in range(h) if (i//sq)%2 == 1]] = row

It works, but I was hoping for something simpler.


def checkerboard(shape):
    return np.indices(shape).sum(axis=0) % 2

Most compact, probably the fastest, and also the only solution posted that generalizes to n-dimensions.


I'd use the Kronecker product kron:

np.kron([[1, 0] * 4, [0, 1] * 4] * 4, np.ones((10, 10)))

The checkerboard in this example has 2*4=8 fields of size 10x10 in each direction.