我有一个图像数据的4D ndarray,其组织为[NumberOfImages,RowsOfImage,ColumnsOfImage,ChannelsOfImage]。
现在,我想将4D ndarray中的图像调整为新的大小,即[NumberOfImages,NewRowsOfImage,NewColumnsOfImage,ChannelsOfImage]的大小,而其他尺寸保持不变。
我知道TensorFlow中有一个函数tf.image.resize_images可以做到这一点。如果新图像大于原始图像,则将使用双线性插值法或最近邻插值法用新像素填充新图像。
但是,调整大小后,图像数据的ndarray被转换为TensorFlow的Tensor对象。然后,我必须将其转换回ndarray。这些过程将花费大量时间。
我已经尝试过skimage.transform.resize,但是此功能似乎可以调整2D图像数据的大小。如果使用此功能,则必须使用for循环,这也会花费大量时间。
那么Python中是否存在与TensorFlow的tf.image.resize_images函数相同的resize函数?如果没有,有人可以给我一些建议来解决我的问题吗?
非常感谢你。
最佳答案
使用numpy.resize
。请参见以下示例。所有图像都具有相同的形状(在这种情况下为768 x 1024 x 3)。在此示例中,我将行号与列号切换了。 im_all
是您的4d数组。
from scipy.misc import imread
import numpy as np
import matplotlib.pyplot as plt
f = r"C:\Users\Public\Pictures\Sample Pictures\Lighthouse.jpg"
im0 = imread(f)
f = r"C:\Users\Public\Pictures\Sample Pictures\koala.jpg"
im1 = imread(f)
f = r"C:\Users\Public\Pictures\Sample Pictures\tulips.jpg"
im2 = imread(f)
f = r"C:\Users\Public\Pictures\Sample Pictures\desert.jpg"
im3 = imread(f)
im_all = np.array([im0, im1, im2, im3])
im_all_b = np.resize(im_all, [im_all.shape[0], im_all.shape[2], im_all.shape[1], im_all.shape[3]])
plt.figure()
plt.imshow(im_all_b[1])
plt.figure()
plt.imshow(im_all[1])
plt.show()
这是一个插值示例(默认值为
bilinear
,请参见:http://docs.scipy.org/doc/scipy-0.16.1/reference/generated/scipy.misc.imresize.html),其中带有内存使用优化:from scipy.misc import imread, imresize
import numpy as np
import matplotlib.pyplot as plt
f = r"C:\Users\Public\Pictures\Sample Pictures\Lighthouse.jpg"
im0 = imread(f)
f = r"C:\Users\Public\Pictures\Sample Pictures\koala.jpg"
im1 = imread(f)
f = r"C:\Users\Public\Pictures\Sample Pictures\tulips.jpg"
im2 = imread(f)
f = r"C:\Users\Public\Pictures\Sample Pictures\desert.jpg"
im3 = imread(f)
im_all = np.array([im0, im1, im2, im3])
for i in range(im_all.shape[0]):
temp = im_all[0, :, :, :].copy()
im_all = np.delete(im_all, 0, 0)
temp = imresize(temp, (temp.shape[0]+200, temp.shape[1]+200, 3))
temp = np.expand_dims(temp, axis=0)
try:
im_all_b = np.vstack([im_all_b, temp])
except NameError:
im_all_b = temp
plt.figure()
plt.imshow(im_all_b[1])
plt.show()
在上面的示例中,我向x和y轴各添加了200个像素。