Python / PyGame:通过colorcode查找像素

时间:2015-05-14 15:54:04

标签: python colors find pygame pixel

有没有办法按颜色找到像素(在表面/图像内)? 像:

img = python.image.load("image.gif").convert()
img.find((255, 255, 255)) >> (50, 100) = white pixel

如果你不知道我的意思,请随时问。 谢谢!

1 个答案:

答案 0 :(得分:1)

def findPixel(img, r, g, b):
    for x in range(0, img.get_width()):
        for y in range(0, img.get_height()):
            pixel = img.get_at((x, y))
            if pixel[0] >= r and pixel[1] >= g and pixel[2] >= b:
                return pixel
    return None

这是我头脑中写的。传入你的图像对象应该说出来。如果不是,则必须输入image.surface对象引用。但迭代X和Y的想法应该在理论上有效。

Pygame主机没有这样的功能,但它确实为你提供了获取或迭代像素位置的能力。

有一种更快的方法,那就是在循环之前存储整个图像数组并迭代该数组,而不是调用我认为的get_at函数,但是这些天我不使用Pygame所以我无法测试两种实现的优化差异,因此我将其留在此处并将优化留给您。

如果您有兴趣找到与您的参数相对应的所有颜色值(感谢SuperBiasedMan):

def findPixel(img, r, g, b):
    found = []
    for x in range(0, img.width):
        for y in range(0, img.height):
            pixel = img.get_at((x, y))
            if pixel[0] >= r and pixel[1] >= g and pixel[2] >= b:
                found.append((x, y))
    return found

请注意,这会慢一些,但您会在一次迭代中找到所有像素。