查找具有给定RGB颜色的像素

时间:2017-07-05 10:07:20

标签: python colors

我想从Python中获取具有给定RGB颜色的像素的所有坐标。这是我正在使用的代码,但它不起作用。我想找到所有黄色像素。

from PIL import Image
def find_rgb(imagename, r_query, g_query, b_query):
    img = Image.open(imagename)
    rgb = img.convert('RGB')
    for x in range(507):
        for y in range(337):
            r, g, b, = rgb.getpixel((x, y))
            if r >= r_query and g >= g_query and b <= b_query:
                return (x,y)

如果至少有三个具有相同颜色的像素,那么Python怎么能只提供坐标呢? (它们不能是完全相同的颜色,例如156,173,87和155,173,87。)

3 个答案:

答案 0 :(得分:2)

您在循环中使用return,因此您将始终返回最多一个像素,您可以将像素存储在set中,以便返回所有黄色像素。

def find_yellow_pixels(image_name):

    # Set the value you want for these variables
    r_min = 250
    r_max = 255
    g_min = 250
    g_max = 255
    b_min = 0
    b_max = 0

    yellow_pixels = set()

    img = Image.open(image_name)
    rgb = img.convert('rgb')
    for x in range(img.size[0]):
        for y in range(img.size[1]):
            r, g, b = rgb.getpixel((x, y))
            if r >= r_min and r <= r_max and b >= b_min and b <= b_max and g >= g_min and g <= g_max:
                yellow_pixels.add((x,y))

    return yellow_pixels

修改:修复,open(改为Image.open(

答案 1 :(得分:1)

出于速度原因,我建议使用numpy:

import numpy as np

width = 100
height = 100
channels = 3
img = np.random.rand(width, height, channels) * 255

r=0
g=1
b=2

r_query = 240
g_query = 240
b_query = 20
print(np.where((img[:,:,r] >= r_query) & (img[:,:,g] >= g_query) & (img[:,:,b] <= b_query)))

这为您提供了一个2D-Array,其原始图像中的黄色像素坐标为

答案 2 :(得分:0)

from PIL import Image
def find_rgb(imagename, r_query, g_query, b_query):
    img = Image.open(imagename)
    pix = img.load()
    coordinates= []
    for x in range(img.size[0]):
        for y in range(img.size[1]):
            r, g, b = pix[x,y]
            if matching_algo(r, g, b, r_query, g_query, b_query):
                # print("{},{} contains {}-{}-{} ".format(x, y, r, g, b))
                coordinates.append((x, y))
    return(coordinates)


def matching_algo(r, g, b, r_query, g_query, b_query):
    if r == r_query and g == g_query:
        return True
    elif r == r_query and b == b_query:
        return True
    elif b == b_query and g == g_query:
        return  True
    else:
        return False


if __name__== "__main__":
    find_rgb('dead_parrot.jpg', 255, 255, 0)

尝试一下,你可以改进我的匹配算法实现。 我删除了你的convert()代码并使用了load()而不是