【问题标题】:Image Shape Issue with Tensorflow and NumpyTensorFlow 和 Numpy 的图像形状问题
【发布时间】:2022-01-16 13:34:34
【问题描述】:

我正在尝试从https://www.tensorflow.org/tutorials/generative/dcgan 运行基本的 GAN 神经网络

按照此处的代码,当我使用 mnist 数据集时它可以正常工作。我想用我自己的自定义图像来试试这个。

我正在按如下方式加载图像:

import glob
import imageio
import matplotlib.pyplot as plt
import numpy as np
import os
import PIL
from tensorflow.keras import layers
import time
import tensorflow as tf
from PIL import Image
from IPython import display

#Set Max image pixels to none to avoid pixel limit breach
Image.MAX_IMAGE_PIXELS = None

#Create empty list for images
images = []

#Glob together images from file and create numpy aray with them
for f in glob.iglob("...Images/*"):
    images.append(np.asarray(Image.open(f)))

#Load image array into empty list
images = np.array(images)

#Show array shape
images.shape

形状的输出是:

(100,)

按照 tensorflow 文档加载和预处理图像,他们使用以下内容:

(train_images, train_labels), (_, _) = tf.keras.datasets.mnist.load_data()

train_images = train_images.reshape(train_images.shape[0], 28, 28, 1).astype('float32')
train_images = (train_images - 127.5) / 127.5  # Normalize the images to [-1, 1]

BUFFER_SIZE = 60000
BATCH_SIZE = 256

# Batch and shuffle the data
train_dataset = tf.data.Dataset.from_tensor_slices(train_images).shuffle(BUFFER_SIZE).batch(BATCH_SIZE)

我的问题是如何重塑我当前的一批图像以匹配文档所需的输入?

如果我尝试插入我自己的数据,我会得到:

ValueError: 无法将大小为 100 的数组重新整形为 (100,28,28,3)

【问题讨论】:

  • Do images.dtype 看起来你有一个对象数组。
  • 运行 dtype 时我得到:dtype('O') 查看第一个索引图像时 [0] 我得到:array([[[63, 28, 9], [77, 25, 14], [72, 49, 15], ..., [38, 29, 20], [38, 29, 20], [38, 29, 20]], (继续几行)和 dtype on这表明:dtype=uint8
  • O 是一个对象类型。我怀疑这条线弄错了np.asarray(Image.open(f))。我想你想在这里用np.concatenate 做点什么。我没有时间亲自测试它并给你一个正确的答案,但希望其他人这样做,或者如果你在该区域周围添加一些调试语句,也许你可以弄清楚并回答。

标签: python image numpy tensorflow tensorflow2.0


【解决方案1】:

也许您正在加载的图像具有不同数量的通道。尝试在 for 循环中打印出每个图像数组的形状。无论如何,我建议使用 open opencv 来阅读您的图像。它非常简单,apparentlyPIL 快:

import glob
import cv2

Image.MAX_IMAGE_PIXELS = None
images = []
for f in glob.iglob("images/*"):
    images.append(np.asarray(cv2.imread(f)))

images = np.array(images)
images.shape
# (3, 100, 100, 3) 3 images 100x100x3

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-02
    • 2019-05-25
    • 1970-01-01
    • 2020-06-24
    • 2021-05-18
    • 2021-10-12
    • 2021-07-15
    • 2021-02-18
    相关资源
    最近更新 更多