Python中的图像梯度向量场

2024-06-02 08:55:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用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的结果有问题?


Tags: 图像imageimportnoneasnpsliceplt
1条回答
网友
1楼 · 发布于 2024-06-02 08:55:45

我认为你奇怪的结果,至少部分是因为p是uint8类型。即使是numpy diff也会导致此数据类型的数组的值明显不正确。如果通过将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

相关问题 更多 >