【发布时间】:2014-08-15 14:40:06
【问题描述】:
我有一个很大的形状矩阵 (977,699)。我想沿着大约从矩阵中心开始的一条线计算元素的总和。线的角度应在 0 到 180 度之间变化(相对于从矩阵中心经过的另一条线),步长为 20 度。对于每个步骤,我都想要元素的总和,因此输出应该是一个 10 个元素的 numpy 数组。我怎么能在 numpy 中做到这一点?
我想我已经找到了做我想做的事的方法,但我仍然需要帮助。这里有一个例子:
data = array([[ 0., 3., 0., 2., 0., 0., 0., 0., 0., 3.],
[ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 18., 15., 25., 0., 0., 0.],
[ 0., 0., 0., 23., 19., 20., 20., 0., 0., 0.],
[ 0., 0., 20., 22., 26., 23., 18., 0., 0., 0.],
[ 0., 0., 0., 23., 16., 20., 13., 0., 0., 0.],
[ 0., 0., 0., 0., 18., 20., 18., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 4., 0., 0., 3., 0., 0., 3., 0., 0.]])
def index_coords(data, origin=None):
"""Creates x & y coords for the indicies in a numpy array "data".
"origin" defaults to the center of the image. Specify origin=(0,0)
to set the origin to the lower left corner of the image."""
ny, nx = data.shape
if origin is None:
origin_x, origin_y = nx // 2, ny // 2
else:
origin_x, origin_y = origin
x, y = np.meshgrid(np.arange(nx), np.arange(ny))
x -= origin_x
y -= origin_y
return x, y
def cart2polar(x, y):
"""Transform carthesian to polar coordinates"""
r = np.sqrt(x**2 + y**2)
theta = np.arctan2(y, x)
return r, theta
a,b = index_coords(data,origin=(4,4))
r,theta = cart2polar(b,a)
degree = theta*(180.0/np.pi) # degrees
d = degree.astype(np.int) # from float to integer (degrees at all pixels)
d = array([[-135, -143, -153, -165, 180, 165, 153, 143, 135, 128],
[-126, -135, -146, -161, 180, 161, 146, 135, 126, 120],
[-116, -123, -135, -153, 180, 153, 135, 123, 116, 111],
[-104, -108, -116, -135, 180, 135, 116, 108, 104, 101],
[ -90, -90, -90, -90, 0, 90, 90, 90, 90, 90],
[ -75, -71, -63, -45, 0, 45, 63, 71, 75, 78],
[ -63, -56, -45, -26, 0, 26, 45, 56, 63, 68],
[ -53, -45, -33, -18, 0, 18, 33, 45, 53, 59],
[ -45, -36, -26, -14, 0, 14, 26, 36, 45, 51]])
一旦我有了“d 数组”,我想对“数据数组”的所有元素求和,这些元素相对于原点位于相同的度数,即沿 180、沿 165、沿 161 等等直到零度。输出应该是一个包含度数和该度数的元素总和的数组,即 out = array ([[180,sum along 180],[165, sum along 165],...[0, sum along 0]] )。你能帮我解决这个问题吗?谢谢你
【问题讨论】:
-
您想要什么并不完全清楚:矩阵中的“线”是什么,尤其是变化的线?您似乎想将几何应用于矩阵的概念。也许一个小草图会有所帮助。另外:到目前为止,您自己尝试过什么?
-
看看我刚刚编辑的例子,希望更清楚..
标签: python arrays numpy linear-algebra