Certainly! Below is a complete Python script that integrates with your existing configuration. This script captures the specified grid area when the 'u' key is pressed, processes the image to identify the digits 1, 2, and 3 using template matching, handles imperfect matches and noise, counts the total occurrences of each digit, and prints the results.
Complete Script
import time
import mss
import keyboard
import cv2
import numpy as np
from datetime import datetime
# Configuration
GRID_TOP_LEFT = (798, 408) # (x, y) of the top-left corner of the grid
GRID_BOTTOM_RIGHT = (1122, 732) # (x, y) of the bottom-right corner of the grid
GRID_WIDTH = 9 # Number of columns in the grid
GRID_HEIGHT = 9 # Number of rows in the grid
# Load templates for "one", "two", and "three"
# Convert templates to grayscale for easier matching
template_one = cv2.imread('1.png', cv2.IMREAD_GRAYSCALE)
template_two = cv2.imread('2.png', cv2.IMREAD_GRAYSCALE)
template_three = cv2.imread('3.png', cv2.IMREAD_GRAYSCALE)
# Check if templates are loaded correctly
if template_one is None:
raise IOError("Template image '1.png' not found or cannot be opened.")
if template_two is None:
raise IOError("Template image '2.png' not found or cannot be opened.")
if template_three is None:
raise IOError("Template image '3.png' not found or cannot be opened.")
templates = {
'1': template_one,
'2': template_two,
'3': template_three
}
# Parameters for template matching
MATCH_METHOD = cv2.TM_CCOEFF_NORMED
MATCH_THRESHOLD = 0.7 # Adjust based on testing for optimal results
def capture_grid():
"""Captures the grid area of the screen."""
with mss.mss() as sct:
monitor = {
"top": GRID_TOP_LEFT[1],
"left": GRID_TOP_LEFT[0],
"width": GRID_BOTTOM_RIGHT[0] - GRID_TOP_LEFT[0],
"height": GRID_BOTTOM_RIGHT[1] - GRID_TOP_LEFT[1]
}
sct_img = sct.grab(monitor)
img = np.array(sct_img)
img = cv2.cvtColor(img, cv2.COLOR_BGRA2BGR)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Optional: Apply Gaussian Blur to reduce noise
gray = cv2.GaussianBlur(gray, (3, 3), 0)
return gray
def divide_grid(image):
"""Divides the grid image into individual cells."""
cell_width = (GRID_BOTTOM_RIGHT[0] - GRID_TOP_LEFT[0]) / GRID_WIDTH
cell_height = (GRID_BOTTOM_RIGHT[1] - GRID_TOP_LEFT[1]) / GRID_HEIGHT
cells = []
for row in range(GRID_HEIGHT):
for col in range(GRID_WIDTH):
x_start = int(col * cell_width)
y_start = int(row * cell_height)
x_end = int((col + 1) * cell_width)
y_end = int((row + 1) * cell_height)
cell = image[y_start:y_end, x_start:x_end]
cells.append(cell)
return cells
def identify_digit(cell):
"""Identifies the digit in a single cell using template matching."""
best_match = None
best_score = -1
for digit, template in templates.items():
# Resize template if necessary to match cell size
# Assuming templates are similar in size to cells; adjust if necessary
res = cv2.matchTemplate(cell, template, MATCH_METHOD)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
if max_val > best_score:
best_score = max_val
best_match = digit
if best_score >= MATCH_THRESHOLD:
return best_match
else:
return None # No confident match found
def process_grid(image):
"""Processes the entire grid image and counts the digits."""
cells = divide_grid(image)
counts = {'1': 0, '2': 0, '3': 0}
for idx, cell in enumerate(cells):
digit = identify_digit(cell)
if digit:
counts[digit] += 1
return counts
def print_totals(counts):
"""Prints the total counts of each digit."""
total_ones = counts.get('1', 0)
total_twos = counts.get('2', 0)
total_threes = counts.get('3', 0)
print(f"Totals at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}:")
print(f"Ones: {total_ones}, Twos: {total_twos}, Threes: {total_threes}")
print("-" * 40)
def main():
print("Press 'u' to scan the grid and count digits (1, 2, 3). Press 'ESC' to exit.")
try:
while True:
if keyboard.is_pressed('u'):
print("Scanning grid...")
gray_image = capture_grid()
counts = process_grid(gray_image)
print_totals(counts)
# Debounce to prevent multiple scans on a single press
while keyboard.is_pressed('u'):
time.sleep(0.1)
elif keyboard.is_pressed('esc'):
print("Exiting program.")
break
time.sleep(0.1) # Reduce CPU usage
except KeyboardInterrupt:
print("\nProgram interrupted and exiting.")
if __name__ == "__main__":
main()
Explanation of the Script
-
Imports and Configuration:
- Libraries: The script uses
mss for screen capturing, keyboard for keypress detection, cv2 (OpenCV) for image processing, and numpy for numerical operations.
- Grid Configuration: Defined by the top-left and bottom-right coordinates, along with the number of rows and columns (
GRID_WIDTH and GRID_HEIGHT).
-
Template Loading:
- The templates for digits
1, 2, and 3 are loaded in grayscale. The script checks if the templates are loaded correctly and raises an error if any are missing.
-
Template Matching Parameters:
MATCH_METHOD: Uses cv2.TM_CCOEFF_NORMED which is suitable for normalized cross-correlation.
MATCH_THRESHOLD: A threshold value to determine whether a match is considered valid. You might need to adjust this based on your specific templates and grid images.
-
Function Definitions:
capture_grid(): Captures the specified grid area from the screen. It converts the captured image to grayscale and applies Gaussian Blur to reduce noise, which can improve template matching accuracy.
divide_grid(image): Divides the captured grid image into individual cells based on the grid's configuration. It calculates the width and height of each cell and extracts them.
identify_digit(cell): Identifies the digit in a single cell by performing template matching with each of the loaded templates. It selects the digit with the highest matching score above the defined threshold.
process_grid(image): Processes all cells in the grid, identifies digits, and counts their occurrences.
print_totals(counts): Prints the total counts of each digit along with a timestamp for reference.
-
Main Loop:
- The
main() function sets up an infinite loop that listens for keypresses.
- Activation: When the
'u' key is pressed, it triggers the scanning process:
Additional Recommendations
-
Adjusting MATCH_THRESHOLD:
- The threshold for template matching might need fine-tuning based on the quality of your grid images and templates. Start with
0.7 and adjust higher or lower as needed.
-
Template and Cell Size Matching:
- Ensure that the templates (
1.png, 2.png, 3.png) are scaled similarly to the digits in the grid. If there’s a size mismatch, consider resizing the templates or cells accordingly.
-
Handling Different Lighting Conditions:
- If the grid images have varying lighting conditions, applying adaptive thresholding or histogram equalization might improve matching accuracy.
- For example, you can add:
gray = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY, 11, 2)
in the capture_grid() function after converting to grayscale.
-
Optimizing Performance:
- For larger grids or higher resolutions, processing might take longer. Consider optimizing by processing only regions of interest or using more efficient algorithms if necessary.
-
Error Handling:
- The script currently raises an error if templates are not found. You might want to handle these cases more gracefully depending on your use case.
-
Logging:
- For long-term usage, consider logging the counts to a file instead of just printing to the console.
Final Notes
Ensure that the template images (1.png, 2.png, 3.png) are placed in the same directory as the script or provide the correct path to these images. The script assumes that these templates closely match the digits displayed in the grid. If the grid's digits vary in font or style, you may need to generate new templates that accurately represent them.
Feel free to customize and expand upon this script based on your specific requirements and the characteristics of your grid and digits.