【问题标题】:Image Gradient Vector Field in PythonPython中的图像梯度向量场
【发布时间】:2015-07-16 18:24:42
【问题描述】:

我正在尝试使用 Python 获取图像的Gradient Vector Field(类似于this matlab question)。

这是原图:

这是我的代码:

import numpy as np
import matplotlib.pyplot as plt
import Image
from PIL import ImageFilter

I = Image.open('test.png').transpose(Image.FLIP_TOP_BOTTOM)
I = I.filter(ImageFilter.BLUR)
p = np.asarray(I)
w,h = I.size
y, x = np.mgrid[0:h:500j, 0:w:500j]

dy, dx = np.gradient(p)
skip = (slice(None, None, 3), slice(None, None, 3))

fig, ax = plt.subplots()
im = ax.imshow(I, extent=[x.min(), x.max(), y.min(), y.max()])
ax.quiver(x[skip], y[skip], dx[skip], dy[skip])

ax.set(aspect=1, title='Quiver Plot')
plt.show()

这是结果:

问题在于向量似乎不正确。当您放大图像时,这一点会变得更加清晰:

为什么有些向量按预期指向中心,而有些则没有?

可能调用np.gradient的结果有问题?

【问题讨论】:

    标签: python image image-processing numpy gradient


    【解决方案1】:

    我认为您的奇怪结果至少部分是因为 p 的类型为 uint8。即使是 numpy diff 也会导致该 dtype 数组的值明显不正确。如果通过将p 的定义替换为以下内容来转换为有符号整数:p = np.asarray(I).astype(int8),则 diff 的结果是正确的。下面的代码给了我一个看起来很合理的字段,

    import numpy as np
    import matplotlib.pyplot as plt
    from PIL import Image
    from PIL import ImageFilter
    
    I = Image.open('./test.png')
    I = I.filter(ImageFilter.BLUR)
    p = np.asarray(I).astype('int8')
    w,h = I.size
    x, y = np.mgrid[0:h:500j, 0:w:500j]
    
    dy, dx = np.gradient(p)
    skip = (slice(None, None, 3), slice(None, None, 3))
    
    fig, ax = plt.subplots()
    im = ax.imshow(I.transpose(Image.FLIP_TOP_BOTTOM), 
                   extent=[x.min(), x.max(), y.min(), y.max()])
    plt.colorbar(im)
    ax.quiver(x[skip], y[skip], dx[skip].T, dy[skip].T)
    
    ax.set(aspect=1, title='Quiver Plot')
    plt.show()
    

    这给出了以下内容:

    并关闭它看起来像你期望的那样,

    【讨论】:

    • 很好,.astype('int8') 也可以。是 u(无符号)造成了负梯度问题(将负值剪切为正值)
    • 解决了,非常感谢!。其实我把“transpose”调用移到了im = ax.imshow(I), ieim = ax.imshow(I.transpose(Image. FLIP_TOP_BOTTOM)),然后我得到了与您的图像完全相同的结果。如果您愿意,可以更改它,以便人们可以直接使用您的代码。另外,我同意使用 np.int8 可能比 float 更好。
    • 更新:在梯度上使用高斯滤波器可以获得“更柔和”的版本。即:dcc.fceia.unr.edu.ar/~rbaravalle/gradient/resultSoft.png 代码结果:dcc.fceia.unr.edu.ar/~rbaravalle/gradient/test3.py
    • 在 diff/gradient 等 numpy 例程中使用无符号整数似乎有点棘手。正如建议的那样,我已将转置移至 imshow,更改为 int8 并从 dy 中删除减号。
    猜你喜欢
    • 2012-05-12
    • 2015-12-30
    • 1970-01-01
    • 1970-01-01
    • 2017-01-03
    • 1970-01-01
    • 2016-11-27
    • 2018-09-04
    • 2017-12-10
    相关资源
    最近更新 更多