如何在不同大小的NumPy数组之间执行逻辑操作?

huangapple go评论65阅读模式
英文:

How do I apply a logical operation between numpy arrays of different sizes?

问题

我有一个存储为形状为(x,y,3)的numpy数组的图像。我有一个形状为(x,y)的numpy ndarray的掩码。如何将该掩码应用于我的图像?cv2.bitwise_and()似乎不起作用,直接使用image[mask]也不行。具体来说,我的掩码包含True和False,我想执行image & mask,但是要一次应用于所有图层而不是逐个图层(R,G,B)处理,然后再将它们合并。

英文:

I have an image stored as a numpy array with the shape (x,y,3). I have a mask that is a numpy ndarray of shape (x,y). How do I apply that mask to my image? cv2.bitwise_and() doesn't seem to work and neither does directly indexing with image[mask]. To be specific, my mask contains True and False and I want to perform image & mask, but applied to all layers at once instead of doing it one layer at a time (R,G,B) and combining them later.

答案1

得分: 1

使用 mask[:.:,None]。这将使 mask 变成一个维度为 (x, y, 1) 的数组,正常的广播规则可以处理 (x, y, 1) 与 (x, y, 3) 的按位与操作。

英文:

Try using mask[:.:,None]. This makes mask out to be an array of dimension (x, y, 1), and the normal broadcasting rules can handle anding (x, y, 1) with (x, y, 3).

huangapple
  • 本文由 发表于 2023年6月30日 03:48:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76584198.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定