Lanczos Interpolation in Python with 2D images

╄→гoц情女王★ 提交于 2020-12-13 05:39:12

问题


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?


回答1:


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)



回答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()


来源:https://stackoverflow.com/questions/60416856/lanczos-interpolation-in-python-with-2d-images

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!