pyautogui pixel color scanner, works manually but doesn't with automation

23 views Asked by At

Im trying to create a simple pixel scanner from move a mouse from one location downwards untill it hits a specific color. I can simply do this manually and it works perfectly, but as soon as I implement automation to it it fails to do it.

Python Version

Python 3.11.5
import pyautogui

while True:
  try:
    # Start positon of the mouse              <---- Automation
    pyautogui.moveTo(899,50)

    # Gets the positon
    position = pyautogui.position()

    # Gets the color of pixel
    color_matching = pyautogui.pixel(position.x,position.y)

    # Prints the pixel in format (255,255,255)
    print(color_matching)

    # - Green -
    #If the color matches prints "Found Green!"
    if color_matching == (86,183,39):
      print("Found Green!")
      break

    # - Red -
    #If the color matches prints "Found Red!"
    if color_matching == (244,59,13):
      print("Found Red!")
      break

    # End positon of the mouse              <---- Automation
    pyautogui.moveTo(899,1000,5)

  except:
    break

Without the automation I can get it to work, by just running the mouse of the designated color of my choosing.

With the automation it only captures the first pixel when moving to this code:

pyautogui.moveTo(899,50)

Without it if I just add a print to the color_matching it will constantly update, but with it... It will as mentioned before just print out once.

So, how can I make this to work? I also want it to run quickly, but first I just want it to work.

1

There are 1 answers

0
Artb On

I think you can solve the problem with threading. Here is the code:

import pyautogui
import threading

# Variable to control the scanning state
scanning = False

def startScan():
    global scanning
    scanning = True
    pyautogui.moveTo(899, 1000, 5)  # Move the mouse to a specific position
    scanning = False

while True:
    try:
        if not scanning:  # If scanning is completed, start again
            pyautogui.moveTo(899, 50)  # Start position of the mouse (Automation)
            
            # Start a new thread for moving the mouse
            threading.Thread(target=startScan, daemon=True).start()
    
        # Get the mouse position
        position = pyautogui.position()
    
        # Get the color of the pixel
        color_matching = pyautogui.pixel(position.x, position.y)
    
        # Print the pixel color in the format (255, 255, 255)
        print(color_matching)
    
        # Green
        # If the color matches, print "Found Green!" and exit the loop
        if color_matching == (86, 183, 39):
            print("Found Green!")
            break
    
        # Red
        # If the color matches, print "Found Red!" and exit the loop
        elif color_matching == (244, 59, 13):
            print("Found Red!")
            break
        
    except:
        break