nocturne
nocturne

Reputation: 647

inverse reshaping giving different results

I need to resize and then reshape certain image. Then I want to apply the inverse reshaping which should give the original picture, but it is not working. Let us have this code:

images=[]
image = imread('1.png')
resized = np.resize(image, (320, 440))
images.append(resized)

arr=np.asarray(images)
newArray=arr.astype('float32')

plt.figure(figsize=[5, 5])
reshaped = np.reshape(newArray[0], (320,440))
plt.imshow(reshaped, cmap='gray')
plt.show()

Original picture 1.png:

enter image description here

Reshaped picture shown by plt.show(): enter image description here

Inverse reshaped image is not like the original, can someone tell me where is the problem? Thanks.

Upvotes: 0

Views: 485

Answers (1)

sturgemeister
sturgemeister

Reputation: 456

Edit:

After clarification, it looks like the confusion comes from np.resize, which is not an image processing operation, and is not used for rescaling an image while retaining content.

It looks as though image processing wrappers such as imresize have been removed from the scipy library, and while you can in principle use the scipy.interpolate package to reproduce the functionality of imresize, I recommend either using pillow, or scikit-image

with pillow:

import numpy as np
from PIL import Image
image = Image.open("my_image.jpg")
image = image.resize((224, 224))
image = np.asarray(image)  # convert to numpy

with sckit-image:

from skimage.transform import resize
image = imread("my_image.jpg")
image = resize(image, (224, 224))

original answer

np.reshape will first ravel the elements, then sort them into the new shape specified, losing a lot of spatial relationships, as you're seeing. Likely, what you actually want to do is np.transpose the image, swapping two axes:

images=[]
image = imread('1.png')
resized = np.resize(image, (320, 440))
images.append(resized)

arr=np.asarray(images)
newArray=arr.astype('float32')

plt.figure(figsize=[5, 5])
transposed = np.transpose(newArray[0])
plt.imshow(transposed, cmap='gray')
plt.show()

Upvotes: 1

Related Questions