我是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()
到目前为止,这一切都运转良好,但我想解决'#34; masking&#34;以更快/更有效的方式。是否有可能在一行中分配类似所有3个限制的内容?像color_frame[((b_ch < b-offset) | (b_ch > b+offset)) & ... & ((r_ch < r-offset) | (r_ch > r+offset)))] = 0
这样的东西(虽然这不起作用)或者我的解决方案已经是最有效的了吗?
答案 0 :(得分:1)
您可以将&
用于逻辑和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