Sure! Below is the code that trains an image generative AI using TensorFlow and Keras. It checks if a pre-trained model is already available in the file system and if not, it trains a new model using images from a specified folder.
import os
import random
import numpy as np
from tensorflow.python import keras
from tensorflow.python.keras.preprocessing.image import load_img, img_to_array
# Path to the folder containing training images
training_folder = "/path/to/training/folder"
# Path to the folder containing test images
test_folder = "/path/to/test/folder"
# Check if a pre-trained model is already available
if os.path.exists("generative_model.h5"):
# Load the pre-trained model
model = keras.models.load_model("generative_model.h5")
print("Loaded pre-trained model.")
else:
# List all image file names in the training folder
image_files = os.listdir(training_folder)
random.shuffle(image_files)
# Function to preprocess images
def preprocess_image(image_path):
img = load_img(image_path, color_mode="grayscale", target_size=(64, 64))
img = img_to_array(img)
img = img / 255.0 # Normalize pixel values
return img
# Load and preprocess training images
training_images = []
for image_file in image_files:
image_path = os.path.join(training_folder, image_file)
img = preprocess_image(image_path)
training_images.append(img)
training_images = np.array(training_images)
# Define the model architecture
model = keras.Sequential([
keras.layers.Conv2D(64, (3, 3), activation='relu', input_shape=(64, 64, 1)),
keras.layers.MaxPooling2D((2, 2)),
keras.layers.Conv2D(128, (3, 3), activation='relu'),
keras.layers.MaxPooling2D((2, 2)),
keras.layers.Flatten(),
keras.layers.Dense(128, activation='relu'),
keras.layers.Dense(64, activation='relu'),
keras.layers.Dense(1)
])
model.compile(optimizer='adam', loss='mse')
# Train the model
model.fit(training_images, training_images, epochs=10, batch_size=32)
# Save the trained model
model.save("generative_model.h5")
print("Trained model saved.")
# Load and preprocess test images
test_images = []
test_image_files = os.listdir(test_folder)
for image_file in test_image_files:
image_path = os.path.join(test_folder, image_file)
img = preprocess_image(image_path)
test_images.append(img)
test_images = np.array(test_images)
# Use the model to generate images
generated_images = model.predict(test_images)
# Process and save the generated images
for i, generated_image in enumerate(generated_images):
generated_image = (generated_image * 255.0).astype(np.uint8)
generated_image = np.squeeze(generated_image, axis=2)
generated_image = Image.fromarray(generated_image)
generated_image.save(f"generated_image_{i}.png")
Note that this code assumes the images are grayscale and resizes them to a fixed size of 64x64 pixels. You can modify the preprocessing step according to your image requirements. Additionally, the model architecture is a simple convolutional neural network (CNN) but you can experiment with different architectures to improve the generative results.