Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find pixels with given RGB colors

Tags:

python

colors

I would like to get all coordinates from the pixels with a given RGB color in Python. Here is the code that I'm using but it doesn't work. I want to find all pixels with a yellow color.

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)

And how can you do it that Python only gives the coordinates if there are at least three pixels with the same color? (They mustn't be the exact same color, they can be for example 156,173,87 and 155,173,87.)

like image 781
AV13 Avatar asked Nov 08 '25 21:11

AV13


2 Answers

For speed reasons I would recommend using 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)))

This gives you a 2D-Array with the coordinates of the yellow pixels in your original image.

like image 175
Flomp Avatar answered Nov 10 '25 12:11

Flomp


You are using return in the loop, so you will always have max one pixel returned, you can store the pixels in a set in order to return all yellow pixels.

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

Edit: fix, open( to Image.open(

like image 29
Benoît Zu Avatar answered Nov 10 '25 10:11

Benoît Zu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!