【问题标题】:How to use all images read from a folder for image augmentation如何使用从文件夹中读取的所有图像进行图像增强
【发布时间】:2020-03-25 07:58:48
【问题描述】:

我使用以下代码读取文件夹中的所有图像并将它们用于图像增强。 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

【问题讨论】:

  • 总是将完整的错误消息(从单词“Traceback”开始)作为文本(不是屏幕截图)放在有问题的(不是评论)中。还有其他有用的信息。
  • 首先您使用load_images 读取所有图像并将它们分配给images,但在一行之后您将image 分配给相同的变量imagesimage 可能是单个图像。如果你想重塑所有图像,那么你应该在load_images(使用img.reshape())中进行,或者创建for-loop,它将对每个图像(来自列表images)分别进行。
  • 您可以使用print() 和/或print( type() ) - 查看变量images - print(images) print( type(images) ) 中的内容。在images =load_images() 之后,您应该拥有带有图像/数组的list。在images = image.reshape() 之后,您应该有单个图像/数组。

标签: python numpy tensorflow matplotlib python-os


【解决方案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-loop 或列表推导来分别重塑每个图像

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]

【讨论】:

    【解决方案2】:

    你可能有一个错字,你打电话给你的名单imagees然后继续images,你知道吗?

    【讨论】:

      【解决方案3】:

      非常感谢您的帮助。我根据您的 cmets 对我的代码进行了一些更改,但有时会出现以下错误。主要问题是代码仅从文件夹中的图像列表中增加一个图像,而不是全部。 [

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-03
        • 2015-04-24
        • 1970-01-01
        • 2022-01-25
        • 2021-10-20
        • 2011-03-12
        相关资源
        最近更新 更多