根据 2D numpy 数组过滤 3D numpy 数组 [英] filtering a 3D numpy array according to 2D numpy array

查看:55
本文介绍了根据 2D numpy 数组过滤 3D numpy 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个形状为 (3024, 4032) 的二维 numpy 数组.

I have a 2D numpy array with the shape (3024, 4032).

我有一个形状为 (3024, 4032, 3) 的 3D numpy 数组.

I have a 3D numpy array with the shape (3024, 4032, 3).

2D numpy 数组由 0 和 1 填充.

2D numpy array is filled with 0s and 1s.

3D numpy 数组填充了 0 到 255 之间的值.

3D numpy array is filled with values between 0 and 255.

通过查看 2D 数组值,我想更改 3D 数组中的值.如果 2D 数组中的值为 0,我会将 3D 数组中的所有 3 个像素值沿最后一个轴更改为 0.如果二维数组中的值是 1,我不会改变它.

By looking at the 2D array values, I want to change the values in 3D array. 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. If a value in 2D array is 1, I won't change it.

我查了这个问题,如何过滤具有另一个数组值的 numpy 数组,但它适用于具有相同维度的 2 个数组.就我而言,尺寸不同.

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. 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?

推荐答案

好的,我会回答这个问题以突出一个关于缺失"维度的特殊性.让我们假设 a.shape==(5,4,3)b.shape==(5,4)

Ok, I'll answer this to highlight one pecularity regarding "missing" dimensions. Lets' assume a.shape==(5,4,3) and b.shape==(5,4)

索引时,现有维度对齐,这就是@Divakar的解决方案a[b == 0] = 0有效的原因.

When indexing, existing dimensions are left aligned which is why @Divakar's solution a[b == 0] = 0 works.

广播时,现有尺寸对齐,这就是@InvaderZim的a*b不起作用的原因.您需要做的是 a*b[..., None] 在右侧插入一个可广播维度

When broadcasting, existing dimensions are right aligned which is why @InvaderZim's a*b does not work. What you need to do is a*b[..., None] which inserts a broadcastable dimension at the right

这篇关于根据 2D numpy 数组过滤 3D numpy 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆