简体   繁体   English

检查图像的 RGB 值是否满足没有循环的条件

[英]Check if RGB values of an image meet conditions without a loop

Say I have a coloured image img, as defined below.假设我有一个彩色图像 img,定义如下。 And I have range values for R, G, and B: R1, R2, B1, and so on...我有 R、G 和 B 的范围值:R1、R2、B1 等等......

Now I want to set all RGB values of an image to [255, 0, 0] if the following conditions satisfied [(R1 > R & R < R2) & (G1 > G & G < G2) & (B1 > B & B < B2)].现在,如果满足以下条件,我想将图像的所有 RGB 值设置为 [255, 0, 0] [(R1 > R & R < R2) & (G1 > G & G < G2) & (B1 > B & B < B2)]。

I can do this by looping to all RGB values of the image, but I don't want to do it that way.我可以通过循环到图像的所有 RGB 值来做到这一点,但我不想那样做。 Is there a way that I can implement this one in the NumPyish way?有没有一种方法可以让我以 NumPyish 的方式实现这个? Or what is the best way to implement this one?或者实现这一点的最佳方法是什么?

img = cv2.imread(file)
R1 = 91
R2 = 150
G1 = 10
G2 = 100
B1 = 100
B2 = 150

You can do the colour comparison for each colour channel at once using numpy like img[:,:,2] > R1 for the red channel.您可以使用 numpy 一次对每个颜色通道进行颜色比较,例如红色通道的img[:,:,2] > R1 You can combine all these together like so.您可以像这样将所有这些组合在一起。

# opencv stores colour channels in BGR order by default normally
img[(img[:,:,0] > B1) &(img[:,:,0] < B2) & (img[:,:,1] > G1) & (img[:,:,1] < G2) & (img[:,:,2] > R1) & (img[:,:,2] < R2),:] = [0,0,255]

You can put the elements R1,R2,...,G1,G2,...,B1,B2,... into an array and check for the conditions in the following way:您可以将元素R1,R2,...,G1,G2,...,B1,B2,...放入数组中,并按以下方式检查条件:

import numpy as np
R = 90 # example
array=np.array([[R1,R2],[G1,G2],[B1,B2]])

And using the numpy where function, you can specify the condition, eg <R and the operations if the condition is satisfied or not satisfied.并且使用numpy where function,您可以指定条件,例如<R以及条件满足或不满足的操作。

np.where(array[:,0]<R, 255, array[:,0]) # for R1,G1,B1
np.where(array[:,1]<R, 0, array[:,0]) # for R2,G2,B2 and so on

You can modify from here.你可以从这里修改。

np.where(array[:,0]<R, 255, array[:,0]) goes through elements and if an element is less than R replaces the element with 255 and if not then does not modify the element. np.where(array[:,0]<R, 255, array[:,0])遍历元素,如果元素小于 R 将元素替换为 255,如果不是则不修改元素。

Just create a function and apply it over your elements.只需创建一个 function 并将其应用于您的元素。 Might still use a for loop internally.可能仍然在内部使用 for 循环。 Images are BGR format in opencv.图像为 opencv 中的 BGR 格式。

func = lambda x: [0, 0, 255] if (R1 > x[2] & x[2] < R2) & (G1 > x[1] & x[1] < G2) & (B1 > x[0] & x[0] < B2) else x
img2 = numpy.apply_along_axis(func, 0, img)

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

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