Creating a system that records mouse click positions along with webcam images, trains a model to predict click positions based on webcam images, and displays predictions in real-time involves several steps. Below are three Python scripts that accomplish these tasks using pynput, opencv-python, and PyTorch.
Overview of the Three Scripts:
-
Data Collection Script (data_collector.py):
- Captures global mouse clicks.
- Captures webcam images when a click is detected.
- Saves images and corresponding click positions.
-
Model Training Script (train_model.py):
- Loads the collected data.
- Preprocesses images and positions.
- Defines and trains a convolutional neural network (CNN) using PyTorch.
- Saves the trained model.
-
Prediction Display Script (predict_display.py):
- Captures live webcam images.
- Uses the trained model to predict click positions.
- Displays the webcam feed with predicted click positions.
1. Data Collection Script (data_collector.py)
This script listens for global mouse clicks, captures the webcam image at the time of the click, and saves both the image and the click coordinates.
Dependencies:
pynput for capturing mouse events.
opencv-python (cv2) for webcam access.
os, csv, and time for file handling.
Installation:
pip install pynput opencv-python
Code:
# data_collector.py
import os
import csv
import time
from pynput import mouse
import cv2
import threading
# Directory to save data
DATA_DIR = "data"
IMAGES_DIR = os.path.join(DATA_DIR, "images")
CSV_FILE = os.path.join(DATA_DIR, "data.csv")
# Create directories if they don't exist
os.makedirs(IMAGES_DIR, exist_ok=True)
# Initialize CSV file with headers if it doesn't exist
if not os.path.isfile(CSV_FILE):
with open(CSV_FILE, mode='w', newline='') as file:
writer = csv.writer(file)
writer.writerow(["image_path", "x", "y"])
# Initialize webcam
cap = cv2.VideoCapture(0)
if not cap.isOpened():
print("Cannot open webcam")
exit()
# Lock for thread-safe operations
lock = threading.Lock()
def on_click(x, y, button, pressed):
if pressed:
# Capture the frame
ret, frame = cap.read()
if not ret:
print("Failed to grab frame")
return
timestamp = int(time.time() * 1000)
image_filename = f"img_{timestamp}.png"
image_path = os.path.join(IMAGES_DIR, image_filename)
# Save the image
cv2.imwrite(image_path, frame)
print(f"Saved {image_path} with click at ({x}, {y})")
# Save the coordinates
with lock:
with open(CSV_FILE, mode='a', newline='') as file:
writer = csv.writer(file)
writer.writerow([image_path, x, y])
def main():
print("Starting data collection. Press Ctrl+C to stop.")
# Start the mouse listener
with mouse.Listener(on_click=on_click) as listener:
listener.join()
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print("\nData collection stopped by user.")
finally:
cap.release()
Usage:
Run the script, then click anywhere on your screen. Each click will capture the current webcam frame and save the image along with the click coordinates.
python data_collector.py
2. Model Training Script (train_model.py)
This script loads the collected images and click coordinates, preprocesses the data, defines a CNN using PyTorch, trains the model, and saves the trained model for future predictions.
Dependencies:
torch, torchvision for deep learning.
opencv-python (cv2) for image processing.
pandas for data handling.
Pillow for image transformations.
Installation:
pip install torch torchvision opencv-python pandas pillow
Code:
# train_model.py
import os
import pandas as pd
import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
import cv2
from PIL import Image
from torchvision import transforms
import matplotlib.pyplot as plt
# Configuration
DATA_DIR = "data"
IMAGES_DIR = os.path.join(DATA_DIR, "images")
CSV_FILE = os.path.join(DATA_DIR, "data.csv")
MODEL_PATH = "eye_position_model.pth"
BATCH_SIZE = 32
EPOCHS = 20
LEARNING_RATE = 1e-3
IMAGE_SIZE = (224, 224) # Resize images
# Custom Dataset
class EyeDataset(Dataset):
def __init__(self, csv_file, transform=None):
self.data = pd.read_csv(csv_file)
self.transform = transform
def __len__(self):
return len(self.data)
def __getitem__(self, idx):
img_path = self.data.iloc[idx, 0]
x = self.data.iloc[idx, 1]
y = self.data.iloc[idx, 2]
# Load image
image = Image.open(img_path).convert("RGB")
if self.transform:
image = self.transform(image)
# Normalize coordinates to [0,1]
screen_width = 1920 # Adjust according to your screen resolution
screen_height = 1080
x_norm = x / screen_width
y_norm = y / screen_height
coords = torch.tensor([x_norm, y_norm], dtype=torch.float32)
return image, coords
# Define the CNN model
class EyePositionModel(nn.Module):
def __init__(self):
super(EyePositionModel, self).__init__()
self.features = nn.Sequential(
# Use a pre-trained model for better performance
# Here, we'll use a simple CNN
nn.Conv2d(3, 32, kernel_size=3, stride=1, padding=1), # [B, 32, 224, 224]
nn.ReLU(),
nn.MaxPool2d(2, 2), # [B, 32, 112, 112]
nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=1), # [B, 64, 112, 112]
nn.ReLU(),
nn.MaxPool2d(2, 2), # [B, 64, 56, 56]
nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=1), # [B, 128, 56, 56]
nn.ReLU(),
nn.MaxPool2d(2, 2), # [B, 128, 28, 28]
)
self.regressor = nn.Sequential(
nn.Linear(128 * 28 * 28, 512),
nn.ReLU(),
nn.Dropout(0.5),
nn.Linear(512, 2)
)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.regressor(x)
return x
def main():
# Transformations
transform = transforms.Compose([
transforms.Resize(IMAGE_SIZE),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], # Using ImageNet means
std=[0.229, 0.224, 0.225])
])
# Dataset and DataLoader
dataset = EyeDataset(CSV_FILE, transform=transform)
dataloader = DataLoader(dataset, batch_size=BATCH_SIZE, shuffle=True, num_workers=4)
# Initialize the model, loss function, and optimizer
model = EyePositionModel()
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)
criterion = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=LEARNING_RATE)
# Training loop
for epoch in range(1, EPOCHS + 1):
model.train()
running_loss = 0.0
for images, coords in dataloader:
images = images.to(device)
coords = coords.to(device)
optimizer.zero_grad()
outputs = model(images)
loss = criterion(outputs, coords)
loss.backward()
optimizer.step()
running_loss += loss.item() * images.size(0)
epoch_loss = running_loss / len(dataset)
print(f"Epoch {epoch}/{EPOCHS}, Loss: {epoch_loss:.4f}")
# Save the model
torch.save(model.state_dict(), MODEL_PATH)
print(f"Model saved to {MODEL_PATH}")
if __name__ == "__main__":
main()
Notes:
-
Screen Resolution: Adjust screen_width and screen_height in the EyeDataset class to match your screen resolution to normalize the click coordinates properly.
-
Model Architecture: For better performance, consider using a pre-trained model like ResNet or VGG from torchvision.models and fine-tuning it for your task.
-
Data Augmentation: To improve model robustness, you can add data augmentation techniques in the transforms pipeline.
Usage:
Ensure that you have collected sufficient data using data_collector.py before training the model.
python train_model.py
After training, the model will be saved as eye_position_model.pth.
3. Prediction Display Script (predict_display.py)
This script captures live webcam images, uses the trained model to predict click positions, and displays the webcam feed with the predicted positions overlaid.
Dependencies:
torch, torchvision for loading and using the model.
opencv-python (cv2) for webcam access and display.
PIL for image transformations.
numpy for array manipulations.
Installation:
pip install torch torchvision opencv-python pillow numpy
Code:
# predict_display.py
import cv2
import torch
from torchvision import transforms
from PIL import Image
import numpy as np
# Configuration
MODEL_PATH = "eye_position_model.pth"
IMAGE_SIZE = (224, 224)
SCREEN_WIDTH = 1920 # Adjust according to your screen resolution
SCREEN_HEIGHT = 1080
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Load the model
class EyePositionModel(nn.Module):
def __init__(self):
super(EyePositionModel, self).__init__()
self.features = nn.Sequential(
nn.Conv2d(3, 32, kernel_size=3, stride=1, padding=1), # [B, 32, 224, 224]
nn.ReLU(),
nn.MaxPool2d(2, 2), # [B, 32, 112, 112]
nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=1), # [B, 64, 112, 112]
nn.ReLU(),
nn.MaxPool2d(2, 2), # [B, 64, 56, 56]
nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=1), # [B, 128, 56, 56]
nn.ReLU(),
nn.MaxPool2d(2, 2), # [B, 128, 28, 28]
)
self.regressor = nn.Sequential(
nn.Linear(128 * 28 * 28, 512),
nn.ReLU(),
nn.Dropout(0.5),
nn.Linear(512, 2)
)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.regressor(x)
return x
model = EyePositionModel()
model.load_state_dict(torch.load(MODEL_PATH, map_location=DEVICE))
model.to(DEVICE)
model.eval()
print("Model loaded.")
# Transformations
transform = transforms.Compose([
transforms.Resize(IMAGE_SIZE),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], # Must match training
std=[0.229, 0.224, 0.225])
])
# Initialize webcam
cap = cv2.VideoCapture(0)
if not cap.isOpened():
print("Cannot open webcam")
exit()
# Function to map normalized coordinates to screen coordinates
def map_coords(x_norm, y_norm):
x = int(x_norm * SCREEN_WIDTH)
y = int(y_norm * SCREEN_HEIGHT)
return x, y
try:
while True:
ret, frame = cap.read()
if not ret:
print("Failed to grab frame")
break
# Convert frame to PIL Image
img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
pil_img = Image.fromarray(img)
# Apply transformations
input_tensor = transform(pil_img).unsqueeze(0).to(DEVICE)
# Predict
with torch.no_grad():
output = model(input_tensor)
x_norm, y_norm = output[0].cpu().numpy()
# Map to screen coordinates
pred_x, pred_y = map_coords(x_norm, y_norm)
# Overlay the prediction on the frame
# Here, we map the prediction to the display window instead of actual screen
# To visualize relative to the webcam frame
frame_height, frame_width, _ = frame.shape
display_x = int(x_norm * frame_width)
display_y = int(y_norm * frame_height)
cv2.circle(frame, (display_x, display_y), 10, (0, 255, 0), -1)
cv2.putText(frame, f"Pred: ({pred_x}, {pred_y})", (display_x + 15, display_y),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)
# Display the frame
cv2.imshow("Eye Position Prediction", frame)
# Break the loop on 'q' key press
if cv2.waitKey(1) & 0xFF == ord('q'):
break
except KeyboardInterrupt:
print("\nPrediction stopped by user.")
finally:
cap.release()
cv2.destroyAllWindows()
Notes:
-
Screen Coordinates vs Webcam Frame Coordinates:
- The model predicts normalized coordinates
[0,1] which are then mapped to screen coordinates based on your screen resolution.
- However, since displaying predictions on the actual screen requires more advanced GUI handling, in this script, predictions are overlaid on the webcam frame itself for visualization purposes. You can adjust the
map_coords function to handle actual screen overlay if needed.
-
Model Architecture Consistency:
- Ensure that the
EyePositionModel class in this script matches exactly with the one used during training.
-
Performance Optimization:
- For real-time predictions, ensure that the model and transformations are optimized for speed. Consider using a lighter model if necessary.
Usage:
Run the script to start the webcam and see real-time predictions of where you are looking.
python predict_display.py
Press q to exit the prediction display.
Final Remarks
This system provides a basic framework for capturing eye positions based on webcam images and predicting them using a neural network. Here are some suggestions to enhance the system:
-
Data Quality:
- Ensure that the collected data is diverse and covers various angles, lighting conditions, and screen areas to improve model generalization.
-
Model Improvements:
- Utilize pre-trained models like ResNet, EfficientNet, or MobileNet for better feature extraction.
- Implement more sophisticated techniques like attention mechanisms or gaze estimation algorithms.
-
Real-Time Performance:
- Optimize the prediction script for faster inference (e.g., using NVIDIA TensorRT if available).
- Reduce the image size or model complexity for real-time applications.
-
User Interface:
- Develop a more interactive UI that can display predictions on the actual screen or integrate with other applications.
-
Calibration:
- Implement a calibration step to adjust predictions based on individual user differences.
-
Privacy Considerations:
- Handle webcam data securely and ensure user privacy, especially if collecting and storing sensitive information.
Feel free to further customize and expand these scripts to suit your specific requirements.