Python – Fill a numpy array with random values in a given range?

Fill a numpy array with random values in a given range?… here is a solution to the problem.

Fill a numpy array with random values in a given range?

I want to be able to add a border to an array (actually an image file) with a random set of values. The numpy.pad() function does not have any pattern to do this. Is there a shorthand way to achieve this, or do I have to create a function from scratch?

Solution

I think you need to create a fill function yourself to pass to np.pad.
This one is filled with random integers.

def random_pad(vec, pad_width, *_, **__):
    vec[:pad_width[0]] = np.random.randint(20, 30, size=pad_width[0])
    vec[vec.size-pad_width[1]:] = np.random.randint(30,40, size=pad_width[1])

You can use it with np.pad like this:

In [13]: img = np.arange(12).reshape(3, 4)

In [14]: img
Out[14]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

In [15]: np.pad(img, ((2,3), (1,4)), mode=random_pad)
Out[15]: 
array([[26, 21, 22, 24, 21, 37, 37, 37, 39],
       [26, 25, 23, 29, 20, 39, 38, 30, 31],
       [26,  0,  1,  2,  3, 37, 31, 32, 36],
       [29,  4,  5,  6,  7, 30, 32, 33, 37],
       [24,  8,  9, 10, 11, 33, 34, 33, 37],
       [26, 36, 36, 36, 30, 32, 36, 38, 31],
       [29, 33, 34, 38, 35, 31, 33, 37, 33],
       [23, 37, 33, 33, 34, 32, 37, 33, 35]])

Related Problems and Solutions