Certainly! Below is a complete Python script that accomplishes the following:
- Waits for the 'u' Key Press: Utilizes the
keyboard library to listen for the 'u' key press.
- Captures the Specified Region: Uses
mss to capture the defined grid area on the screen.
- Processes the Image with OCR:
- Converts the captured image to grayscale.
- Applies thresholding for better OCR accuracy.
- Uses
pytesseract to detect numbers within the region.
- Identifies Numbers and Their Locations:
- Extracts the text and their bounding box coordinates from the OCR results.
- Filters out non-numeric detections.
- Overlays Bright Red Boxes and Numbers:
- Draws red rectangles around detected numbers.
- Optionally, overlays the detected number in red at its position.
- Saves the Modified Image: Saves the final image with overlays to the disk.
Prerequisites:
Before running the script, ensure you have the following installed:
Complete Script:
import time
import mss
import pydirectinput
import keyboard
import pytesseract
import cv2
import numpy as np
from PIL import Image
import sys
from datetime import datetime
# Specify the path to the Tesseract executable if not in PATH
# Uncomment and set the correct path if necessary
# Example for Windows:
# pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
# Game Grid Coordinates (Update these coordinates based on your screen resolution and Minesweeper window position)
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 = 32 # Size of each tile in pixels
def capture_grid(mss_instance):
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 = mss_instance.grab(monitor)
img = Image.frombytes('RGB', sct_img.size, sct_img.rgb)
return img
def preprocess_image(pil_image):
# Convert to OpenCV image
cv_image = cv2.cvtColor(np.array(pil_image), cv2.COLOR_RGB2BGR)
# Convert to grayscale
gray = cv2.cvtColor(cv_image, cv2.COLOR_BGR2GRAY)
# Apply thresholding to make text more prominent
_, thresh = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY_INV)
return thresh, cv_image
def get_ocr_data(thresh_image):
# Configure tesseract to recognize only digits
custom_config = r'--oem 3 --psm 7 -c tessedit_char_whitelist=0123456789'
data = pytesseract.image_to_data(thresh_image, config=custom_config, output_type=pytesseract.Output.DICT)
return data
def draw_overlays(orig_image, data):
n_boxes = len(data['level'])
for i in range(n_boxes):
text = data['text'][i]
if text.strip() and text.strip().isdigit():
(x, y, w, h) = (data['left'][i], data['top'][i], data['width'][i], data['height'][i])
# Draw rectangle
cv2.rectangle(orig_image, (x, y), (x + w, y + h), (0, 0, 255), 2) # Red color in BGR
# Optionally, put the digit itself
cv2.putText(orig_image, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0,0,255), 2)
return orig_image
def save_image(image):
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"annotated_grid_{timestamp}.png"
cv2.imwrite(filename, image)
print(f"[INFO] Saved annotated image as {filename}")
def main():
print("[INFO] Waiting for 'u' key press to capture the grid...")
with mss.mss() as sct:
while True:
try:
if keyboard.is_pressed('u'):
print("[INFO] 'u' key pressed. Capturing the grid...")
pil_image = capture_grid(sct)
thresh, orig_cv = preprocess_image(pil_image)
ocr_data = get_ocr_data(thresh)
annotated_image = draw_overlays(orig_cv, ocr_data)
save_image(annotated_image)
print("[INFO] Waiting for the next 'u' key press...")
# Debounce to prevent multiple captures from a single press
while keyboard.is_pressed('u'):
time.sleep(0.1)
time.sleep(0.1)
except KeyboardInterrupt:
print("\n[INFO] Exiting program.")
sys.exit()
if __name__ == "__main__":
main()
Script Breakdown:
-
Configuration:
- GRID_TOP_LEFT & GRID_BOTTOM_RIGHT: Define the top-left and bottom-right coordinates of the Minesweeper grid on your screen. Adjust these based on your screen resolution and the game window's position.
- GRID_WIDTH & GRID_HEIGHT: Number of columns and rows in the grid.
- TILE_SIZE: Size of each tile in pixels. This can help in mapping bounding boxes to grid positions if needed.
-
Functions:
capture_grid: Captures the specified screen region using mss and returns it as a PIL image.
preprocess_image: Converts the image to grayscale and applies thresholding to enhance text detection.
get_ocr_data: Uses pytesseract to extract text data from the preprocessed image. It’s configured to recognize only digits to improve accuracy.
draw_overlays: Draws bright red rectangles around detected numbers and optionally overlays the number itself above the rectangle.
save_image: Saves the annotated image with a timestamped filename to avoid overwriting previous captures.
main: The main loop that waits for the 'u' key press and orchestrates the capture and processing.
-
Optimizations & Considerations:
- Debouncing Key Press: After detecting a 'u' key press, the script waits until the key is released to prevent multiple captures from a single press.
- OCR Configuration: The
custom_config restricts Tesseract to recognize only digits, which is useful for Minesweeper where tiles typically display numbers 1-8.
- Error Handling: The script gracefully exits on a keyboard interrupt (e.g., pressing
Ctrl+C).
-
Running the Script:
Example Output:
When you press the 'u' key, the script captures the defined grid area, detects all numbers, overlays red rectangles around them, and saves an image like annotated_grid_20231010_153045.png showing the grid with highlighted numbers.
Troubleshooting:
Feel free to modify and enhance the script based on your specific requirements, such as integrating it with other game automation tasks or improving the OCR accuracy with advanced image preprocessing techniques.