简体   繁体   English

如何检查 RGB colors 列表中的所有项目是否在没有循环的图像中?

[英]How to check if all items in list of RGB colors is in an image without a loop?

Say I have a list of RGB values as follows:假设我有一个 RGB 值列表,如下所示:

rgbL = [[20 45 40] [30 45 60] .... [70 50 100]]

Then, I have an image say, img = cv.imread("location")然后,我有一张图片说, img = cv.imread("location")

Now, I want to change ALL RGB values of an image into (255, 0, 0) if the image RGB value is IN my list of RGB values (rgbL).现在,如果图像 RGB 值在我的 RGB 值列表 (rgbL) 中,我想将图像的所有 RGB 值更改为 (255, 0, 0)。

I was able to do this by this code:我能够通过这段代码做到这一点:

for rgb in rgbL :

    k = list(filter(None, rgb[1:-1].split(" ")))
    r = int(k[0])
    g = int(k[1])
    b = int(k[2])

    img[np.all(img == (r, g, b), axis=-1)] = (255,0,0)  

But the code above is taking too long because my "rgbL" list is too long.但是上面的代码花费的时间太长,因为我的“rgbL”列表太长了。

Is there a way that I can do this without a loop?有没有办法不用循环就可以做到这一点? What is the best way to implement it in numpyish way?以 numpyish 方式实现它的最佳方法是什么?

convert your rgbL and img into numpy arrays. one way of doing it without loop:将您的rgbLimg转换为 numpy arrays。一种无需循环的方法:

sh = img.shape
img = img.reshape(-1, 3)
img[np.where(((rgbL[:,None,:]-img)==0).all(axis=2))[1]]=np.array([255,0,0])
img = img.reshape(sh)

which takes a difference of your image with every row of rgbL and checks for all zero difference in RGBs to replace using np.where .这需要你的图像与rgbL的每一行的差异,并检查 RGB 中的all零差异以使用np.where替换。

sample img and output:示例img和 output:

img:
[[ 20  45  40]
 [ 30  45  60]
 [  0   1   2]
 [ 70  50 100]
 [  4   5   6]]
rgbL:
[[ 20  45  40]
 [ 30  45  60]
 [ 70  50 100]]
Output:
[[255   0   0]
 [255   0   0]
 [  0   1   2]
 [255   0   0]
 [  4   5   6]]

UPDATE : Per OP's comment on converting string dict keys to numpy arrays:更新:根据 OP 关于将字符串字典键转换为 numpy arrays 的评论:

rgbL = np.array([list(map(int,[s.strip() for s in key.strip('[').strip(']').strip(' ').split(' ') if s.strip()])) for key in rgb_dict.keys()])

The algorithm mentioned above is O(length of rgbL * size of image)上面提到的算法是O(length of rgbL * size of image)

We can bring it down to O(length of the rgbL + size of image)我们可以将它降低到O(rgbL 的长度 + 图像的大小)

set_rgbl = set(rgbL)
height = img.shape[0]
width = img.shape[1]
BLUE_COLOR = (255, 0, 0)

for h in range(0, height):
    for w in range(0, width):
        if list(img[h, w]) in set_rgbl:
            img[h, w] = BLUE_COLOR

What happens here is that we created a set of rgbL values.这里发生的是我们创建了一组 rgbL 值。 The insert in set is constant time operation.集合中的插入是恒定时间操作。 Same holds for lookup.同样适用于查找。 Hence, when we are iterating over every pixel values in image for every pixel we spend O(1) time.因此,当我们为每个像素迭代图像中的每个像素值时,我们花费O(1)时间。 This leads to improvement in our time complexity.这导致我们的时间复杂度得到改善。

Hope that helps.希望有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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