我有一个包含一些图像数据的 numpy 数组。我想绘制在图像上绘制的横断面的“轮廓”。最简单的情况是平行于图像边缘运行的轮廓,所以如果图像数组是imdat
,那么在选定点(r,c)
的轮廓是只需 imdat[r]
(水平)或 imdat[:,c]
(垂直)。
现在,我想将两个点 (r1,c1)
和 (r2,c2)
作为输入,它们都位于 imdat
内.我想沿着连接这两个点的线绘制值的轮廓。
沿着这条线从 numpy 数组中获取值的最佳方法是什么?更一般地,沿着路径/多边形?
我以前使用过切片和索引,但对于连续切片元素不在同一行或同一列中的情况,我似乎无法找到一个优雅的解决方案。感谢您的帮助。
最佳答案
@Sven 的答案是简单的方法,但对于大型数组来说效率相当低。如果您正在处理一个相对较小的数组,您不会注意到差异,如果您想要一个较大的配置文件(例如 >50 MB),您可能需要尝试其他几种方法。不过,您需要在“像素”坐标中处理这些问题,因此会有额外的复杂性。
还有两种更节省内存的方法。 1) 使用scipy.ndimage.map_coordinates
如果您需要双线性或三次插值。 2)如果你只是想要最近邻采样,那么直接使用索引。
以第一个为例:
import numpy as np
import scipy.ndimage
import matplotlib.pyplot as plt
#-- Generate some data...
x, y = np.mgrid[-5:5:0.1, -5:5:0.1]
z = np.sqrt(x**2 + y**2) + np.sin(x**2 + y**2)
#-- Extract the line...
# Make a line with "num" points...
x0, y0 = 5, 4.5 # These are in _pixel_ coordinates!!
x1, y1 = 60, 75
num = 1000
x, y = np.linspace(x0, x1, num), np.linspace(y0, y1, num)
# Extract the values along the line, using cubic interpolation
zi = scipy.ndimage.map_coordinates(z, np.vstack((x,y)))
#-- Plot...
fig, axes = plt.subplots(nrows=2)
axes[0].imshow(z)
axes[0].plot([x0, x1], [y0, y1], 'ro-')
axes[0].axis('image')
axes[1].plot(zi)
plt.show()
使用最近邻插值的等效项如下所示:
import numpy as np
import matplotlib.pyplot as plt
#-- Generate some data...
x, y = np.mgrid[-5:5:0.1, -5:5:0.1]
z = np.sqrt(x**2 + y**2) + np.sin(x**2 + y**2)
#-- Extract the line...
# Make a line with "num" points...
x0, y0 = 5, 4.5 # These are in _pixel_ coordinates!!
x1, y1 = 60, 75
num = 1000
x, y = np.linspace(x0, x1, num), np.linspace(y0, y1, num)
# Extract the values along the line
zi = z[x.astype(np.int), y.astype(np.int)]
#-- Plot...
fig, axes = plt.subplots(nrows=2)
axes[0].imshow(z)
axes[0].plot([x0, x1], [y0, y1], 'ro-')
axes[0].axis('image')
axes[1].plot(zi)
plt.show()
但是,如果您使用最近邻,您可能只需要每个像素的样本,因此您可能会做更多类似的事情,而不是......
import numpy as np
import matplotlib.pyplot as plt
#-- Generate some data...
x, y = np.mgrid[-5:5:0.1, -5:5:0.1]
z = np.sqrt(x**2 + y**2) + np.sin(x**2 + y**2)
#-- Extract the line...
# Make a line with "num" points...
x0, y0 = 5, 4.5 # These are in _pixel_ coordinates!!
x1, y1 = 60, 75
length = int(np.hypot(x1-x0, y1-y0))
x, y = np.linspace(x0, x1, length), np.linspace(y0, y1, length)
# Extract the values along the line
zi = z[x.astype(np.int), y.astype(np.int)]
#-- Plot...
fig, axes = plt.subplots(nrows=2)
axes[0].imshow(z)
axes[0].plot([x0, x1], [y0, y1], 'ro-')
axes[0].axis('image')
axes[1].plot(zi)
plt.show()
关于python - 如何从 numpy 数组中提取任意行值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7878398/