Reputation: 129
I am trying to run a basic GAN Neural Network from: https://www.tensorflow.org/tutorials/generative/dcgan
Following along with the code in here it works fine when I use the mnist dataset. I would like to try this with my own custom images instead.
I am loading the images as follows:
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
Output of shape is:
(100,)
Following the tensorflow doc to load and preprocess images they use the following:
(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)
My question is how can I reshape my current batch set of images to match the input needed to follow along with the doc?
If I try to just plug in my own data I get:
ValueError: cannot reshape array of size 100 into shape (100,28,28,3)
Upvotes: 1
Views: 864
Reputation: 26718
Maybe the images you are loading have a different number of channels. Try printing out the shape of each image array in your for loop. Anyway, I would recommend using open opencv
to read your images. It is pretty straightforward and apparently faster than PIL
:
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
Upvotes: 1