scipy.signal.correlate2d似乎无法按预期工作

时间:2019-07-19 11:02:20

标签: python scipy

我正在尝试使两个图像互相关,从而通过找到最大相关值将模板图像定位在第一幅图像上。 我绘制了一些具有随机形状的图像(第一个图像),并切出了其中一个形状(模板)。现在,当我使用scipy的relatede2d并在最大值中找到相关点时,会出现几个点。据我所知,难道不应该只有一个重叠最大的点吗?

此练习背后的想法是获取图像的一部分,然后将其与数据库中的某些先前图像相关联。然后,我应该能够根据相关的最大值在旧图像上定位此部分。

我的代码如下:

from matplotlib import pyplot as plt
from PIL import Image 
import scipy.signal as sp

img = Image.open('test.png').convert('L')
img = np.asarray(img)

temp = Image.open('test_temp.png').convert('L')
temp = np.asarray(temp)
corr = sp.correlate2d(img, temp, boundary='symm', mode='full')

plt.imshow(corr, cmap='hot')
plt.colorbar()

coordin = np.where(corr == np.max(corr)) #Finds all coordinates where there is a maximum correlation

listOfCoordinates= list(zip(coordin[1], coordin[0]))

for i in range(len(listOfCoordinates)): #Plotting all those coordinates
    plt.plot(listOfCoordinates[i][0], listOfCoordinates[i][1],'c*', markersize=5)

得出图: Cyan stars are points with max correlation value (255)

我希望“ corr”中只有一个点具有最大的相关值,但是有几个点会出现。我尝试使用不同的关联模式,但无济于事。 This is the test image i use when correlatingThis is the template, cut from the original image

任何人都可以对我在这里做错的事情有所了解吗?

2 个答案:

答案 0 :(得分:0)

您可能正在溢出numpy类型uint8。 尝试使用:

img = np.asarray(img,dtype=np.float32)
temp = np.asarray(temp,dtype=np.float32)

未经测试。

答案 1 :(得分:0)

正在申请

img = img - img.mean()
temp = temp - temp.mean()

在计算2D互相关corr之前,应该可以得到预期的结果。

相关问题