【发布时间】:2017-08-23 05:29:52
【问题描述】:
提供了一个带有标签的图像(像素的值对应于它的标签),以及接受的标签列表,如果像素标签被接受,我正在尝试创建一个带有255 值的“掩码”图像, 0 否则。
我知道这是一种缓慢的方法,因为它以 python 速度迭代图像(但它很好地展示了这个想法):
mask = numpy.zeros(labels.shape[:2], dtype = "uint8")
for i in xrange(mask.shape[0]):
for j in xrange(mask.shape[1]):
if labels[i][j] in accepted:
mask[i][j] = 255
我知道使用python slicing and masking 会快很多,但是我不知道如何组合一个复杂的条件。当我一个接一个地屏蔽接受标签的像素时,我仍然获得了巨大的加速,如下所示:
for value in accepted:
mask[labels == value] = 255
我能以某种方式制作一个单行线来做我想做的事吗?我的 python 知识很生疏(阅读:过去几年几乎没有 python),所以当我尝试使用我找到的一些示例来编写这个时,这是我得到的最接近的:
mask[(labels in accepted).all()] = 255
在这种情况下,我收到以下错误:ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
我查看过类似的 SO 问题(例如here 或 here 等),但它们似乎都涵盖了值来自某个范围或低于/高于阈值 (
任何关于如何检查“在接受值中的价值”的建议都会很棒。
【问题讨论】:
标签: python image performance numpy vectorization