遮罩图像中具有特定 RGB 值的对象
Masking Objects with certain RGB values in Images
我对 Python 有点陌生,之前用过很多 MATLAB,现在我正在为最简单的事情苦苦挣扎。我的问题如下:
我有一个合成场景的图像。某些对象具有预定义的 rgb 值。我现在想提取这些对象。我声明 RGB 值加上一些偏移量,因此能够创建一个仅包含属于该对象的像素的蒙版,其他所有内容都设置为 0(=黑色)。
举个简单的例子,假设 rgb 值中所需对象的颜色是 r=255,b=0,g=60,每种颜色的偏移量=5。
到目前为止,我的代码如下所示:
import cv2
import numpy as np
# read image_file
color_frame = cv2.imread(image_file,1)
# split the channles
b_ch,g_ch,r_ch = cv2.split(color_frame)
# mask the different channels seperately
color_frame[np.where((b_ch < b-offset) | (b_ch > b+offset))] = 0
color_frame[np.where((g_ch < g-offset) | (g_ch > g+offset))] = 0
color_frame[np.where((r_ch < r-offset) | (r_ch > r+offset))] = 0
# show the extracted image
cv.imshow('Extracted Object',color_frame)
cv.waitKey(0)
cv.destroyAllWindows()
到目前为止一切正常,但我想以 faster/more 有效的方式解决 "masking"。是否有可能在一行中分配所有 3 个限制?像 color_frame[((b_ch < b-offset) | (b_ch > b+offset)) & ... & ((r_ch < r-offset) | (r_ch > r+offset)))] = 0
这样的东西(虽然这不起作用)还是我的解决方案已经是最有效的?
您可以使用 &
作为逻辑和 np.where
。所以你可以这样写:
color_frame[np.where(((b_ch < b-offset) | (b_ch > b+offset)) & ((g_ch < g-offset) | (g_ch > g+offset)) & ((r_ch < r-offset) | (r_ch > r+offset)))] = 0
我对 Python 有点陌生,之前用过很多 MATLAB,现在我正在为最简单的事情苦苦挣扎。我的问题如下: 我有一个合成场景的图像。某些对象具有预定义的 rgb 值。我现在想提取这些对象。我声明 RGB 值加上一些偏移量,因此能够创建一个仅包含属于该对象的像素的蒙版,其他所有内容都设置为 0(=黑色)。
举个简单的例子,假设 rgb 值中所需对象的颜色是 r=255,b=0,g=60,每种颜色的偏移量=5。 到目前为止,我的代码如下所示:
import cv2
import numpy as np
# read image_file
color_frame = cv2.imread(image_file,1)
# split the channles
b_ch,g_ch,r_ch = cv2.split(color_frame)
# mask the different channels seperately
color_frame[np.where((b_ch < b-offset) | (b_ch > b+offset))] = 0
color_frame[np.where((g_ch < g-offset) | (g_ch > g+offset))] = 0
color_frame[np.where((r_ch < r-offset) | (r_ch > r+offset))] = 0
# show the extracted image
cv.imshow('Extracted Object',color_frame)
cv.waitKey(0)
cv.destroyAllWindows()
到目前为止一切正常,但我想以 faster/more 有效的方式解决 "masking"。是否有可能在一行中分配所有 3 个限制?像 color_frame[((b_ch < b-offset) | (b_ch > b+offset)) & ... & ((r_ch < r-offset) | (r_ch > r+offset)))] = 0
这样的东西(虽然这不起作用)还是我的解决方案已经是最有效的?
您可以使用 &
作为逻辑和 np.where
。所以你可以这样写:
color_frame[np.where(((b_ch < b-offset) | (b_ch > b+offset)) & ((g_ch < g-offset) | (g_ch > g+offset)) & ((r_ch < r-offset) | (r_ch > r+offset)))] = 0