简体   繁体   English

索引numpy数组的最后一个维度

[英]indexing the last dimension of numpy array

I have two images called image and mask with the following shapes: 我有两个图像,分别为image和mask,具有以下形状:

image shape: (876, 1020, 3)
mask shape: (876, 1020)

What I am trying to do is divide each of the three elements of image with the mask where the mask is non-zero. 我想做的是将图像的三个元素中的每一个都除以遮罩,其中遮罩为非零值。 So, I do: 因此,我这样做:

import numpy as np

index = np.nonzero(mask)
image[index, :] = image[index, :]/mask[index]

This however causes the program to take a long time and then it fails with; 但是,这会使程序花费很长时间,然后失败。

ValueError: operands could not be broadcast together with shapes (2,302793,1020,3) (302793,) ValueError:操作数不能与形状(2,302793,1020,3)一起广播(302793,)

If you don't have memory problems with the creation of a copy of the mask, you could set the zero elements to 1 and divide through directly: 如果创建掩码副本没有内存问题,则可以将零元素设置为1并直接除法:

mask2 = mask.copy()
mask2[mask2==0]=1
image /= mask2[...,np.newaxis]

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

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