Reputation: 199
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.
Upvotes: 1
Views: 7967
Reputation: 16197
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))
Upvotes: 1
Reputation: 207365
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
Upvotes: 0