查找具有给定RGB颜色的像素 [英] Find pixels with given RGB colors

查看:83
本文介绍了查找具有给定RGB颜色的像素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

如果只有至少三个具有相同颜色的像素,Python如何给出坐标呢? (它们的颜色不能完全相同,例如可以是156,173,87和155,173,87。)

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

推荐答案

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

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.

这篇关于查找具有给定RGB颜色的像素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆