Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the numpy.resize and numpy.reshape function works internally in python ?

In the package numpy their are two function resize and reshape. How internally they work? What kind of interpolation does they use ?I looked into the code, but didnt get it. Can anyone help me out. Or how does an image get resized. What happens with its pixels ?

like image 409
Shopon Avatar asked Jan 05 '23 22:01

Shopon


1 Answers

Neither interpolates. And if you are wondering about interpolation and pixels of an image, they probably aren't the functions that you want. There some image packages (e.g in scipy) that manipulate the resolution of images.

Every numpy array has a shape attribute. reshape just changes that, without changing the data at all. The new shape has to reference the same total number of elements as the original shape.

 x = np.arange(12)
 x.reshape(3,4)    # 12 elements
 x.reshape(6,2)    # still 12
 x.reshape(6,4)    # error

np.resize is less commonly used, but is written in Python and available for study. You have to read its docs, and x.resize is different. Going larger it actually repeats values or pads with zeros.

examples of resize acting in 1d:

In [366]: x=np.arange(12)
In [367]: np.resize(x,6)
Out[367]: array([0, 1, 2, 3, 4, 5])
In [368]: np.resize(x,24)
Out[368]: 
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11,  0,  1,  2,  3,  4,
        5,  6,  7,  8,  9, 10, 11])
In [369]: x.resize(24)
In [370]: x
Out[370]: 
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11,  0,  0,  0,  0,  0,
        0,  0,  0,  0,  0,  0,  0])

A recent question about scipy.misc.imresize. It also references scipy.ndimage.zoom:

Broadcasting error when vectorizing misc.imresize()

like image 115
hpaulj Avatar answered Jan 13 '23 15:01

hpaulj