-1

Ok so i have this script, it clicks only the pixels that have a certain shade of grey, it works fine for the most part except one thing, it loops too long and takes about like a second to go through each time how should i change my break to work better and stop it from looping all around after ive found one valid pixel?

xx = 0
while xx <= 600:
    with mss.mss() as sct:
        region = {'top': 0, 'left': 0, 'width': 1920, 'height': 1080}
        imgg = sct.grab(region)
        pxls = imgg.pixels

        for row, pxl in enumerate(pxls):
            for col, pxll in enumerate(pxl):
                if pxll == (102, 102, 102):
                    if col>=71 and col<=328 and row<=530 and row>=378:
                        foundpxl = pxll
                        print(str(col) +" , "+ str(row))
                        pyautogui.click(col,row)
                        break
        xx = xx + 1
        time.sleep(.05)
  • 4
    Put everything into a function and use `return`. – Klaus D. Feb 22 '19 at 01:49
  • 1
    Possible duplicate of [How to break out of multiple loops in Python?](https://stackoverflow.com/questions/189645/how-to-break-out-of-multiple-loops-in-python) – iz_ Feb 22 '19 at 01:51

2 Answers2

0

You can use the for-else construct to continue if no valid pixel is found (and therefore no break occurs) in the inner loop, or break the outer loop if one is found:

for row, pxl in enumerate(pxls):
    for col, pxll in enumerate(pxl):
        if pxll == (102, 102, 102) and col >= 71 and col <= 328 and row <= 530 and row >= 378:
            foundpxl = pxll
            print(str(col) + " , " + str(row))
            pyautogui.click(col, row)
            break
    else:
        continue
    break
blhsing
  • 91,368
  • 6
  • 71
  • 106
0

Disclaimer: I'm not familiar with mss. A few things you could improve:

  1. No need to enumerate the values you're not interested in. You could do:
for row, pxl in enumerate(pxls, start=378):
    if row > 530:
       break
    for col, pxll in enumerate(pxl, start=71):
        if col > 328:
           break
  1. Can't you just take the screenshot of the desired region instead? Something like this should work?
region = {'top': 378, 'left': 71, 'width': 328-71, 'height': 530-378}
  1. You're manipulating 2D arrays with double python loops. You could use some module designed to perform operations on arrays and can be orders of magnitude faster. Something like Pandas or NumPy should be able to run this almost instantly.
Keldorn
  • 1,980
  • 15
  • 25