如何使用从文件夹中读取的所有图像进行图像增强

2024-10-02 08:21:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用下面的代码读取文件夹中的所有图像,并使用它们进行图像增强。load_images()函数将所有图像读取为numpy数组,但当我在代码的第二部分中使用此函数作为图像增强的输入时,会出现错误(使用序列设置数组元素)。感谢您的帮助。你知道吗

from tensorflow.keras.preprocessing.image import ImageDataGenerator
from matplotlib.pyplot import imread, imshow, subplots, show
from matplotlib import pyplot as plt
import matplotlib.image as mpimg
import os

image_path = '/path/to/images/'
def load_images(image_path):
    imagees = []
    for filename in os.listdir(image_path):
        img = mpimg.imread(os.path.join(image_path, filename))
        if img is not None:
            imagees.append(img)
    return imagees

datagen = ImageDataGenerator(rotation_range=90, width_shift_range=0.3, 
height_shift_range=0.3,shear_range=45.0, brightness_range=(0.1, 0.9), 
zoom_range=[0.5, 1.5],channel_shift_range = 150.0, horizontal_flip=True, vertical_flip=True)
images = load_images(image_path)
images = image.reshape((1, image.shape[0], image.shape[1], image.shape[2]))
save_here = '/path/to/images/'
datagen.fit(images)
for x, val in zip(datagen.flow(images,
        save_to_dir=save_here,
         save_prefix='aug',
        save_format='png'),range(36)):
  pass

Tags: topathfromimageimportimgshiftmatplotlib
3条回答

你可能有一个输入错误,你叫你的列表imagees,然后继续images,你知道吗?你知道吗

非常感谢你的帮助。我根据你的评论对我的代码做了一些修改,但有时会出现以下错误。主要的问题是代码只增加文件夹中图像列表中的一个图像,而不是全部。 [Code with error[1]

我跑不了所以我猜。你知道吗

直列

images = load_images(image_path)

将数组/图像分配给images列表。一切都好。你知道吗

但在下一行

images = image.reshape((1, image.shape[0], image.shape[1], image.shape[2]))

将单个图像/数组指定给images,这样就删除了前面的列表。我在代码中没有看到变量image,所以我不知道它是什么,所以我只能猜测。你知道吗

如果您想重塑列表images上的所有图像,那么您可以在读取图像时这样做

imagees.append(img.reshape((1, img.shape[0], img.shape[1], img.shape[2])))

或者您必须使用for-循环或列表理解来分别重塑每个图像

new_images = []

for image in images:
    new_images.append(image.reshape((1, image.shape[0], image.shape[1], image.shape[2])))

images = new_images

或与列表理解

images = [img.reshape((1, img.shape[0], img.shape[1], img.shape[2])) for img in images]

相关问题 更多 >

    热门问题