0

My objective is to create a square binary grid in a numpy 2D array (containing only 0 and 1 values) with a given length and given number of cells per row/column. E.g.: assigning 8 cells per axis would give us a chess board (with a given length):

chess_board

Translated into code, an example would look like this (using length=8 for simplicity):

res = np_binary_grid(length=8, cells_per_row=4)
array([[1, 1, 0, 0, 1, 1, 0, 0],
       [1, 1, 0, 0, 1, 1, 0, 0],
       [0, 0, 1, 1, 0, 0, 1, 1],
       [0, 0, 1, 1, 0, 0, 1, 1],
       [1, 1, 0, 0, 1, 1, 0, 0],
       [1, 1, 0, 0, 1, 1, 0, 0],
       [0, 0, 1, 1, 0, 0, 1, 1],
       [0, 0, 1, 1, 0, 0, 1, 1]])

So far I've been toying with np.meshgrid, np.dot and np.roll, but all my attempts were unsuccessful (no colour on some columns, just stripes, etc...)

Extra

To help visualize a given matrix M, I am using a small routine:

from PIL import Image
import numpy as np
display(Image.fromarray(M.astype(np.uint8)*255))

2 Answers 2

3
  • Try to create C-element-long vector of alternating 0/1.
  • use Kronecker product to expand those elements to desired size
  • Finally, use broadcasting and xoring to create an 2d chessboard

Code:

import numpy as np

def np_binary_grid(L, C):
    assert L % C == 0
    r = np.arange(C, dtype=np.uint8) & 1
    r = np.kron(r, np.ones(L // C, dtype=np.uint8))
    # `^ 1` fill force upper-left cell to consist of 1s
    return (r ^ 1) ^ r[:, None]

print(np_binary_grid(8, 4))

displays:

[[1 1 0 0 1 1 0 0]
 [1 1 0 0 1 1 0 0]
 [0 0 1 1 0 0 1 1]
 [0 0 1 1 0 0 1 1]
 [1 1 0 0 1 1 0 0]
 [1 1 0 0 1 1 0 0]
 [0 0 1 1 0 0 1 1]
 [0 0 1 1 0 0 1 1]]
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Right what I was looking for. I'll post my own answer too, but yours seems nicer.
0

I got my own version working:

def np_binary_grid(length, cells_per_row):
    '''Generates a binary grid in a numpy array.
    cells_per_row must be a power of 2'''
    aux = np.full(length, False)
    n=2
    aux[:length//n]=True
    while n<cells_per_row:
        n*=2
        aux = aux != np.roll(aux, length//n)
    
    a, b = np.meshgrid(aux, np.roll(aux, length//n))
    return (a != b).astype(np.bool)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.