13

我有一个将 numpy 数组切成圆形的代码。我希望仅从圆中恢复一定角度范围内的值并掩盖数组。例如:用圆的 0 到 45 度之间的 (x,y) 位置屏蔽原始数组。

有这样做的pythonic方式吗?

这是我的(简化的)原始代码:

import numpy as np
matrix = np.zeros((500,500))
x = 240
y = 280
radius = 10
mask=np.ogrid[x-radius:x+radius+1,y-radius:y+radius+1]
matrix[mask]

提前致谢

编辑:我忽略了半径可以变化。

4

2 回答 2

28

我会通过从笛卡尔坐标转换为极坐标并为圆和您想要的角度范围构造布尔掩码来做到这一点:

import numpy as np

def sector_mask(shape,centre,radius,angle_range):
    """
    Return a boolean mask for a circular sector. The start/stop angles in  
    `angle_range` should be given in clockwise order.
    """

    x,y = np.ogrid[:shape[0],:shape[1]]
    cx,cy = centre
    tmin,tmax = np.deg2rad(angle_range)

    # ensure stop angle > start angle
    if tmax < tmin:
            tmax += 2*np.pi

    # convert cartesian --> polar coordinates
    r2 = (x-cx)*(x-cx) + (y-cy)*(y-cy)
    theta = np.arctan2(x-cx,y-cy) - tmin

    # wrap angles between 0 and 2*pi
    theta %= (2*np.pi)

    # circular mask
    circmask = r2 <= radius*radius

    # angular mask
    anglemask = theta <= (tmax-tmin)

    return circmask*anglemask

例如:

from matplotlib import pyplot as pp
from scipy.misc import lena

matrix = lena()
mask = sector_mask(matrix.shape,(200,100),300,(0,50))
matrix[~mask] = 0
pp.imshow(matrix)
pp.show()

在此处输入图像描述

于 2013-08-21T10:03:35.523 回答
1

方阵中的中心圆的相同方法:

def circleMask(mat, r=0):
    if mat.shape[0] != mat.shape[1]:
        raise TypeError('Matrix has to be square')
    if not isinstance(r, int):
        raise TypeError('Radius has to be of type int')

    s = mat.shape[0]
    d = num.abs(num.arange(-s/2 + s%2, s/2 + s%2))
    dm = num.sqrt(d[:, num.newaxis]**2 + d[num.newaxis, :]**2)

    return num.logical_and(dm >= r-.5, dm < r+.5)

循环这个隐式函数是昂贵的!

于 2017-01-19T13:39:36.190 回答