for every tile run predictor and get chess fen : import os
import cv2
import numpy as np
import math
from PIL import Image
import torch
import torch.nn as nn
import torch.nn.functional as F
import matplotlib.pyplot as plt
Set device (use GPU if available, otherwise fallback to CPU)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
CNN model definition
class CNNModel(nn.Module):
def init(self):
super(CNNModel, self).init()
# First Convolutional Layer: 32 features, 5x5 kernel
self.conv1 = nn.Conv2d(in_channels=1, out_channels=32, kernel_size=5, padding=2)
# Second Convolutional Layer: 64 features, 5x5 kernel
self.conv2 = nn.Conv2d(in_channels=32, out_channels=64, kernel_size=5, padding=2)
# Fully connected layer
self.fc1 = nn.Linear(8 * 8 * 64, 1024)
self.dropout = nn.Dropout(p=0.5) # Dropout with a probability of 0.5
# Output layer
self.fc2 = nn.Linear(1024, 13)
code
# Initialize weights and biases
self._initialize_weights()
def _initialize_weights(self):
# Initialize weights with truncated normal (approximate with normal and clamp)
nn.init.trunc_normal_(self.conv1.weight, std=0.1)
nn.init.constant_(self.conv1.bias, 0.1)
nn.init.trunc_normal_(self.conv2.weight, std=0.1)
nn.init.constant_(self.conv2.bias, 0.1)
nn.init.trunc_normal_(self.fc1.weight, std=0.1)
nn.init.constant_(self.fc1.bias, 0.1)
nn.init.trunc_normal_(self.fc2.weight, std=0.1)
nn.init.constant_(self.fc2.bias, 0.1)
def forward(self, x):
# Apply first convolutional layer + ReLU activation
x = F.relu(self.conv1(x))
x = F.max_pool2d(x, kernel_size=2, stride=2) # First pooling
# Apply second convolutional layer + ReLU activation
x = F.relu(self.conv2(x))
x = F.max_pool2d(x, kernel_size=2, stride=2) # Second pooling
# Flatten the tensor
x = x.view(-1, 8 * 8 * 64)
# Fully connected layer + ReLU activation
x = F.relu(self.fc1(x))
# Apply dropout
x = self.dropout(x)
# Output layer (no activation, as CrossEntropyLoss applies Softmax internally)
x = self.fc2(x)
return x
def load_model(model_path):
model = CNNModel() # Instantiate the model
model.load_state_dict(torch.load(model_path, map_location=device)) # Load model parameters
model.to(device)
model.eval() # Set to evaluation mode
return model
Prepare an image for prediction
def prepare_image(image_path):
"""Prepares an image for prediction by the model"""
with Image.open(image_path) as img:
img = img.convert('L') # Convert to grayscale
img = img.resize((32, 32)) # Resize to 32x32 if needed
img_array = np.array(img, dtype=np.float32) / 255.0 # Normalize pixel values
img_array = np.expand_dims(img_array, axis=0) # Add channel dimension
img_tensor = torch.tensor(img_array, dtype=torch.float32) # Convert to tensor
img_tensor = img_tensor.unsqueeze(0) # Add batch dimension
return img_tensor
Predict the class of the image
def predict_image(image_tensor, model):
"""Predict the class of a single image using the loaded model"""
image_tensor = image_tensor.to(device) # Move image to the same device as the model
with torch.no_grad(): # Disable gradient computation during inference
outputs = model(image_tensor) # Forward pass
_, predicted = torch.max(outputs.data, 1) # Get the predicted class index
return predicted.item()
Display image and predicted class
def display_image_with_prediction(image_path, predicted_class):
"""Display the image along with the predicted label"""
img = Image.open(image_path).convert('L')
plt.imshow(img, cmap='gray')
plt.title(f'Predicted: {labelIndex2Name(predicted_class)}')
plt.axis('off')
plt.show()
Function definitions
def gradientx(img):
# Compute gradient in x-direction using larger Sobel kernel
grad_x = cv2.Sobel(img, cv2.CV_32F, 1, 0, ksize=31)
return grad_x
def gradienty(img):
# Compute gradient in y-direction using larger Sobel kernel
grad_y = cv2.Sobel(img, cv2.CV_32F, 0, 1, ksize=31)
return grad_y
def checkMatch(lineset):
linediff = np.diff(lineset)
x = 0
cnt = 0
for line in linediff:
if abs(line - x) < 5:
cnt += 1
else:
cnt = 0
x = line
return cnt == 5
def pruneLines(lineset, image_dim, margin=20):
# Remove lines near the margins
lineset = [x for x in lineset if x > margin and x < image_dim - margin]
if not lineset:
return lineset
linediff = np.diff(lineset)
x = 0
cnt = 0
start_pos = 0
for i, line in enumerate(linediff):
if abs(line - x) < 5:
cnt += 1
if cnt == 5:
end_pos = i + 2
return lineset[start_pos:end_pos]
else:
cnt = 0
x = line
start_pos = i
return lineset
def skeletonize_1d(arr):
_arr = arr.copy()
for i in range(len(_arr) - 1):
if _arr[i] <= _arr[i + 1]:
_arr[i] = 0
for i in range(len(_arr) - 1, 0, -1):
if _arr[i - 1] > _arr[i]:
_arr[i] = 0
return _arr
# Pad the image if necessary
padl_x = 0
padr_x = 0
padl_y = 0
padr_y = 0
if lines_x[0] - stepx < 0:
padl_x = abs(lines_x[0] - stepx)
if lines_x[-1] + stepx > img.shape[1] - 1:
padr_x = lines_x[-1] + stepx - img.shape[1] + 1
if lines_y[0] - stepy < 0:
padl_y = abs(lines_y[0] - stepy)
if lines_y[-1] + stepy > img.shape[0] - 1:
padr_y = lines_y[-1] + stepy - img.shape[0] + 1
img_padded = cv2.copyMakeBorder(img, padl_y, padr_y, padl_x, padr_x, cv2.BORDER_REPLICATE)
setsx = [lines_x[0] - stepx + padl_x] + [x + padl_x for x in lines_x] + [lines_x[-1] + stepx + padl_x]
setsy = [lines_y[0] - stepy + padl_y] + [y + padl_y for y in lines_y] + [lines_y[-1] + stepy + padl_y]
squares = []
for j in range(8):
for i in range(8):
x1 = setsx[i]
x2 = setsx[i + 1]
y1 = setsy[j]
y2 = setsy[j + 1]
# Adjust sizes to ensure squares are of equal size
if (x2 - x1) != stepx:
x2 = x1 + stepx
if (y2 - y1) != stepy:
y2 = y1 + stepy
square = img_padded[y1:y2, x1:x2]
squares.append(square)
return squares
def process_image(image_path, output_dir):
# Load the image
image = cv2.imread(image_path)
if image is None:
print(f"Failed to load image: {image_path}")
return
# Convert to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
code
# Preprocessing
equ = cv2.equalizeHist(gray)
norm_image = equ.astype(np.float32) / 255.0
# Compute the gradients
grad_x = gradientx(norm_image)
grad_y = gradienty(norm_image)
# Clip the gradients
Dx_pos = np.clip(grad_x, 0, None)
Dx_neg = np.clip(-grad_x, 0, None)
Dy_pos = np.clip(grad_y, 0, None)
Dy_neg = np.clip(-grad_y, 0, None)
# Compute the Hough transform
hough_Dx = (np.sum(Dx_pos, axis=0) * np.sum(Dx_neg, axis=0)) / (norm_image.shape[0] ** 2)
hough_Dy = (np.sum(Dy_pos, axis=1) * np.sum(Dy_neg, axis=1)) / (norm_image.shape[1] ** 2)
# Adaptive thresholding
a = 1
is_match = False
lines_x = []
lines_y = []
while a < 5:
threshold_x = np.max(hough_Dx) * (a / 5.0)
threshold_y = np.max(hough_Dy) * (a / 5.0)
lines_x, lines_y, is_match = getChessLines(hough_Dx, hough_Dy, threshold_x, threshold_y, norm_image.shape)
if is_match:
break
else:
a += 1
if is_match:
print("7 horizontal and vertical lines found, slicing up squares")
squares = getChessTiles(gray, lines_x, lines_y)
print(f"Tiles generated: ({squares[0].shape[0]}x{squares[0].shape[1]}) * {len(squares)}")
# Extract filename and FEN (assuming filename is FEN)
img_filename = os.path.basename(image_path)
fen = os.path.splitext(img_filename)[0]
img_save_dir = os.path.join(output_dir, fen)
if not os.path.exists(img_save_dir):
os.makedirs(img_save_dir)
print(f"Created dir {img_save_dir}")
letters = "ABCDEFGH"
for i, square in enumerate(squares):
filename = f"{fen}_{letters[i % 8]}{(i // 8) + 1}.png"
save_path = os.path.join(img_save_dir, filename)
if i % 8 == 0:
print(f"#{i}: saving {save_path}...")
# Resize to 32x32 and save
resized = cv2.resize(square, (32, 32), interpolation=cv2.INTER_AREA)
cv2.imwrite(save_path, resized)
else:
print(f"No squares to save for {image_path}")
Main code
def main(file):
output_folder = "tiles" # Replace with your desired output folder
code
# Create output directory if it doesn't exist
os.makedirs(output_folder, exist_ok=True)
process_image(file, output_folder)
if name == "main":
main()
Certainly! It looks like you're working on a project to process an image of a chessboard, recognize the pieces on each square using a Convolutional Neural Network (CNN), and generate the corresponding Forsyth–Edwards Notation (FEN) string representing the board state.
I'll provide a comprehensive solution that integrates the prediction step for each tile and constructs the FEN string. Here's an enhanced version of your script with detailed explanations:
Enhanced Script Overview
Model Loading: Load the pre-trained CNN model to predict the chess pieces on each tile.
Image Processing: Detect and extract individual squares from the chessboard image.
Prediction: For each extracted square, use the CNN model to predict the piece present.
FEN Generation: Convert the predictions into a valid FEN string.
Output: Display or save the FEN string for further use.
Complete Enhanced Script
python
import os
import cv2
import numpy as np
import math
from PIL import Image
import torch
import torch.nn as nn
import torch.nn.functional as F
import matplotlib.pyplot as plt
# Set device (use GPU if available, otherwise fallback to CPU)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# CNN model definition
class CNNModel(nn.Module):
def __init__(self):
super(CNNModel, self).__init__()
# First Convolutional Layer: 32 features, 5x5 kernel
self.conv1 = nn.Conv2d(in_channels=1, out_channels=32, kernel_size=5, padding=2)
# Second Convolutional Layer: 64 features, 5x5 kernel
self.conv2 = nn.Conv2d(in_channels=32, out_channels=64, kernel_size=5, padding=2)
# Fully connected layer
self.fc1 = nn.Linear(8 * 8 * 64, 1024)
self.dropout = nn.Dropout(p=0.5) # Dropout with a probability of 0.5
# Output layer
self.fc2 = nn.Linear(1024, 13)
# Initialize weights and biases
self._initialize_weights()
def _initialize_weights(self):
# Initialize weights with truncated normal (approximate with normal and clamp)
nn.init.trunc_normal_(self.conv1.weight, std=0.1)
nn.init.constant_(self.conv1.bias, 0.1)
nn.init.trunc_normal_(self.conv2.weight, std=0.1)
nn.init.constant_(self.conv2.bias, 0.1)
nn.init.trunc_normal_(self.fc1.weight, std=0.1)
nn.init.constant_(self.fc1.bias, 0.1)
nn.init.trunc_normal_(self.fc2.weight, std=0.1)
nn.init.constant_(self.fc2.bias, 0.1)
def forward(self, x):
# Apply first convolutional layer + ReLU activation
x = F.relu(self.conv1(x))
x = F.max_pool2d(x, kernel_size=2, stride=2) # First pooling
# Apply second convolutional layer + ReLU activation
x = F.relu(self.conv2(x))
x = F.max_pool2d(x, kernel_size=2, stride=2) # Second pooling
# Flatten the tensor
x = x.view(-1, 8 * 8 * 64)
# Fully connected layer + ReLU activation
x = F.relu(self.fc1(x))
# Apply dropout
x = self.dropout(x)
# Output layer (no activation, as CrossEntropyLoss applies Softmax internally)
x = self.fc2(x)
return x
# Helper function to convert label index to name
def labelIndex2Name(label_index):
mapping = {
0: '1', # Empty square (represented by digits in FEN)
1: 'K', # White King
2: 'Q', # White Queen
3: 'R', # White Rook
4: 'B', # White Bishop
5: 'N', # White Knight
6: 'P', # White Pawn
7: 'k', # Black King
8: 'q', # Black Queen
9: 'r', # Black Rook
10: 'b', # Black Bishop
11: 'n', # Black Knight
12: 'p' # Black Pawn
}
return mapping.get(label_index, '?') # '?' for unknown classes
# Load the saved model
def load_model(model_path):
model = CNNModel() # Instantiate the model
model.load_state_dict(torch.load(model_path, map_location=device)) # Load model parameters
model.to(device)
model.eval() # Set to evaluation mode
return model
# Prepare an image for prediction
def prepare_image(image):
"""Prepares an image for prediction by the model"""
img = Image.fromarray(image).convert('L') # Convert to grayscale
img = img.resize((32, 32)) # Resize to 32x32
img_array = np.array(img, dtype=np.float32) / 255.0 # Normalize pixel values
img_array = np.expand_dims(img_array, axis=0) # Add channel dimension
img_tensor = torch.tensor(img_array, dtype=torch.float32) # Convert to tensor
img_tensor = img_tensor.unsqueeze(0) # Add batch dimension
return img_tensor
# Predict the class of the image
def predict_image(image_tensor, model):
"""Predict the class of a single image using the loaded model"""
image_tensor = image_tensor.to(device) # Move image to the same device as the model
with torch.no_grad(): # Disable gradient computation during inference
outputs = model(image_tensor) # Forward pass
_, predicted = torch.max(outputs.data, 1) # Get the predicted class index
return predicted.item()
# Display image and predicted class (optional)
def display_image_with_prediction(image, predicted_class):
"""Display the image along with the predicted label"""
plt.imshow(image, cmap='gray')
plt.title(f'Predicted: {labelIndex2Name(predicted_class)}')
plt.axis('off')
plt.show()
# [Existing Helper Functions: gradientx, gradienty, checkMatch, pruneLines, skeletonize_1d, getChessLines, getChessTiles]
# ... (Assuming all existing helper functions are here unchanged)
# Function to convert the board to FEN
def generate_fen(board_matrix):
fen_rows = []
for row in board_matrix:
fen_row = ""
empty_count = 0
for cell in row:
if cell == '1': # Empty square
empty_count += 1
else:
if empty_count > 0:
fen_row += str(empty_count)
empty_count = 0
fen_row += cell
if empty_count > 0:
fen_row += str(empty_count)
fen_rows.append(fen_row)
fen = "/".join(fen_rows) + " w KQkq - 0 1" # Default values for active color, castling, en passant, etc.
return fen
# Function to process image, predict tiles, and generate FEN
def process_image_and_generate_fen(image_path, output_dir, model):
# Load the image
image = cv2.imread(image_path)
if image is None:
print(f"Failed to load image: {image_path}")
return
# Convert to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Preprocessing
equ = cv2.equalizeHist(gray)
norm_image = equ.astype(np.float32) / 255.0
# Compute the gradients
grad_x = gradientx(norm_image)
grad_y = gradienty(norm_image)
# Clip the gradients
Dx_pos = np.clip(grad_x, 0, None)
Dx_neg = np.clip(-grad_x, 0, None)
Dy_pos = np.clip(grad_y, 0, None)
Dy_neg = np.clip(-grad_y, 0, None)
# Compute the Hough transform
hough_Dx = (np.sum(Dx_pos, axis=0) * np.sum(Dx_neg, axis=0)) / (norm_image.shape[0] ** 2)
hough_Dy = (np.sum(Dy_pos, axis=1) * np.sum(Dy_neg, axis=1)) / (norm_image.shape[1] ** 2)
# Adaptive thresholding
a = 1
is_match = False
lines_x = []
lines_y = []
while a < 5:
threshold_x = np.max(hough_Dx) * (a / 5.0)
threshold_y = np.max(hough_Dy) * (a / 5.0)
lines_x, lines_y, is_match = getChessLines(hough_Dx, hough_Dy, threshold_x, threshold_y, norm_image.shape)
if is_match:
break
else:
a += 1
if is_match:
print("7 horizontal and vertical lines found, slicing up squares")
squares = getChessTiles(gray, lines_x, lines_y)
print(f"Tiles generated: ({squares[0].shape[0]}x{squares[0].shape[1]}) * {len(squares)}")
# Extract filename and FEN (assuming filename is FEN)
img_filename = os.path.basename(image_path)
fen_initial = os.path.splitext(img_filename)[0]
img_save_dir = os.path.join(output_dir, fen_initial)
if not os.path.exists(img_save_dir):
os.makedirs(img_save_dir)
print(f"Created directory: {img_save_dir}")
letters = "ABCDEFGH"
board_matrix = [[] for _ in range(8)] # 8x8 board
for i, square in enumerate(squares):
# Calculate row and column
row = 7 - (i // 8) # FEN starts from rank 8 to 1
col = i % 8
filename = f"{fen_initial}_{letters[col]}{(i // 8) + 1}.png"
save_path = os.path.join(img_save_dir, filename)
if col == 0:
print(f"Row {8 - row}: saving {save_path}...")
# Resize to 32x32 for prediction
resized = cv2.resize(square, (32, 32), interpolation=cv2.INTER_AREA)
cv2.imwrite(save_path, resized)
# Predict the piece on this square
image_tensor = prepare_image(resized)
predicted_class = predict_image(image_tensor, model)
piece = labelIndex2Name(predicted_class)
board_matrix[row].append(piece)
# Optional: Display prediction
# display_image_with_prediction(resized, predicted_class)
# Generate FEN from board_matrix
fen = generate_fen(board_matrix)
print(f"Generated FEN: {fen}")
# Optionally, save FEN to a text file
fen_file_path = os.path.join(img_save_dir, "position.fen")
with open(fen_file_path, 'w') as fen_file:
fen_file.write(fen)
print(f"FEN saved to: {fen_file_path}")
else:
print(f"No squares to save for {image_path}")
# Main function
def main(image_file, model_path):
output_folder = "tiles" # Replace with your desired output folder
# Create output directory if it doesn't exist
os.makedirs(output_folder, exist_ok=True)
# Load the trained model
model = load_model(model_path)
print("Model loaded successfully.")
# Process the image, predict, and generate FEN
process_image_and_generate_fen(image_file, output_folder, model)
if __name__ == "__main__":
import argparse
# Set up command-line argument parsing
parser = argparse.ArgumentParser(description='Process a chessboard image and generate FEN.')
parser.add_argument('image_path', type=str, help='Path to the chessboard image.')
parser.add_argument('model_path', type=str, help='Path to the trained CNN model file.')
args = parser.parse_args()
# Run the main function with provided arguments
main(args.image_path, args.model_path)
Detailed Explanation
Model Loading:
load_model: This function loads the pre-trained CNN model from the specified path. Ensure that the model_path points to a valid .pth or .pt file containing the saved model state.
python
def load_model(model_path):
model = CNNModel()
model.load_state_dict(torch.load(model_path, map_location=device))
model.to(device)
model.eval()
return model
Image Processing and Tile Extraction:
process_image_and_generate_fen: This function handles the entire workflow:
Loads and preprocesses the image.
Detects the chessboard lines and extracts individual squares.
Saves each square as a separate image.
Prediction:
prepare_image: Prepares a square image for prediction by the CNN. It resizes the image to 32x32 pixels, normalizes the pixel values, and converts it to a PyTorch tensor.
predict_image: Uses the CNN model to predict the class of the given square image.
The script will process the image, extract each square, predict the piece (if any), and generate the corresponding FEN string.
The FEN string will be printed in the console and also saved to a position.fen file within a directory named after the image (without extension) inside the tiles folder.
Example Output:
code
Model loaded successfully.
7 horizontal and vertical lines found, slicing up squares
Tiles generated: (50x50) * 64
Created directory: tiles/board1
Row 8: saving tiles/board1/board1_A1.png...
...
Generated FEN: rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1
FEN saved to: tiles/board1/position.fen
Understanding the FEN String:
The FEN string represents the current state of a chess game. The parts are as follows:
Piece Placement: Each rank is described from the 8th to the 1st rank, with pieces represented by letters (KQRBNPkqrbnp) and empty squares by numbers.
Active Color:w means white to move, b for black.
Castling Availability:KQkq indicates both sides can castle both kingside and queenside.
En Passant Target Square: if none.
Additional Recommendations
Model Accuracy:
Ensure that your CNN model is well-trained with a diverse dataset of chess pieces under various lighting conditions and board styles to maximize prediction accuracy.
Handling Uncertainties:
Implement confidence thresholds. If the model's prediction confidence is below a certain threshold for any square, flag it for manual review or reprocessing.
Enhancing FEN Generation:
Currently, the script assumes default values for active color, castling rights, en passant targets, etc. For a more dynamic solution:
Active Color: Determine whose turn it is based on the game's history or additional inputs.
Castling Rights: Track whether kings or rooks have moved.
En Passant: Detect potential en passant targets.
Move Counters: Update halfmove and fullmove counters based on the game state.
User Interface:
Consider developing a graphical user interface (GUI) for easier interaction, especially if multiple images need processing.
Error Handling:
Implement robust error handling to manage unexpected issues, such as incorrectly detected squares, prediction anomalies, or file I/O errors.
Testing:
Validate the script with multiple chessboard images to ensure consistency and reliability in FEN generation.
Optimization:
For processing multiple images or larger datasets, consider optimizing the script for performance, potentially leveraging batch predictions with the CNN model.
Conclusion
The enhanced script provided integrates the prediction of each chessboard tile using a CNN and generates the corresponding FEN string. By following the usage instructions and considering the additional recommendations, you can develop a robust tool for digitizing chessboard images into standardized game representations.
Feel free to customize and extend the script further based on your specific requirements and project goals!
labelIndex2Name: Maps the predicted class index to the corresponding chess piece symbol as per FEN notation. Empty squares are represented numerically, while pieces are denoted by their respective letters. Uppercase letters represent white pieces, and lowercase letters represent black pieces.
python
def labelIndex2Name(label_index):
mapping = {
0: '1', # Empty square (represented by digits in FEN)
1: 'K', # White King
2: 'Q', # White Queen
3: 'R', # White Rook
4: 'B', # White Bishop
5: 'N', # White Knight
6: 'P', # White Pawn
7: 'k', # Black King
8: 'q', # Black Queen
9: 'r', # Black Rook
10: 'b', # Black Bishop
11: 'n', # Black Knight
12: 'p' # Black Pawn
}
return mapping.get(label_index, '?') # '?' for unknown classes
FEN Generation:
generate_fen: Converts the 8x8 board_matrix, which contains piece symbols, into a valid FEN string. It handles the compression of consecutive empty squares into numerical values as per FEN standards.
python
def generate_fen(board_matrix):
fen_rows = []
for row in board_matrix:
fen_row = ""
empty_count = 0
for cell in row:
if cell == '1': # Empty square
empty_count += 1
else:
if empty_count > 0:
fen_row += str(empty_count)
empty_count = 0
fen_row += cell
if empty_count > 0:
fen_row += str(empty_count)
fen_rows.append(fen_row)
fen = "/".join(fen_rows) + " w KQkq - 0 1" # Default values for active color, castling, en passant, etc.
return fen
Main Functionality:
main: Handles command-line arguments for specifying the image and model paths, loads the model, and initiates the image processing and FEN generation.
python
def main(image_file, model_path):
output_folder = "tiles" # Replace with your desired output folder
# Create output directory if it doesn't exist
os.makedirs(output_folder, exist_ok=True)
# Load the trained model
model = load_model(model_path)
print("Model loaded successfully.")
# Process the image, predict, and generate FEN
process_image_and_generate_fen(image_file, output_folder, model)
Command-Line Interface:
Utilizes Python's argparse module to allow users to specify the image path and model path when running the script.
python
if __name__ == "__main__":
import argparse
# Set up command-line argument parsing
parser = argparse.ArgumentParser(description='Process a chessboard image and generate FEN.')
parser.add_argument('image_path', type=str, help='Path to the chessboard image.')
parser.add_argument('model_path', type=str, help='Path to the trained CNN model file.')
args = parser.parse_args()
# Run the main function with provided arguments
main(args.image_path, args.model_path)
-
Halfmove Clock: Number of halfmoves since the last capture or pawn advance (for the fifty-move rule).
Fullmove Number: Starts at 1 and increments after black's move.
Example FEN:
code
rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1
This represents the initial position of a chess game.