在numpy中创建环形面具

时间:2018-04-15 00:17:01

标签: python arrays numpy

我有256x256像素数据。每个像素是4个单位。我试图在numpy中创建一个环形或环状的掩码函数。该函数应采用内外半径,x数组的维数和y数组和中心。到目前为止我写了这个:

def createAnnularMask(dimx, dimy, center, big_radius, small_radius):

    Y, X = np.ogrid[:dimx, :dimy]
    distance_from_center = np.sqrt((X - center[0])**2 + (Y-center[1])**2)

    mask =  small_radius <= distance_from_center <= big_radius

    return mask

但是当我尝试使用参数调用函数时,它会返回以下错误:

createAnnularMask(256, 256, [128,128], 413, 80)

ValueError                                Traceback (most recent call last)
<ipython-input-45-65514f563633> in <module>()
----> 1 ring = createAnnularMask(256, 256, center, big_radius, small_radius)

<ipython-input-39-d7207a35bc48> in createAnnularMask(dimx, dimy, center, big_radius, small_radius)
      4     distance_from_center = np.sqrt((X - center[0])**2 + (Y-center[1])**2)
      5 
----> 6     mask =  small_radius <= distance_from_center <= big_radius
      7 
      8     return mask

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

你能否轻松指出我在这里做错了什么以及如何解决这个问题。

1 个答案:

答案 0 :(得分:2)

您无法与numpy数组进行复合比较。将该行更改为以下内容:

mask = (small_radius <= distance_from_center) & \
    (distance_from_center <= big_radius)