Sure! I can guide you through the process of training an AI model to differentiate between two types of images stored in different folders using Python. We'll be using the popular deep learning library, Keras, which provides an easy way to build and train neural networks.
Here are the steps we'll cover:
- Set up the directory structure.
- Preprocess the data.
- Build and train the model.
- Save the trained model.
- Create a separate program to use the trained model.
Let's start with the training program:
-
Set up the directory structure:
- Create a folder named "dataset" in your project directory.
- Inside the "dataset" folder, create two subfolders for each type of image, let's say "class1" and "class2".
- Place the respective images in each of these subfolders.
-
Preprocess the data:
-
Import the required libraries:
import os
import cv2
import numpy as np
from keras.preprocessing.image import ImageDataGenerator
-
Define the image dimensions and paths:
img_width, img_height = 150, 150
train_data_dir = 'dataset'
-
Prepare the training data generator:
train_datagen = ImageDataGenerator(rescale=1.0/255)
train_generator = train_datagen.flow_from_directory(
train_data_dir,
target_size=(img_width, img_height),
batch_size=32,
class_mode='binary'
)
-
Build and train the model:
-
Import the necessary libraries:
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense
-
Build the model:
model = Sequential()
model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(img_width, img_height, 3)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(64, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
-
Compile and train the model:
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(train_generator, epochs=10)
-
Save the trained model:
-
After training, save the model for future use:
model.save('image_classifier.h5')
print("Model saved successfully!")
Now, let's create a separate program to use the trained model:
-
Import the required libraries:
from keras.models import load_model
import cv2
-
Load the trained model:
model = load_model('image_classifier.h5')
-
Use the model to predict new images:
def predict_image(image_path):
img = cv2.imread(image_path)
img = cv2.resize(img, (img_width, img_height))
img = np.expand_dims(img, axis=0)
result = model.predict_classes(img)
if result[0][0] == 1:
print("Class 2")
else:
print("Class 1")
Note: Make sure this program is present in the same directory as the trained model.
That's it! You now have a training program to train the AI model and another program to use the trained model for image classification. Remember to adjust the code based on your specific dataset and requirements.