首页 > 解决方案 > 使用 Python 在保持比例的同时调整图像大小

问题描述

我有一个关于使用 python 预处理一些图像的问题。我发现的大多数答案都使用 Java,我需要使用 Python。

我有一个包含 2050 张图像的训练集,我想将它们的大小调整为 224 x 224,以便稍后将它们提供给卷积神经网络 (CNN)。最大的问题是我不能在不丢失图像比例的情况下做到这一点。并非所有图像的大小都相同。例如,我有 1000 x 700 像素和 700 x 600 像素的图像。

我的想法是使用周围像素的平均值用像素填充图像的较小一侧。但我真的不知道如何将它与我已经拥有的东西结合起来。我听说过 cv2 库,但我一直无法让它工作。

我的代码如下:

training_set = pd.DataFrame({'Images': training_imgs,'Labels': training_labels})

 
train_dataGen = ImageDataGenerator(rescale=1./255)

train_generator = train_dataGen .flow_from_dataframe(
      dataframe = training_set, directory="",
      x_col="Images", y_col="Labels", 
      class_mode="categorical", 
      target_size=(224,224), batch_size=32)

## Steps to plot the images
imgs, labels = next(train_generator)

for i in range(batch_size):   
    image = imgs[i]
    plt.imshow(image)
    plt.show()

标签: pythonimage-processing

解决方案


你快完成了。如果您使用 keras,则此处不需要 opencv。

image = imgs[i,:,:,:] # batch_size, height, width, channels
print(np.shape(image) # should be (224,224) in case your image is grayscale
plt.imshow(image)
plt.show()

这将显示您调整大小的图像并打印它的形状。如果要更改调整大小方法的插值方法,可以查看文档。默认情况下它是双线性的,我认为这就是您要寻找的。

编辑 0:如果您想为图像上的任何类型的预处理(调整大小等)创建自定义函数,您可以preprocessing_function在您的ImageDataGenerator方法中定义。此功能适用于批次中的每个图像。

import cv2

def preprocess(image):
   # feel free to define your own function here
   # be sure this function returns an image

   processed_image = cv2.resize(image, dsize=(224,224)) 

   return processed_image

train_dataGen = ImageDataGenerator(preprocessing_function=preprocess,
                                   rescale=1./255)

推荐阅读