i have inherited a legacy code, and due to updates in scipy, i have to replace scipy.misc.imresize
with PIL.Image.resize
now.
This Is the original code
# xn.shape = (519, 20)
xnr = scipy.misc.imresize(xn, (200, xn.shape[1]))
# xnr.shape = (200, 20) i think ?
SomeOtherArray[i, :] = xnr.flatten()
As recommended here, i should be calling np.array(Image.fromarray(arr).resize())
# xn.shape = (519, 20)
xnr = np.array(Image.fromarray(xn).resize((200, xn.shape[1])))
# xnr.shape = (20, 200) !!! Not (200, 20)
SomeOtherArray[i, :] = xnr.flatten()
Question 1: Is it correct that xnr = scipy.misc.imresize(xn, (200, xn.shape[1]))
gives shape of (200, 20)
Question 2: How do i make it such that after using the PIL, xnr is correct, as previously intended in the original code?
It's a bit confusing due to the order of dimensions differing between Numpy and PIL.
An image in PIL has a size (width, height)
However, a Numpy array representing an image has a shape (height, width)
.
The following snippet illustrate this:
import numpy as np
from numpy import random
from PIL import Image
import matplotlib.pyplot as plt
random.seed()
xn = random.randint(0, 255, (539,20), dtype=np.uint8)
im = Image.fromarray(xn)
print(im.size)
plt.imshow(im, cmap='gray', vmin=0, vmax=255)
plt.show()
So when calling Image.fromarray(xn)
, you get a picture 20 wide x 539 high.
Now Image.fromarray(xn).resize((200, xn.shape[1]))
is a picture 200 wide x 20 high obtained by shrinking the original 539 height to 20 and stretching the original 20 width to 200.
If you want to keep the original 20 width and shrink the 539 height to 200, you should do:
Image.fromarray(xn).resize((xn.shape[1], 200))
By contrast scipy.misc.imresize(xn, (200, 20))
returns an array with shape (200, 20)
as explained in the docs:
size : int, float or tuple
int - Percentage of current size.
float - Fraction of current size.
tuple - Size of the output image (height, width).