1
votes

Example with a black pixel in the middle

What's the fastest way to find x and y coordinates of a pixel with a given rgb value? In this example the black pixel is at 100x100. Should I use openCV or Image? Does anyone have an idea or an example for me?

#!/usr/bin/env python
# coding: utf-8

import Image

img = Image.open('splash.png')
rgb = img.convert('RGB')
r, g, b = rgb.getpixel((100, 100))

print r, g, b
#for pixel in rgb.getdata():
#    print pixel
>>>0 0 0

As you can see I need the opposite way.

2
note that you could create some kind of hash-table RGB-Value-to-Pixelosition of an image, that allows you to access the desired pixels very fast, but needs some time to compute. This will be nice if you will search again and again for single RGB values of the same image for different "inputs".Micka

2 Answers

1
votes

The only way to do this is to iterate through the complete image and stop when you found one pixel that matches your search. If you have to do it very often, for many different images, you can put them into a dictionary for faster access.

import Image

def find_rgb(imagename, r_query, g_query, b_query):
    img = Image.open(imagename)
    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_query and g == g_query and b == b_query:
               return (x,y)

print(find_rgb('splash.png', 0, 0, 0))
0
votes

Not sure whether you mean "short run time" or "quickest command to type". If you mean the latter, this took around 4 seconds to type using ImageMagick's convert command:

convert B7cjD.png txt: | grep "#000000"
100,100: (0,0,0,1)  #000000  black