首页 > 解决方案 > IndexError:图像索引超出范围?

问题描述

我正在尝试制作一个屏幕颜色检测器,所以基本上你告诉它你想要找到的颜色的值。但我遇到的错误是IndexError: image index out of range

我的代码:

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

有更好的方法吗?

标签: pythonnumpywinapipython-imaging-library

解决方案


您收到错误是因为x并且y本质上是从零开始的系统中的长度。至少你会想要color = px[x-1, y-1]......如果你想检查屏幕上的最后一个像素。

也许您正在尝试做更多类似的事情?

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")

推荐阅读