【问题标题】:Arbitrary image slice with python/numpy使用 python/numpy 进行任意图像切片
【发布时间】:2013-11-03 20:29:00
【问题描述】:

我想沿任意线绘制 2D 图像的 1D 轮廓。下面的代码加载托管在 github 上的图像数据并绘制它:

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)

例如,上图中的红线是手工绘制的。我想可以以 a*x + b 的形式对其进行参数化。我也猜测某种插值是必要的,因为该线通过的点可能不是原始二维数据数组的一部分。

【问题讨论】:

标签: python numpy matplotlib scipy


【解决方案1】:

您想使用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

【讨论】:

  • 我觉得有更清晰的方法来生成要采样的点列表。
  • 我同意。有这种方法,它更 numpyish: a = asarray(a); b = asarray(b); dst = norm(b - a); return map_coordinates(I, (a[:,newaxis] * linspace(1, 0, dst) + b[:,newaxis] * linspace(0, 1, dst)), *arg, **kws)
  • 我会使用linspace(0, 1, int(np.ceil(dst)) + 1) 之类的东西来确保您获得足够的积分。 (确保a, b =(0, 0), (0, 1) 回馈你认为应该得到的东西)
猜你喜欢
  • 1970-01-01
  • 2023-03-07
  • 1970-01-01
  • 2015-05-08
  • 1970-01-01
  • 1970-01-01
  • 2018-10-23
  • 1970-01-01
  • 2019-01-24
相关资源
最近更新 更多