【发布时间】:2015-11-30 14:59:58
【问题描述】:
我对 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()
到目前为止,一切正常,但我想以更快/更有效的方式解决“屏蔽”问题。是否有可能在一行中分配类似所有 3 个限制的内容? color_frame[((b_ch < b-offset) | (b_ch > b+offset)) & ... & ((r_ch < r-offset) | (r_ch > r+offset)))] = 0 之类的东西(虽然这不起作用)还是我的解决方案已经是最有效的?
【问题讨论】:
-
你也可以使用 np.logical_and(b_ch b+offset) 代替 np.where
标签: python indexing boolean rgb