Implement image similarity detection using PIL and Hamming distance
masterThe core automation logic relies on comparing real-time screenshots against baseline images.
- Capture: Use
ImageGrab.grab()to take a screenshot of a specific region relative to the game window. - Hash: Convert the captured image into a hash using a
get_hash()function. - Compare: Use the
hamming()function to calculate the Hamming distance between the current hash and a pre-saved baseline hash.
A lower Hamming distance indicates higher similarity. If the distance is below a certain threshold (e.g., 20 or 30), the script triggers a corresponding move_click() action.
# Example logic for detecting a button and clicking it
# 1. Load baseline
shiyong = Image.open("shiyong_jpg")
shiyong_hash = get_hash(shiyong)
# 2. In a loop, grab current screen area and compare
img_shiyong = ImageGrab.grab((topx + x1, topy + y1, topx + x2, topy + y2))
if hamming(get_hash(img_shiyong), shiyong_hash, 20):
move_click(target_x, target_y)
print("Clicked button")