Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a checkerboard in numpy?

Tags:

python

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.

like image 902
Ned Batchelder Avatar asked Jan 30 '10 21:01

Ned Batchelder


People also ask

How do you make a 3 by 3 matrix in python?

You can use numpy. First, convert your list into numpy array. Then, take an element and reshape it to 3x3 matrix.

What is checkerboard pattern?

A checkerboard (American English) or chequerboard (British English; see spelling differences) is a board of checkered pattern on which checkers (also known as English draughts) is played.


1 Answers

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.

like image 112
Eelco Hoogendoorn Avatar answered Sep 19 '22 02:09

Eelco Hoogendoorn