ibarrond
ibarrond

Reputation: 7591

Creating a numpy binary grid array

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))

Upvotes: 0

Views: 970

Answers (2)

ibarrond
ibarrond

Reputation: 7591

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)

Upvotes: 0

tstanisl
tstanisl

Reputation: 14127

  • 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]]

Upvotes: 3

Related Questions