i have written the beginning of the cv detection code. use best practices in cv to do pattern matching to images i loaded there, 1.png 2.png and 3.png. they are images of digits, as names suggest. they are on the dark brown board, in grid. background is not always perfectly consistent, but the digits are. add the code to count ones twos and threes on the grid and output it. make it start counting when 'u' is pressed:
import time
import mss
import pydirectinput
import keyboard
import cv2
import numpy as np
from PIL import Image
from datetime import datetime
Configuration
GRID_TOP_LEFT = (798, 408) # (x, y)
GRID_BOTTOM_RIGHT = (1121, 731) # (x, y)
GRID_WIDTH = 10 # Number of columns
GRID_HEIGHT = 10 # Number of rows
TILE_SIZE = 36 # Size of each tile in pixels
Certainly! Below is the complete implementation of your CV digit detection and counting system. This code follows best practices for computer vision tasks, ensuring robust pattern matching despite inconsistent backgrounds. The program waits for the user to press the 'u' key, captures the specified screen region, processes the grid of digits, counts the occurrences of ones, twos, and threes, and then outputs the results.
Complete Code:
python
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 = (1121, 731) # (x, y) of the bottom-right corner of the grid
GRID_WIDTH = 10 # Number of columns in the grid
GRID_HEIGHT = 10 # Number of rows in the grid
TILE_SIZE = 36 # Size of each tile in pixels
# 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 or template_two is None or template_three is None:
raise FileNotFoundError("One or more template images (1.png, 2.png, 3.png) not found.")
# Preprocess templates: Apply Gaussian Blur and adaptive thresholding
def preprocess_template(template):
blurred = cv2.GaussianBlur(template, (5, 5), 0)
thresh = cv2.adaptiveThreshold(
blurred, 255,
cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY_INV,
11, 2
)
return thresh
template_one = preprocess_template(template_one)
template_two = preprocess_template(template_two)
template_three = preprocess_template(template_three)
# Initialize MSS for screen capturing
sct = mss.mss()
# Define the region of the screen to capture
monitor = {
"left": GRID_TOP_LEFT[0],
"top": GRID_TOP_LEFT[1],
"width": GRID_BOTTOM_RIGHT[0] - GRID_TOP_LEFT[0],
"height": GRID_BOTTOM_RIGHT[1] - GRID_TOP_LEFT[1]
}
# Preprocess captured image: grayscale, blur, and threshold
def preprocess_captured_image(image):
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
thresh = cv2.adaptiveThreshold(
blurred, 255,
cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY_INV,
11, 2
)
return thresh
# Extract a single tile from the grid based on row and column
def extract_tile(image, row, col):
x_start = col * TILE_SIZE
y_start = row * TILE_SIZE
tile = image[y_start:y_start + TILE_SIZE, x_start:x_start + TILE_SIZE]
return tile
# Identify digit in a tile by matching with templates
def identify_digit(tile, templates, threshold=0.7):
best_score = 0
best_digit = None
for digit, template in templates.items():
# Ensure the template and tile are the same size
if tile.shape != template.shape:
resized_template = cv2.resize(template, (tile.shape[1], tile.shape[0]))
else:
resized_template = template
result = cv2.matchTemplate(tile, resized_template, cv2.TM_CCOEFF_NORMED)
score = result[0][0]
if score > best_score:
best_score = score
best_digit = digit
if best_score >= threshold:
return best_digit
return None
# Count the digits in the captured grid
def count_digits(captured_image):
counts = {'1': 0, '2': 0, '3': 0}
processed_image = preprocess_captured_image(captured_image)
templates = {
'1': template_one,
'2': template_two,
'3': template_three
}
for row in range(GRID_HEIGHT):
for col in range(GRID_WIDTH):
tile = extract_tile(processed_image, row, col)
digit = identify_digit(tile, templates)
if digit:
counts[digit] += 1
return counts
# Main function to handle user input and counting
def main():
print("Digit Counting System Initialized.")
print("Press 'u' to start counting digits on the grid.")
try:
while True:
if keyboard.is_pressed('u'):
print(f"\n'u' pressed at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
# Capture the screen region
sct_img = sct.grab(monitor)
# Convert to NumPy array
img = np.array(sct_img)
# Convert from BGRA to BGR
img = cv2.cvtColor(img, cv2.COLOR_BGRA2BGR)
# Count the digits
start_time = time.time()
counts = count_digits(img)
end_time = time.time()
# Output the counts
print("Digit Counts:")
print(f"Ones : {counts['1']}")
print(f"Twos : {counts['2']}")
print(f"Threes : {counts['3']}")
print(f"Processing Time: {end_time - start_time:.2f} seconds")
# Wait until 'u' is released to avoid multiple triggers
while keyboard.is_pressed('u'):
time.sleep(0.1)
# Small delay to reduce CPU usage
time.sleep(0.1)
except KeyboardInterrupt:
print("\nExiting Digit Counting System.")
if __name__ == "__main__":
main()
Explanation of the Code:
Imports and Configuration:
Libraries:
mss: For efficient screen capturing.
keyboard: To detect key presses.
cv2 (OpenCV): For image processing and template matching.
numpy: For array manipulations.
datetime: For timestamping events.
Grid Configuration:
GRID_TOP_LEFT and GRID_BOTTOM_RIGHT define the area of the screen where the grid is located.
GRID_WIDTH and GRID_HEIGHT define the number of tiles horizontally and vertically.
TILE_SIZE specifies the pixel dimensions of each tile.
Template Loading and Preprocessing:
Templates (1.png, 2.png, 3.png) are loaded in grayscale to simplify processing.
The preprocess_template function applies Gaussian blur to reduce noise and adaptive thresholding to convert the image into a binary format, which enhances contrast between digits and the background.
Screen Capturing:
MSS Setup:
mss is initialized and configured to capture the specified grid region based on screen coordinates.
Preprocessing Captured Image:
The captured image is converted to grayscale.
Gaussian blur and adaptive thresholding are applied to prepare the image for template matching, ensuring consistency despite background variations.
Tile Extraction and Digit Identification:
extract_tile Function:
Splits the processed image into individual tiles based on the grid layout.
identify_digit Function:
Compares each tile against all templates using cv2.matchTemplate with the TM_CCOEFF_NORMED method, which normalizes correlation coefficients to handle varying lighting conditions.
The best matching digit is determined based on the highest correlation score, provided it exceeds a defined threshold (default is ). This helps avoid false positives.
Best Practices Implemented:
Robust Template Matching:
Preprocessing: Both templates and captured images undergo Gaussian blurring and adaptive thresholding to enhance feature detection and reduce the impact of noise and varying backgrounds.
Normalization: Using TM_CCOEFF_NORMED ensures that the matching process is less sensitive to lighting changes and contrast variations.
Efficient Screen Capture:
Utilizing mss for capturing only the necessary screen region minimizes resource usage and speeds up the capture process.
Responsive User Interaction:
The program listens for the 'u' key press to trigger the counting process, ensuring that counting occurs only when desired.
Preventing multiple triggers from a single key press avoids redundant processing and potential performance issues.
Error Handling:
The code checks if all templates are loaded correctly and raises an error if any template is missing, preventing runtime issues.
Graceful handling of keyboard interruptions allows the user to exit the program without abrupt termination.
Performance Monitoring:
Measuring and displaying the processing time helps in assessing the efficiency of the detection process and identifying potential bottlenecks.
Modular Design:
Functions like preprocess_template, preprocess_captured_image, extract_tile, and identify_digit encapsulate specific tasks, making the code modular, readable, and maintainable.
Potential Enhancements:
Dynamic Thresholding:
Implementing dynamic threshold adjustments based on real-time analysis of the captured image could improve matching accuracy in varying conditions.
Multi-Scale Matching:
If there's a chance that digits may appear in different sizes, incorporating multi-scale template matching would enhance detection robustness.
Machine Learning Integration:
For more complex or varied digit representations, integrating a machine learning model (e.g., a trained CNN) could improve recognition accuracy beyond template matching.
Visual Feedback:
Adding visual annotations (like drawing rectangles around detected digits) can help in debugging and provide real-time feedback to the user.
Logging:
Implementing a logging system to record detections over time can be useful for analysis and auditing purposes.
Conclusion
The provided code effectively captures a specified screen region, processes the image to detect and count digits using template matching, and outputs the results upon user input. It incorporates several best practices to ensure robustness, efficiency, and maintainability. Depending on the specific requirements and environment, further enhancements can be implemented to extend its capabilities.
Not yet included in a published release.
0.7
Counting Digits:
count_digits Function:
Iterates through each tile in the grid, identifies the digit using template matching, and updates the counts for ones, twos, and threes accordingly.
User Interaction and Execution Loop:
main Function:
Informs the user that the system is initialized and waits for the 'u' key press.
Upon detecting the 'u' key press, it captures the screen region, processes the image, counts the digits, and prints the results along with the processing time.
To prevent multiple detections from a single key press, the program waits until the 'u' key is released before resuming the listening loop.
The loop includes a small delay (time.sleep(0.1)) to reduce CPU usage.
Graceful Exit:
The program can be terminated gracefully using Ctrl+C, which triggers a KeyboardInterrupt and exits the loop.