Python中的图像渐变矢量场

时间:2015-05-06 14:31:00

标签: python image image-processing numpy gradient

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

这是原始图片: http:/ /dcc.fceia.unr.edu.ar/~rbaravalle/gradient/test.png

这是我的代码:

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()

这是结果: http://dcc.fceia.unr.edu.ar/~rbaravalle/gradient/result.png

问题是矢量似乎不正确。放大图像时,此点会更清晰:

http://dcc.fceia.unr.edu.ar/~rbaravalle/gradient/result2.png

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

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

1 个答案:

答案 0 :(得分:7)

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

import numpy as np
import matplotlib.pyplot as plt
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()

这给出了以下内容:

Solution

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

enter image description here