我有一个将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]
提前致谢
编辑:我省略了半径可能会有所不同。
答案 0 :(得分: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
例如:
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()
答案 1 :(得分:1)
方形矩阵中心圆的相同方法:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity">
<item
android:id="@+id/filter"
android:icon="@android:drawable/ic_dialog_email"
android:title="Filter"
app:showAsAction="always">
<menu>
<item
android:id="@+id/action_dropdown1"
android:checkable="true"
android:icon="@android:drawable/btn_dialog"
android:title="free"
app:showAsAction="always" />
<item
android:id="@+id/action_dropdown2"
android:icon="@android:drawable/btn_minus"
android:title="paid">
</item>
<item
android:id="@+id/action_find"
android:icon="@android:drawable/ic_dialog_email"
android:title="find" />
</menu>
</item>
<item
android:id="@+id/action_search"
android:icon="@android:drawable/ic_menu_search"
android:title="Search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="always" />
</menu>
循环这个隐式函数是很昂贵的!