简体   繁体   English

通过2D数组索引3D数组

[英]Index 3D array by 2D array

I have a 3D color image im (shape 512 512 3), and a 2D array mask(512 512). 我有一个3D彩色图像im(形状为512 512 3)和一个2D阵列蒙版(512 512)。 I want to annotate this color image by the mask: 我想通过蒙版注释此彩色图像:

im = im[mask>threshold] + im[mask<threshold] * 0.2 + (255,0,0) * [mask<threshold].

How do I write this in Python efficiently? 如何有效地用Python编写此代码?

This works: 这有效:

mask3 = numpy.dstack(mask,mask,mask)
im = im * (mask3>threshold) + im * (mask3<threshold) * 0.2
im[:,:,0] += 255 * (mask<threshold)

It relies on the fact that the numeric value of true is 1 and false is 0. 它依赖于以下事实:true为1,false为0。

It may not be the clearest or the most efficient, but it will still likely be much faster than indexing by a boolean array, like im[ mask3 < threshold ] *= 0.2 ( unless the index has a very small number of true values, anyway ). 它可能不是最清晰或最有效的方法,但是它仍然可能比通过布尔数组建立索引要快得多,例如im[ mask3 < threshold ] *= 0.2无论如何,除非索引的真值数量非常少 )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM