Gua*_*l11 11 python numpy angle matrix
我有一个代码将一个numpy数组切成一个圆圈.我希望仅从圆圈中恢复包含在特定角度范围内的值并掩盖数组.例如:屏蔽原始数组,其中(x,y)位置包含在圆圈的0到45度之间.
有这样做的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]
Run Code Online (Sandbox Code Playgroud)
提前致谢
编辑:我省略了半径可以变化.
ali*_*i_m 19
我会这样做,从笛卡儿坐标到极坐标转换,并为圆圈和你想要的角度范围构建布尔蒙版:
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
Run Code Online (Sandbox Code Playgroud)
例如:
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()
Run Code Online (Sandbox Code Playgroud)

| 归档时间: |
|
| 查看次数: |
6821 次 |
| 最近记录: |