Commit 35aa65a3 authored by Parindya H.S.T 's avatar Parindya H.S.T

This is the code of the model that I have implemented using direct CNN

parent 9a4ddc60
# Import necessary libraries
import matplotlib.pyplot as plt
import numpy as np
import cv2
import os
import PIL
import tensorflow as tf
from PIL import Image
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.models import Sequential
# Define the path to the dataset directory
data_dir='.\\datasets\\balls_images'
# Print the path
print(data_dir)
# Convert path to a pathlib object
import pathlib
data_dir = pathlib.Path(data_dir)
# Print the pathlib object
print(data_dir)
# List the image files in the dataset directory
list(data_dir.glob('*/*.jpg'))[:5]
# Count the total number of images in the dataset
image_count = len(list(data_dir.glob('*/*.jpg')))
print(image_count)
# Define the list of legal ball images
legal_ball = list(data_dir.glob('legal_ball/*'))
# Display an example image from the legal ball images
PIL.Image.open(str(legal_ball[1]))
# Define a dictionary containing the paths of all ball images grouped by ball type
balls_images_dict = {
'no_ball': list(data_dir.glob('no_ball/*')),
'legal_ball': list(data_dir.glob('legal_ball/*')),
}
# Define a dictionary containing the class labels for each ball type
balls_labels_dict = {
'no_ball': 0,
'legal_ball': 1,
}
# Display the paths to the first five 'no_ball' images
balls_images_dict['no_ball'][:5]
# Load an image using OpenCV and display its shape
img = cv2.imread(str(balls_images_dict['no_ball'][0]))
img.shape
# Resize the image and display its new shape
cv2.resize(img,(180,180)).shape
# Initialize empty lists for the features and labels
X, y = [], []
# Iterate through each ball type and its corresponding images
for ball_type, images in balls_images_dict.items():
for image in images:
# Load the image using OpenCV and resize it to (224,224)
img = cv2.imread(str(image))
resized_img = cv2.resize(img,(224,224))
# Append the resized image to the feature list and its label to the label list
X.append(resized_img)
y.append(balls_labels_dict[ball_type])
# Convert the feature and label lists to numpy arrays
X = np.array(X)
y = np.array(y)
# Split the dataset into training and testing sets
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
# Normalize the pixel values of the training and testing sets
X_train_scaled = X_train / 255
X_test_scaled = X_test / 255
# Define the number of classes
num_classes = 2
# Define the convolutional neural network model
model = Sequential([
layers.Conv2D(16, 3, padding='same', activation='relu'),
layers.MaxPooling2D(),
layers.Conv2D(32, 3, padding='same', activation='relu'),
layers.MaxPooling2D(),
layers.Conv2D(64, 3, padding='same', activation='relu'),
layers.MaxPooling2D(),
layers.Flatten(),
layers.Dense(128, activation='relu'),
layers.Dense(num_classes)
])
# Compile the model
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
# Train the model
model.fit(X_train_scaled, y_train, epochs=5)
model.evaluate(X_test_scaled,y_test)
loss, accuracy = model.evaluate(X_test_scaled,y_test)
print('Accuracy:', accuracy)
plt.imshow(X[0])
# save the model
model.save("balls_model.h5")
from tensorflow.keras.models import load_model
loaded_model = load_model("balls_model.h5")
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment