'How to generate numpy arrays with random regions with rectangular shape with random size?

I would like to generate a binary array (values are 1s and 0s) filled with rectangular regions. Something like this:

a = np.array([0, 1, 1, 0, 0]
             [0, 1, 1, 0, 0]
             [0, 0, 0, 0, 0]
             [0, 1, 1, 1, 0]
             [0, 1, 1, 1, 0])

The idea is that the rectangles could be generated randomly, and even intersect, like here:

b = np.array([0, 1, 1, 0, 0]
             [0, 1, 1, 1, 0]
             [0, 1, 1, 1, 0]
             [0, 1, 1, 1, 0]
             [0, 1, 1, 1, 0])

How could one accomplish this?



Solution 1:[1]

Here's a function that places ones in a random location based on the shape you set:

def fill_array(base_array, shape_to_be_inserted):
    row_loc = np.random.randint(low=0, high=(base_array.shape[0]-shape_to_be_inserted.shape[0]+1))
    col_loc = np.random.randint(low=0, high=(base_array.shape[1]-shape_to_be_inserted.shape[1]+1))

    output_array = np.copy(base_array)
    for i in range(base_array.shape[0]):
        for k in range(base_array.shape[1]):
            if i >= row_loc and i < row_loc+shape_to_be_inserted.shape[0]:
                if k >= col_loc and k < col_loc+shape_to_be_inserted.shape[1]:
                    output_array[i, k] = 1
    return output_array

And here I put the function in a loop:

empty_area = np.zeros(shape=(8, 8))
some_shape = np.zeros(shape=(3, 3))

for i in range(20):
    empty_area = fill_array(empty_area, some_shape)

I have to be honest - I found this solution very unsatisfactory and I'd like to hear how others would solve this problem.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1