Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python function to expand image (NumPy array)

Say I have a greyscale image that is 3x3 and is represented by the numpy array below.

I want to increase the size and resolution of the image, similar to a resizing function in a normal picture editing software, but I don't want it to change any of the values of the pixels, just to expand them.

Is there a Python function that does the following conversion?

[0,0,0]
[0,1,0]
[0,0,0]

---->

[0,0,0,0,0,0]
[0,0,0,0,0,0]
[0,0,1,1,0,0]
[0,0,1,1,0,0]
[0,0,0,0,0,0]
[0,0,0,0,0,0]
like image 486
user0 Avatar asked Feb 05 '26 05:02

user0


1 Answers

You could use np.repeat along both axes of the 3x3 img array:

>>> img.repeat(2, axis=0).repeat(2, axis=1)
array([[0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0],
       [0, 0, 1, 1, 0, 0],
       [0, 0, 1, 1, 0, 0],
       [0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0]])

Another way is to calculate the Kronecker product of img and an array of the appropriate shape filled with ones:

>>> np.kron(img, np.ones((2,2)))
array([[ 0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  1.,  1.,  0.,  0.],
       [ 0.,  0.,  1.,  1.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.]])

Here's a link to the documentation for np.kron:

So in the example above, each value x in img is multiplied by a 2x2 array of ones to create a 2x2 array of x values. These new 2x2 arrays make up the returned array.

This multiplication might be slower than simply repeating, however.

like image 102
Alex Riley Avatar answered Feb 06 '26 17:02

Alex Riley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!