Script that is supposed to find a certain color object isn't working?

Question:

I’ve returned to python after a long time. I tried to make code to detect if a certain color (light purple) is detected on the entire screen. I wanted it to be a range since the purple object is a 3d object and has some shading. It is not detected the object. I was wondering if you could help.

from PIL import ImageGrab

#230-260
#0-2
#200-220

px = ImageGrab.grab().load()
for y in range(0, 1080, 1):
    var = True
    r = 230
    g = 0
    b = 200
    for x in range(0, 1920, 1):
        color = px[x, y]
        while var == True:
            if color == (r,g,b):
                print("Found")
                break
            elif r != 260:
                r += 1
            elif g != 2:
                g += 1
            elif b != 220:
                b += 1
            else:
                var = False    
            print(r, g, b)    

print("Done")
Asked By: sam dalian

||

Answers:

The problem is with the way you’re cycling through the color possibilities.
Thinking through how this program would execute, the colors would be tried in the following order:

(230, 0, 200),
(231, 0, 200),
.
.
.
(260, 0, 200)

Then, now that your first elif won’t trigger anymore, it will search these:

(260, 1, 200),
(260, 2, 200)

Finally, it will start increasing the blues in the third elif.

(260, 2, 201),
(260, 2, 202),
.
.
.
(260, 2, 220)

Obvious this is leaving a whole lot of values unchecked. If you want to try every combination of RGB values in the ranges you provided, I would recommend doing something like this:

for y in range(1080):
    for x in range(1920):
        color = px[x, y]
        for r in range(230, 261):
            for g in range(0, 3):
                for b in range(200, 221):
                    if color == (r, g, b):
                        print("Found")

Point of note, the break statement you had wouldn’t work the same in this case as it does in yours, since there are more nested for loops. It might be worth wrapping all of this into a function and using return to avoid all the unnecessary iterations.

Answered By: GotCubes
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.