4

I try to rescale 2D images (greyscale). The image size is 256x256 and the desired output is 224x224. The pixel values range from 0 to 1300.

I tried 2 approaches to rescale them with Lanczos Interpolation:

First using PIL Image:

import numpy as np
from PIL import Image
import cv2

array = np.random.randint(0, 1300, size=(10, 256, 256))
array[0] = Image.fromarray(array[0]).resize(size=(224, 224), resample=Image.LANCZOS)

resulting in the error message: ValueError: image has wrong mode

And then CV2:

array[0] = cv2.resize(array[0], dsize=(224, 224), interpolation=cv2.INTER_LANCZOS4)

resulting in the error message: ValueError: could not broadcast input array from shape (224,224) into shape (256,256)

How to do it properly?

tamtam_
  • 99
  • 1
  • 9
  • Now it should be a minimal reproducible example :) – tamtam_ Feb 26 '20 at 16:43
  • Just a suspicion (it's been some time since I worked with ```opencv```). Constants in ```cv2``` are denoted slightly differently when you work with ```python``` Vs it's native ```c```. I would double check - whether this is really the name of the constant in ```python``` (I don't think it is) – Grzegorz Skibinski Feb 26 '20 at 18:51

2 Answers2

4

In the second case, you are resizing a 256x256 image to 224x224, then assigning it back into a slice of the original array. This slice still has size 256x256, so NumPy doesn't know how to do the data copy.

Instead, create a new output array of the right sizes:

array = np.random.randint(0, 1300, size=(10, 256, 256))
newarray = np.zeros((10, 224, 224))
newarray[0] = cv2.resize(array[0], dsize=(224, 224), interpolation=cv2.INTER_LANCZOS4)
Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
2

In the PIL part, you have a few issues.

Firstly, you need to check the dtype of things you create! You create an array of np.int64 when you use np.random() like that. As you know your data only maxes out at 1300, an unsigned 16-bit is preferable:

array = np.random.randint(0, 1300, size=(10, 256, 256), dtype=np.uint16)

Secondly, when you create a PIL Image from the Numpy array, you need to tell PIL the mode - greyscale or Lightness here:

array[0] = Image.fromarray(array[0], 'L')

Thirdly, you are trying to stuff the newly created PIL Image back into a Numpy array - don't do that:

newVariable = Image.fromarray(...).resize()
Mark Setchell
  • 191,897
  • 31
  • 273
  • 432