简体   繁体   English

根据2D numpy数组过滤3D numpy数组

[英]filtering a 3D numpy array according to 2D numpy array

I have a 2D numpy array with the shape (3024, 4032). 我有一个2D numpy数组形状(3024,4032)。

I have a 3D numpy array with the shape (3024, 4032, 3). 我有一个3D numpy阵列的形状(3024,4032,3)。

2D numpy array is filled with 0s and 1s. 2D numpy数组填充0和1。

3D numpy array is filled with values between 0 and 255. 3D numpy数组填充0到255之间的值。

By looking at the 2D array values, I want to change the values in 3D array. 通过查看2D数组值,我想更改3D数组中的值。 If a value in 2D array is 0, I will change the all 3 pixel values in 3D array into 0 along the last axes. 如果2D数组中的值为0,我将沿着最后一个轴将3D数组中的所有3个像素值更改为0。 If a value in 2D array is 1, I won't change it. 如果2D数组中的值为1,我将不会更改它。

I have checked this question, How to filter a numpy array with another array's values , but it applies for 2 arrays which have same dimensions. 我已经检查了这个问题, 如何使用另一个数组的值过滤numpy数组 ,但它适用于2个具有相同维度的数组。 In my case, dimensions are different. 就我而言,尺寸是不同的。

How the filtering is applied in two arrays, with same size on 2 dimensions, but not size on the last dimension? 如何在两个数组中应用过滤,在两个维度上具有相同的大小,但在最后一个维度上没有大小?

Ok, I'll answer this to highlight one pecularity regarding "missing" dimensions. 好的,我会回答这个问题,以突出一个关于“缺失”维度的世俗性。 Lets' assume a.shape==(5,4,3) and b.shape==(5,4) 让我们假设a.shape==(5,4,3)b.shape==(5,4)

When indexing , existing dimensions are left aligned which is why @Divakar's solution a[b == 0] = 0 works. 索引时 ,现有维度保持对齐,这就是为什么@Divakar的解决方案a[b == 0] = 0有效。

When broadcasting , existing dimensions are right aligned which is why @InvaderZim's a*b does not work. 广播时 ,现有尺寸是正确对齐的,这就是为什么@InvaderZim的a*b不起作用的原因。 What you need to do is a*b[..., None] which inserts a broadcastable dimension at the right 你需要做的是a*b[..., None] ,它在右边插入一个可广播的维度

I think this one is very simple: 我觉得这个很简单:

If a is a 3D array (a.shape == (5, 4, 3)) filled with values, and b is a 2D array (b.shape == (5, 4)) filled with 1 and 0, then reshape b and multiply them: 如果a是填充了值的3D数组(a.shape ==(5,4,3)),并且b是填充了1和0的2D数组(b.shape ==(5,4)),则重新形成b并乘以它们:

a = a * b.reshape(5, 4, 1)

Numpy will automatically expand the arrays as needed. Numpy会根据需要自动扩展阵列。

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

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