2013-10-24 65 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