[英]Lanczos Interpolation in Python with 2D images
I try to rescale 2D images (greyscale).我尝试重新缩放 2D 图像(灰度)。 The image size is 256x256 and the desired output is 224x224.图像大小为 256x256,所需的输出为 224x224。 The pixel values range from 0 to 1300.像素值范围从 0 到 1300。
I tried 2 approaches to rescale them with Lanczos Interpolation:我尝试了两种方法来使用 Lanczos 插值重新调整它们:
First using PIL Image:首先使用 PIL 图像:
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
导致错误消息: ValueError: image has wrong mode
And then CV2:然后是 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)
导致错误消息: ValueError: could not broadcast input array from shape (224,224) into shape (256,256)
How to do it properly?如何正确操作?
In the second case, you are resizing a 256x256 image to 224x224, then assigning it back into a slice of the original array.在第二种情况下,您将 256x256 图像的大小调整为 224x224,然后将其分配回原始数组的切片。 This slice still has size 256x256, so NumPy doesn't know how to do the data copy.这个切片的大小仍然是 256x256,所以 NumPy 不知道如何进行数据复制。
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)
In the PIL part, you have a few issues.在 PIL 部分,您有一些问题。
Firstly, you need to check the dtype
of things you create!首先,您需要检查您创建的事物的dtype
! You create an array of np.int64
when you use np.random()
like that.当您像这样使用np.random()
时,您会创建一个np.int64
数组。 As you know your data only maxes out at 1300, an unsigned 16-bit is preferable:如您所知,您的数据最多只能达到 1300,因此最好使用无符号 16 位:
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:其次,当您从 Numpy 数组创建 PIL 图像时,您需要在此处告诉 PIL 模式 - 灰度或亮度:
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:第三,您试图将新创建的 PIL 图像塞回 Numpy 数组 - 不要这样做:
newVariable = Image.fromarray(...).resize()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.