Skip to content
Projects
Groups
Snippets
Help
Loading...
Help
Support
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in / Register
Toggle navigation
2
2023-028
Project overview
Project overview
Details
Activity
Releases
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Issues
0
Issues
0
List
Boards
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Analytics
Analytics
CI / CD
Repository
Value Stream
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
Ramanayaka D.H.
2023-028
Commits
35aa65a3
Commit
35aa65a3
authored
May 22, 2023
by
Parindya H.S.T
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
This is the code of the model that I have implemented using direct CNN
parent
9a4ddc60
Changes
1
Show whitespace changes
Inline
Side-by-side
Showing
1 changed file
with
124 additions
and
0 deletions
+124
-0
CNN.txt
CNN.txt
+124
-0
No files found.
CNN.txt
0 → 100644
View file @
35aa65a3
# 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")
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment