Python - 在 X 方向微分图像

Python - differentiating an image in the X direction

我希望有人能为我阐明这个概念。我需要创建一个函数,它将灰度图像(在 numpy 数组中)作为参数并逐像素迭代它。过去,我为此使用 np.nditer(image) 。我需要 return 一张类似于这张图片的图片(在一个 numpy 数组中)。

为了在X方向区分图像,我需要使用: F(x, y) = F(x+1, y) - F(x, y)

如您所见,我需要逐列进行,而 Y 保持不变。我将如何将其合并到 np.nditer 中?我应该注意我必须迭代,我不能为此进行矢量化。此外,输出的宽度将比原始宽度小一个,因为一旦到达最后一列就无法进行计算。

非常感谢任何帮助!

为什么你一定要遍历像素?为什么不简单地使用它?

h,w = image.shape
dx_image = image[:,1:w-1] - image[:,0:w-2]

我认为 numpy.diff(image, axis=0) 可以满足您的要求:

In [17]: image
Out[17]: 
array([[7, 2, 0, 7, 5],
       [7, 7, 2, 8, 6],
       [2, 6, 4, 0, 7],
       [7, 6, 2, 6, 1],
       [6, 8, 7, 6, 3]])

In [18]: np.diff(image, axis=0)
Out[18]: 
array([[ 0,  5,  2,  1,  1],
       [-5, -1,  2, -8,  1],
       [ 5,  0, -2,  6, -6],
       [-1,  2,  5,  0,  2]])

图像处理和数组中使用了不同的索引约定,所以我可能误解了要求。如果上面计算了错误维度的差异,请改用 axis=1

In [19]: np.diff(image, axis=1)
Out[19]: 
array([[-5, -2,  7, -2],
       [ 0, -5,  6, -2],
       [ 4, -2, -4,  7],
       [-1, -4,  4, -5],
       [ 2, -1, -1, -3]])