将 numpy 数组中的所有像素替换为单独数组中的像素,除非值为 0
Replace all pixels in numpy array with pixels in separate array unless the value is 0
有一个opencv图像,我分成了3个通道:
image #opencv image
img_red = image[:, :, 2]
img_green = image[:, :, 1]
img_blue = image[:, :, 0]
然后就是三个过滤器:
red_filter
green_filter
blue_filter
它们都是 numpy 数组,但大部分由零填充,因此格式如下所示:
[0, 0, 0, 132, ... 0, 15, 0, 230, 0]
...
[32, 0, 5, 0, ... 0, 2, 150, 0, 0]
我想使用这些过滤器中的每个非零值来覆盖通道中的相同索引。
像这样:
img_red[index] = red_filter[index] if red_filter != 0
img_green[index] = green_filter[index] if green_filter != 0
img_blue[index] = blue_filter[index] if blue_filter != 0
final_img = cv2.merge(img_red, img_green, img_blue)
例如,如果频道看起来像这样:
[44, 225, 43, ... 24, 76, 56]
和过滤器:
[0, 0, 25 ... 2, 0, 91]
那么结果应该是:
[44, 225, 25 ... 2, 76, 91]
我试过使用 for 循环和列表理解,但是这段代码必须 运行 遍历视频中的每一帧,所以我想知道是否有更快的方法来实现相同的结果.
opencv 中是否有某种图像过滤或 numpy 操作可以有效地完成此过程?
你好像在找np.where
方法:
channel = np.array([44, 225, 43, 24, 76, 56])
filter = np.array([0, 0, 25, 2, 0, 91])
#result = np.array([44, 225, 25, 2, 76, 91])
>>> np.where(filter==0, channel, filter)
array([ 44, 225, 25, 2, 76, 91])
有一个opencv图像,我分成了3个通道:
image #opencv image
img_red = image[:, :, 2]
img_green = image[:, :, 1]
img_blue = image[:, :, 0]
然后就是三个过滤器:
red_filter
green_filter
blue_filter
它们都是 numpy 数组,但大部分由零填充,因此格式如下所示:
[0, 0, 0, 132, ... 0, 15, 0, 230, 0]
...
[32, 0, 5, 0, ... 0, 2, 150, 0, 0]
我想使用这些过滤器中的每个非零值来覆盖通道中的相同索引。
像这样:
img_red[index] = red_filter[index] if red_filter != 0
img_green[index] = green_filter[index] if green_filter != 0
img_blue[index] = blue_filter[index] if blue_filter != 0
final_img = cv2.merge(img_red, img_green, img_blue)
例如,如果频道看起来像这样:
[44, 225, 43, ... 24, 76, 56]
和过滤器:
[0, 0, 25 ... 2, 0, 91]
那么结果应该是:
[44, 225, 25 ... 2, 76, 91]
我试过使用 for 循环和列表理解,但是这段代码必须 运行 遍历视频中的每一帧,所以我想知道是否有更快的方法来实现相同的结果.
opencv 中是否有某种图像过滤或 numpy 操作可以有效地完成此过程?
你好像在找np.where
方法:
channel = np.array([44, 225, 43, 24, 76, 56])
filter = np.array([0, 0, 25, 2, 0, 91])
#result = np.array([44, 225, 25, 2, 76, 91])
>>> np.where(filter==0, channel, filter)
array([ 44, 225, 25, 2, 76, 91])