简体   繁体   中英

How to find a pixel position with a given value

中间有黑色像素的示例

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.

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))

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM