沿numpy数组的某条线求和元素
我有一个很大的矩阵,大小是 (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 array”,我想要对“data array”中与原点在同一角度的所有元素进行求和,也就是说,沿着180度、165度、161度等等,一直到0度。输出应该是一个数组,包含角度和该角度的元素总和,比如说 out = array ([[180, 沿180的总和], [165, 沿165的总和], ... [0, 沿0的总和]]). 你能帮我吗?谢谢!
1 个回答
0
也许你在找的投影就在这个叫做“拉东变换”的东西里,或者它可能就是你所描述的内容。你可以在scikit-image的文档中找到一个关于这个变换的代码示例,还有一些重建的方法,具体可以查看这里
试试复制并粘贴这个:
import numpy as np
from skimage.transform import radon
image = np.zeros([100, 100])
image[25:75, 25:50] = np.arange(25)[np.newaxis, :]
angles = np.linspace(0., 180., 10)
# If the important part of the image is confined
# to a circle in the middle use circle=True
transformed = radon(image, theta=angles)
import matplotlib.pyplot as plt
plt.matshow(image)
plt.matshow(transformed.T)
plt.show()
这个transformed
矩阵每一列代表一个角度,里面包含了整个图像在这个角度方向上的所有投影线。如果你的图像是圆形的,指定circle=True
会很有用,这样就不会把边缘的部分投影出来。