use yolo instead : # Import necessary libraries
import tensorflow as tf
import os
import numpy as np
import glob
from PIL import Image
import matplotlib.pyplot as plt
def getFENtileLabel(fen,letter,number):
"""Given a fen string and a rank (number) and file (letter), return label vector"""
l2i = lambda l: ord(l)-ord('A') # letter to index
number = 8-number # FEN has order backwards
piece_letter = fen[number*8+number + l2i(letter)]
label = np.zeros(13, dtype=np.uint8)
label['1KQRBNPkqrbnp'.find(piece_letter)] = 1 # note the 1 instead of ' ' due to FEN notation
We ignore shorter FENs with numbers > 1 because we generate the FENs ourselves
return label
We'll define the 12 pieces and 1 spacewith single characters
KQRBNPkqrbnp
def getLabelForSquare(letter,number):
"""Given letter and number (say 'B3'), return one-hot label vector
(12 pieces + 1 space == no piece, so 13-long vector)"""
l2i = lambda l: ord(l)-ord('A') # letter to index
piece2Label = lambda piece: ' KQRBNPkqrbnp'.find(piece)
def loadLabels(image_filepaths):
"""Load label vectors from list of image filepaths"""
Each filepath contains which square we're looking at,
since we're in starter position, we know which
square has which piece, 12 distinct pieces
(6 white and 6 black) and 1 as empty = 13 labels
training_data = np.zeros([image_filepaths.size, 13], dtype=np.float64)
for i, image_filepath in enumerate(image_filepaths):
training_data[i,:] = getLabelForSquare(image_filepath[-6],int(image_filepath[-5]))
return training_data
def loadImages(image_filepaths):
Each tile is a 32x32 grayscale image, add extra axis for working with MNIST Data format
training_data = np.zeros([image_filepaths.size, 32, 32, 1], dtype=np.uint8)
for i, image_filepath in enumerate(image_filepaths):
if i % 100 == 0:
print("On #%d/%d : %s" % (i,image_filepaths.size, image_filepath))
img = Image.open(image_filepath)
training_data[i,:,:,0] = np.asarray(img, dtype=np.uint8)
return training_data
Set NumPy print options for better readability
np.set_printoptions(precision=2, suppress=True)
Load and prepare the data
Adjust the path according to your data location
data_path = "tiles//.png" # Update this path as needed
all_paths = np.array(glob.glob(data_path)) # Ensure labels are set correctly
Verify that the data path contains files
if len(all_paths) == 0:
print(f"No image files found in the path: {data_path}")
exit(1)
Shuffle the paths
np.random.shuffle(all_paths)
Split the data into training and testing sets (90/10 ratio)
ratio = 0.9 # Training/testing ratio
divider = int(len(all_paths) * ratio)
train_paths = all_paths[:divider]
test_paths = all_paths[divider:]
Load training dataset
print(f"Loading {train_paths.size} Training tiles")
train_images, train_labels = loadFENtiles(train_paths) # Ensure this function works correctly
do_training = True # Set to True to train the model
epochs = 25 # Adjust the number of epochs as needed
batch_size = 100 # Batch size for training
if do_training:
# Train the model
print(f"Training for {epochs} epochs...")
model.fit(train_images, train_labels, epochs=epochs, batch_size=batch_size,
validation_data=(test_images, test_labels), verbose=1)
print("Finished training.")
code
# Ensure 'saved_models' directory exists
if not os.path.exists('saved_models'):
os.makedirs('saved_models')
# Save the trained model
model.save('saved_models/model_{}.h5'.format(epochs))
print(f"Model saved in file: saved_models/model_{epochs}.h5")
else:
# Load the pre-trained model
model_name = 'saved_models/model_{}.h5'.format(epochs)
print(f"Loading model '{model_name}'")
if os.path.exists(model_name):
model = tf.keras.models.load_model(model_name)
print("Model loaded.")
else:
print(f"Model file '{model_name}' not found.")
exit(1)
Evaluate the model on the testing dataset
test_loss, test_accuracy = model.evaluate(test_images, test_labels, verbose=0)
print(f"Accuracy on test set: {test_accuracy * 100:.2f}%\n")
Certainly! If you'd like to use YOLO (You Only Look Once) for object detection instead of the custom convolutional neural network (CNN) you've provided, I'll guide you through the process. YOLO is a popular and efficient object detection algorithm that can detect multiple objects in an image in real-time.
In your current code, you're using a CNN to classify chess pieces on a chessboard based on image tiles. Switching to YOLO will allow you to detect and classify all the chess pieces on the board in a single forward pass, which can be more efficient and practical, especially for real-time applications.
Here's how you can modify your code to use YOLO:
1. Install Required Libraries
First, you need to install the necessary libraries. For YOLOv5, which is implemented in PyTorch, you can clone the repository and install the requirements:
Labels: Text files containing bounding box coordinates and class labels for each object in the images.
Since you have images of chess pieces and labels, you'll need to convert your labels into YOLO format.
Label Format
Each label file should correspond to an image file and have the same filename but with a .txt extension instead of .jpg or .png. Each line in the label file represents one object in the image, in the following format:
code
<class_id> <x_center> <y_center> <width> <height>
<class_id>: Integer representing the class (e.g., pawn, knight, etc.).
<x_center>, <y_center>, <width>, <height>: Normalized coordinates (values between 0 and 1) relative to the image size.
Steps to Prepare Labels
If you have annotations in a different format, you'll need to convert them. Here's an example of how you might convert your existing labels:
python
import os
import cv2
# Define class names and their corresponding IDs
class_names = ['K', 'Q', 'R', 'B', 'N', 'P', 'k', 'q', 'r', 'b', 'n', 'p', 'empty']
class_to_id = {name: idx for idx, name in enumerate(class_names)}
# Path to your images and labels
images_path = 'path_to_your_images' # Update this path
labels_output_path = 'path_to_your_labels' # Update this path
if not os.path.exists(labels_output_path):
os.makedirs(labels_output_path)
# Loop through images and create labels
for image_name in os.listdir(images_path):
if image_name.endswith('.png') or image_name.endswith('.jpg'):
image_path = os.path.join(images_path, image_name)
img = cv2.imread(image_path)
height, width, _ = img.shape
# Replace this with your method of getting object annotations
# For example, if you have bounding boxes and class labels:
objects = get_objects_for_image(image_name) # This function needs to be defined
# Create label file
label_filename = os.path.splitext(image_name)[0] + '.txt'
label_file_path = os.path.join(labels_output_path, label_filename)
with open(label_file_path, 'w') as f:
for obj in objects:
class_id = class_to_id[obj['class_name']]
x_center = (obj['x_min'] + obj['x_max']) / 2 / width
y_center = (obj['y_min'] + obj['y_max']) / 2 / height
obj_width = (obj['x_max'] - obj['x_min']) / width
obj_height = (obj['y_max'] - obj['y_min']) / height
f.write(f"{class_id} {x_center} {y_center} {obj_width} {obj_height}\n")
You'll need to implement get_objects_for_image(image_name) to return a list of objects with their bounding box coordinates and class labels.
3. Configure YOLOv5 for Your Dataset
Create a YAML configuration file for your dataset (e.g., chess.yaml):
yaml
train: ../data/images/train # Path to training images
val: ../data/images/val # Path to validation images
nc: 13 # Number of classes
names: ['K', 'Q', 'R', 'B', 'N', 'P', 'k', 'q', 'r', 'b', 'n', 'p', 'empty'] # Class names
Make sure the paths to your training and validation images are correct.
4. Train YOLOv5 on Your Dataset
Now you can train YOLOv5 using your dataset:
python
import torch
from yolov5 import train
# Training parameters
data_yaml = 'chess.yaml' # Path to your data config file
epochs = 50 # Number of epochs to train
batch_size = 16 # Batch size
img_size = 640 # Image size for training
# Run training
!python train.py --img {img_size} --batch {batch_size} --epochs {epochs} --data {data_yaml} --weights yolov5s.pt
This command uses the train.py script from the YOLOv5 repository to train the model. It starts from pre-trained weights (yolov5s.pt).
5. Evaluate the Model
After training, you can evaluate the model on your test dataset:
python
# Path to the trained weights
weights_path = 'runs/train/exp/weights/best.pt' # Update with your actual path
# Run validation
!python val.py --img {img_size} --batch {batch_size} --data {data_yaml} --weights {weights_path}
6. Make Predictions
You can now use the trained model to make predictions on new images:
python
# Path to an image or directory of images
source = 'path_to_your_test_images' # Update this path
# Run inference
!python detect.py --weights {weights_path} --img {img_size} --conf 0.25 --source {source}
The detect.py script will save the detection results in the runs/detect/ directory.
7. Integrate YOLO into Your Application
If you want to integrate YOLO into your Python application, you can use the YOLOv5 models directly:
python
import torch
# Load the model
model = torch.hub.load('ultralytics/yolov5', 'custom', path=weights_path)
# Set model parameters
model.conf = 0.25 # Confidence threshold
# Perform inference
results = model('path_to_image_or_directory')
# Results
results.print() # Print results to console
results.save() # Save images with detections
# To access the detection results
detections = results.pandas().xyxy[0] # Predictions as pandas DataFrame
print(detections)
8. Post-Processing and Visualization
You can process detections DataFrame to extract detected pieces and their positions. Each detection includes:
xmin, ymin, xmax, ymax: Bounding box coordinates.
confidence: Confidence score.
class: Class ID.
name: Class name.
This information can be used to map the detected pieces to the corresponding squares on the chessboard.
Example: Mapping Detections to Chessboard Squares
Assuming you're working with a standard chessboard image taken from a fixed perspective, you can calculate which square each detected piece belongs to based on the bounding box coordinates.
python
import numpy as np
def get_square(x_center, y_center, image_width, image_height):
# Assuming the board is properly aligned and fills the image
square_size_x = image_width / 8
square_size_y = image_height / 8
col = int(x_center / square_size_x)
row = int(y_center / square_size_y)
return row, col # 0-indexed row and column
image = cv2.imread('path_to_image')
image_height, image_width, _ = image.shape
for index, row in detections.iterrows():
x_center = (row['xmin'] + row['xmax']) / 2
y_center = (row['ymin'] + row['ymax']) / 2
piece_class = row['name']
row_idx, col_idx = get_square(x_center, y_center, image_width, image_height)
print(f"Detected {piece_class} at square ({row_idx}, {col_idx})")
Summary
Switching to YOLO involves the following steps:
Dataset Preparation: Convert your existing images and labels into the format required by YOLO.
Configuration: Create a YAML config file specifying paths and class names.
Training: Train the YOLO model using your dataset.
Inference: Use the trained model to detect pieces in new images.
Integration: Incorporate the detection results into your application logic.
Additional Notes
Data Augmentation: YOLOv5 includes data augmentation techniques that can improve model performance.
Fine-Tuning Parameters: You may need to adjust training parameters such as learning rate, batch size, and epochs based on your dataset.
Custom Models: If your images are of smaller resolution or you need faster inference, consider using smaller models like yolov5n or yolov5s.
Model Export: YOLOv5 supports exporting models to formats like ONNX or TensorRT for deployment in different environments.