1

I am trying to make an screen color detector so basically you tell it the values of the color of what you want to find. But the error i run into is IndexError: image index out of range

My Code:

from PIL import ImageGrab
from win32api import GetSystemMetrics
import numpy as np


def Color(R,G,B):

    px = ImageGrab.grab().load()
    
    x = GetSystemMetrics(0)
    y = GetSystemMetrics(1)  

    color = px[x, y]

    if color is R and G and B:
        print("Found The color you want!")
                
        
Color(25, 35, 45) #Telling it the RGB value of what i want to find

is there better way to do this?

1
  • 1
    I edited my answer to be more useful, in my opinion. Commented Sep 12, 2020 at 1:46

1 Answer 1

3

You are getting the error because x and y are essentially lengths in a zero-based system. At the very least you would want color = px[x-1, y-1] ... if you wanted to check the very last pixel on the screen.

Maybe you are trying to do something more like this?

from PIL import ImageGrab
from win32api import GetSystemMetrics
from dataclasses import dataclass

@dataclass
class Point:
    x :int
    y :int
    
    def __repr__(self):
        return f'x={self.x}, y={self.y}'


def ColorPositions(R,G,B):
    px   = ImageGrab.grab().load()
    x, y = GetSystemMetrics(0), GetSystemMetrics(1) 
    return [Point(n%x, n//x) for n in range(x*y) if px[n%x, n//x]==(R, G, B)]
        

positions = ColorPositions(99, 99, 99)
print(*positions[0:10], sep="\n")
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.