2013-10-24 66 views
1

我想绘制沿任意一条线的2D图像的一维轮廓。下面的代码加载托管在github上的图像数据,并绘制它:蟒蛇/ numpy的任意图像切片

import urllib 
import numpy as np 
import matplotlib.pyplot as plt 

url = "https://gist.github.com/andreiberceanu/7141843/raw/0b9d50d3d417b1cbe651560470c098700df5a1fc/image.dat" 
f = urllib.urlopen(url) 
data = np.loadtxt(f) 

plt.imshow(data) 

waves with line

在上面的图中的红色线由手绘,作为一个例子。我想可以用a * x + b的形式参数化它。我也猜测某种内插是必要的,因为这条线穿过可能不是原始二维数据阵列一部分的点。

+0

你的问题是什么? – alko

+3

看到这个相关的问题:http://stackoverflow.com/questions/7878398/how-to-extract-an-arbitrary-line-of-values-from-a-numpy-array – aganders3

回答

2

您想使用scipy.ndimage.map_coordinates。你需要建立一个2xn数组,这个数组是坐标进行采样,然后执行map_coordinates(im, samples)

我觉得这是它:

def sliceImage(I, a, b, *arg, **kws): 
    from scipy import linspace, asarray 
    from scipy.ndimage import map_coordinates 
    from scipy.linalg import norm 
    dst = norm(asarray(b) - a) + 1 
    return map_coordinates(I, [linspace(strt, end, dst) 
           for strt, end in zip(a, b)], 
          *arg, **kws) 

编辑: 在进一步的考虑,我觉得这是更优雅:

def sliceImage(I, a, b, *arg, **kws): 
    from scipy import linspace, asarray 
    from scipy.ndimage import map_coordinates 
    from scipy.linalg import norm 
    a = asarray(a) 
    b = asarray(b) 
    dst = norm(b - a) + 1 
    return map_coordinates(I, (a[:,newaxis] * linspace(1, 0, dst) + 
           b[:,newaxis] * linspace(0, 1, dst)), 
          *arg, **kws) 

编辑:感谢tcaswell:新增1 dst

+1

我觉得有更清晰的方法来产生要抽样的点的列表。 – tacaswell

+0

我同意。有这种方法,这是更numpyish: a = asarray(a); b = asarray(b);dst =范数(b - a); (1,0,dst)+ b [:,newaxis] * linspace(0,1,dst)), * arg,** kws) – Ben

+1

我会用'linspace(0,1,int(np.ceil(dst))+ 1)'来确保你获得足够的点数。 (确保'a,b =(0,0),(0,1)'回报你认为应该) – tacaswell