在numpy中选择满足多个条件的rgb图像像素

selecting rgb image pixels satisfying multiple conditions in numpy

我正在尝试进行视频处理,我希望能够有效地获取所有像素,红色高于 100,绿色低于 100,蓝色低于 100。我设法用 for 循环完成了并对每个像素进行 3 次评估,但这太慢了,每帧需要 13 秒。我目前正在使用cv2获取图像,并且有

的处理代码
retval = np.delete(frame, (0, 1), 2) #extracts just red of the pixels
retval = np.argwhere(retval>100) #extracts where red is above 100
retval = np.delete(retval, 2, 1) #removes the actual color value, leaving it as coordinates

这让我对任何红色值超过 100 的东西都有了部分解决方案,但它也包括棕色和白色之类的东西,这并不理想。这个循环需要非常快地发生,这就是我想使用 numpy 的原因,但我不确定要使用什么命令。任何帮助将不胜感激。 "frame" 数组的结构如下,格式为 BGR,而非 RGB。第一个索引为x坐标,第二个索引为y坐标,第三个索引为0、1或2,分别对应蓝、绿、红。

[[[255,   0,   0],
  [255,   0,   0],
  [255,   0,   0],
  ...,
  [  8,  20,   8],
  [ 12,  15,  20],
  [ 16,  14,  26]],

  [[255,   0,   0],
  [ 37,  27,  20],
  [ 45,  36,  32],
  ...,
  [177, 187, 157],
  [180, 192, 164],
  [182, 193, 167]]]

尝试制作三个布尔掩码,每个条件一个,然后将它们与 np.logical_and

合并
im = #define the image suitably 
mask = np.logical_and.reduce((im[:,:,0]<100,im[:,:,1]<100,im[:,:,2]>100))
im[mask] # returns all pixels satisfying these conditions

这很快。它基于两个 numpy 功能:广播和屏蔽。您可以并且应该在 numpy 文档中阅读这些内容。对于相对复杂的任务,您只需要循环。

编辑:

如果你想要像素的索引,

i,j = np.where(mask)

那么像素值为

im[i,j]