Guest User

cv2_template_matching

a guest
Jun 30th, 2025
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.58 KB | Source Code | 0 0
  1. import cv2 as cv
  2. import numpy as np
  3. import os
  4. from matplotlib import pyplot as plt
  5.  
  6. # Paths and constants
  7. screenshot_path = 'images/breach_protocol_screenshot.png'
  8. HEX_IMAGES_PATH = "hexcodes"
  9. MATRIX = "/matrix/"
  10. SEQUENCE = "/sequence/"
  11.  
  12. VALID_HEX_VALUES = ["55", "1C", "BD", "E9", "7A", "FF"]
  13. threshold = 0.8  # adjust as needed
  14.  
  15. # Load screenshot in grayscale
  16. screenshot = cv.imread(screenshot_path, cv.IMREAD_GRAYSCALE)
  17. assert screenshot is not None, "Screenshot could not be loaded"
  18.  
  19. # Convert to BGR for visualization
  20. output_img = cv.cvtColor(screenshot, cv.COLOR_GRAY2BGR)
  21.  
  22. # Generate colors for visualization
  23. np.random.seed(42)
  24. colors = {code: tuple(int(c) for c in np.random.randint(0, 255, 3)) for code in VALID_HEX_VALUES}
  25.  
  26. def build_grid(positions, row_threshold=15):
  27.     """
  28.    Build a 2D grid (list of lists) from detected positions.
  29.    Positions format: [(x, y, code), ...]
  30.    Sorted top-to-bottom, left-to-right.
  31.    row_threshold defines max pixel difference to be in same row.
  32.    """
  33.     # Sort by y (top to bottom)
  34.     positions = sorted(positions, key=lambda p: p[1])
  35.  
  36.     rows = []
  37.     current_row = []
  38.     last_y = None
  39.  
  40.     # Group into rows based on y threshold
  41.     for pos in positions:
  42.         x, y, code = pos
  43.         if last_y is None or abs(y - last_y) <= row_threshold:
  44.             current_row.append(pos)
  45.         else:
  46.             # sort current row by x (left to right)
  47.             current_row.sort(key=lambda p: p[0])
  48.             rows.append(current_row)
  49.             current_row = [pos]
  50.         last_y = y
  51.     if current_row:
  52.         current_row.sort(key=lambda p: p[0])
  53.         rows.append(current_row)
  54.  
  55.     # Build the final grid of codes
  56.     grid = []
  57.     for row in rows:
  58.         codes_row = [code for (_, _, code) in row]
  59.         grid.append(codes_row)
  60.  
  61.     return grid
  62.  
  63. def detect_hex_codes(base_img, valid_codes, templates_folder, offset=10):
  64.     """
  65.    Detect hex codes in base_img using templates from templates_folder.
  66.    Returns list of (x, y, code) for detected positions.
  67.    """
  68.     found_positions = []
  69.     for hex_code in valid_codes:
  70.         template_path = os.path.join(templates_folder, f"{hex_code}.png")
  71.         template = cv.imread(template_path, cv.IMREAD_GRAYSCALE)
  72.         assert template is not None, f"Template {hex_code} could not be loaded from {template_path}"
  73.         w, h = template.shape[::-1]
  74.  
  75.         res = cv.matchTemplate(base_img, template, cv.TM_CCOEFF_NORMED)
  76.         loc = np.where(res >= threshold)
  77.  
  78.         for pt in zip(*loc[::-1]):
  79.             # filter out points too close to existing detections
  80.             if all(np.linalg.norm(np.array(pt) - np.array(pos[:2])) > offset for pos in found_positions):
  81.                 found_positions.append((pt[0], pt[1], hex_code))
  82.  
  83.     return found_positions
  84.  
  85. # --- Detect MATRIX hex codes ---
  86. found_positions_matrix = detect_hex_codes(screenshot, VALID_HEX_VALUES, HEX_IMAGES_PATH + MATRIX)
  87. print(f"Detected {len(found_positions_matrix)} hex codes in MATRIX area.")
  88.  
  89. # Draw MATRIX detections
  90. for x, y, code in found_positions_matrix:
  91.     template_path = os.path.join(HEX_IMAGES_PATH + MATRIX, f"{code}.png")
  92.     template = cv.imread(template_path, cv.IMREAD_GRAYSCALE)
  93.     w, h = template.shape[::-1]
  94.     cv.rectangle(output_img, (x, y), (x + w, y + h), colors[code], 2)
  95.     cv.putText(output_img, "M:" + code, (x, y - 5), cv.FONT_HERSHEY_SIMPLEX, 0.5, colors[code], 1, cv.LINE_AA)
  96.  
  97. matrix_grid = build_grid(found_positions_matrix)
  98. print("MATRIX GRID:")
  99. for row in matrix_grid:
  100.     print(row)
  101.  
  102. # --- Detect SEQUENCE hex codes ---
  103. found_positions_sequence = detect_hex_codes(screenshot, VALID_HEX_VALUES, HEX_IMAGES_PATH + SEQUENCE)
  104. print(f"Detected {len(found_positions_sequence)} hex codes in SEQUENCE area.")
  105.  
  106. # Draw SEQUENCE detections (different color - e.g. white)
  107. for x, y, code in found_positions_sequence:
  108.     template_path = os.path.join(HEX_IMAGES_PATH + SEQUENCE, f"{code}.png")
  109.     template = cv.imread(template_path, cv.IMREAD_GRAYSCALE)
  110.     w, h = template.shape[::-1]
  111.     # Use a fixed color for SEQUENCE (e.g., white)
  112.     cv.rectangle(output_img, (x, y), (x + w, y + h), (255, 255, 255), 2)
  113.     cv.putText(output_img, "S:" + code, (x, y - 5), cv.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1, cv.LINE_AA)
  114.  
  115. sequence_grid = build_grid(found_positions_sequence)
  116. print("SEQUENCE GRID:")
  117. for row in sequence_grid:
  118.     print(row)
  119.  
  120. # Show all detections
  121. plt.figure(figsize=(15, 10))
  122. plt.imshow(cv.cvtColor(output_img, cv.COLOR_BGR2RGB))
  123. plt.title("Detected Hex Codes: MATRIX (colors) & SEQUENCE (white)")
  124. plt.axis('off')
  125. plt.show()
  126.  
Advertisement
Add Comment
Please, Sign In to add comment