Certainly! To modify your existing code to handle both grayscale digit recognition and color-based identification of brown cells, follow these steps:
-
Capture the Colored Image Alongside Grayscale:
Modify the capture_grid function to return both the color and grayscale images. This allows you to perform separate processing for digit recognition and brown cell detection.
-
Add a Function to Identify Brown Cells:
Create a new function, identify_brown, which uses color thresholding to detect brown cells based on the provided RGB ranges.
-
Integrate Both Identifications into Grid Processing:
When processing each cell in the grid, first check if it's a brown cell. If it is, mark it accordingly. If not, proceed to identify the digit using your existing identify_digit function.
Below is the modified and extended code incorporating these changes:
import cv2
import numpy as np
import mss
# Define your grid boundaries
GRID_TOP_LEFT = (x1, y1) # Replace with actual values
GRID_BOTTOM_RIGHT = (x2, y2) # Replace with actual values
# Define brown color range in BGR format (since OpenCV uses BGR)
BROWN_LOWER = np.array([39, 54, 73]) # Converted from RGB to BGR
BROWN_UPPER = np.array([43, 62, 81])
# Define template matching parameters
MATCH_METHOD = cv2.TM_CCOEFF_NORMED
MATCH_THRESHOLD = 0.8 # Adjust based on your requirements
# Load or define your digit templates
templates = {
'0': cv2.imread('templates/0.png', cv2.IMREAD_GRAYSCALE),
'1': cv2.imread('templates/1.png', cv2.IMREAD_GRAYSCALE),
# Add templates for digits 2-9
# ...
}
def capture_grid():
"""Captures the grid area of the screen and returns both color and grayscale images."""
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_color = np.array(sct_img)
img_color = cv2.cvtColor(img_color, cv2.COLOR_BGRA2BGR)
img_gray = cv2.cvtColor(img_color, cv2.COLOR_BGR2GRAY)
# Optional: Apply Gaussian Blur to reduce noise
img_gray = cv2.GaussianBlur(img_gray, (3, 3), 0)
return img_color, img_gray
def identify_brown(cell_color):
"""
Identifies if a cell is brown based on color thresholding.
Args:
cell_color (numpy.ndarray): The BGR image of the cell.
Returns:
bool: True if the cell is brown, False otherwise.
"""
# Create a mask for brown color
mask = cv2.inRange(cell_color, BROWN_LOWER, BROWN_UPPER)
# You can adjust the threshold percentage based on your grid cell coverage
brown_pixels = cv2.countNonZero(mask)
total_pixels = cell_color.shape[0] * cell_color.shape[1]
# If more than a certain percentage of the cell is brown, consider it as brown
return brown_pixels / total_pixels > 0.5 # Adjust threshold as needed
def identify_digit(cell_gray):
"""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_gray, 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 split_into_cells(img_color, img_gray, rows, cols):
"""
Splits the grid image into individual cells.
Args:
img_color (numpy.ndarray): The BGR color image of the grid.
img_gray (numpy.ndarray): The grayscale image of the grid.
rows (int): Number of rows in the grid.
cols (int): Number of columns in the grid.
Returns:
list of tuples: Each tuple contains (cell_color, cell_gray).
"""
cell_height = img_color.shape[0] // rows
cell_width = img_color.shape[1] // cols
cells = []
for r in range(rows):
for c in range(cols):
y_start = r * cell_height
y_end = (r + 1) * cell_height
x_start = c * cell_width
x_end = (c + 1) * cell_width
cell_color = img_color[y_start:y_end, x_start:x_end]
cell_gray = img_gray[y_start:y_end, x_start:x_end]
cells.append((cell_color, cell_gray))
return cells
def process_grid(rows, cols):
"""
Processes the entire grid to identify digits and brown cells.
Args:
rows (int): Number of rows in the grid.
cols (int): Number of columns in the grid.
Returns:
list of list: A 2D list representing the grid, where each cell contains
either a digit (as a string) or 'brown'.
"""
img_color, img_gray = capture_grid()
cells = split_into_cells(img_color, img_gray, rows, cols)
grid = []
for r in range(rows):
row = []
for c in range(cols):
idx = r * cols + c
cell_color, cell_gray = cells[idx]
if identify_brown(cell_color):
row.append('brown')
else:
digit = identify_digit(cell_gray)
if digit is not None:
row.append(digit)
else:
row.append(None) # Empty cell or unrecognized
grid.append(row)
return grid
# Example usage:
if __name__ == "__main__":
ROWS = 9 # Replace with actual number of rows
COLS = 9 # Replace with actual number of columns
grid = process_grid(ROWS, COLS)
for row in grid:
print(row)
Explanation of the Modifications:
-
Color Conversion Adjustment:
- Brown Color Range: OpenCV uses BGR format by default. Make sure to convert your RGB bounds to BGR as shown:
BROWN_LOWER = np.array([39, 54, 73]) # BGR equivalent of [73, 54, 39]
BROWN_UPPER = np.array([43, 62, 81]) # BGR equivalent of [81, 62, 43]
- This ensures that the color thresholding correctly identifies brown cells.
-
Capturing Both Color and Grayscale Images:
- The
capture_grid function now returns both img_color and img_gray.
- This allows you to perform color-based processing alongside grayscale-based digit recognition.
-
Identifying Brown Cells:
- The
identify_brown function creates a mask that highlights pixels within the brown range.
- It then calculates the ratio of brown pixels to the total number of pixels in the cell.
- If the ratio exceeds a certain threshold (e.g., 50%), the cell is marked as brown. Adjust this threshold based on your grid's characteristics.
-
Splitting the Grid into Cells:
- The
split_into_cells function divides the captured images into individual cells based on the specified number of rows and columns.
- Adjust the
rows and cols parameters to match your grid's structure.
-
Processing Each Cell:
- In the
process_grid function, each cell is first checked for the brown color.
- If a cell is identified as brown, it's marked as
'brown'.
- If not, the
identify_digit function attempts to recognize any digit present.
- If no digit is confidently recognized, the cell is marked as
None.
-
Example Usage:
- Replace
ROWS and COLS with the actual number of rows and columns in your grid.
- The example prints out the identified grid, displaying digits,
'brown', or None for each cell.
Additional Considerations:
-
Template Matching Accuracy:
- Ensure that your digit templates are clear and match the size of the digits on the grid.
- Preprocess templates (e.g., resizing, thresholding) if necessary to improve matching accuracy.
-
Color Lighting Conditions:
- Depending on screen lighting and color variations, you might need to adjust the
BROWN_LOWER and BROWN_UPPER values.
- You can use tools like color pickers or calibration scripts to determine the optimal color ranges.
-
Performance Optimization:
- If processing speed becomes an issue, consider resizing the grid image or optimizing the template matching process.
- Utilize multi-threading or parallel processing for handling multiple cells simultaneously.
-
Handling Overlapping Features:
- If some cells could contain both a brown background and a digit, prioritize digit recognition after confirming the cell is not predominantly brown.
- Adjust the identification logic based on the specific behavior of your grid.
By integrating both color-based and grayscale-based processing, this approach ensures that your application can accurately identify both brown cells and digits within the same grid.