Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 遮罩numpy阵列中的圆形扇区_Python_Numpy_Matrix_Angle - Fatal编程技术网

Python 遮罩numpy阵列中的圆形扇区

Python 遮罩numpy阵列中的圆形扇区,python,numpy,matrix,angle,Python,Numpy,Matrix,Angle,我有一个将numpy数组分割成圆形的代码。我只希望从圆中恢复一定角度范围内的值,并屏蔽阵列。例如:使用(x,y)位置遮罩原始阵列,该位置包含在圆的0到45度之间 有没有一种类似蟒蛇的方法 以下是我的(简化)原始代码: 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[mas

我有一个将numpy数组分割成圆形的代码。我只希望从圆中恢复一定角度范围内的值,并屏蔽阵列。例如:使用(x,y)位置遮罩原始阵列,该位置包含在圆的0到45度之间

有没有一种类似蟒蛇的方法

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

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]
提前谢谢


编辑:我省略了半径可以变化的问题。

我将通过将笛卡尔坐标转换为极坐标,并为圆和所需角度范围构造布尔掩码来实现这一点:

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

对于方形矩阵中的中心圆,采用相同的方法:

def回路任务(mat,r=0):
如果材料形状[0]!=材料形状[1]:
raise TypeError('矩阵必须是正方形')
如果不是isinstance(r,int):
raise TypeError('半径必须为int'类型)
s=材料形状[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)
返回num.logical_和(dm>=r-.5,dm

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

您的代码将屏蔽数组中的一个正方形而不是一个圆-它确实是您想要的圆吗?是的,就是这样。我看到了我的错误,我正在努力解决它!也许这是@SaulloCastro的复制品,在这种情况下,这是一个循环扇区,而不仅仅是一个circle@ali_m非常感谢。我不确定这是不是复制品!它工作得很好,这就是我想要的。多谢各位much@ali_m +1. 我希望你不介意,我在答案中添加了图片,这样我们就可以准确地看到发生了什么。
theta=np。arctan2(x-cx,y-cy)
必须使用
theta=np将其更改为所有正角度(theta@Developer很好,我已经编辑了我的函数来解决这个问题
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()