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]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With