为什么scipy.signal.correlate2d在本例中无法工作?

2024-05-13 21:43:15 发布

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

我试图交叉关联两幅图像,并通过找到最大相关值,在第一幅图像上定位模板图像。 我画了一个带有一些随机形状的图像(第一个图像),然后剪下其中一个形状(模板)。现在,当我使用scipy的correlate2d,并在最大值的相关性中定位点时,会出现几个点。据我所知,重叠处不应该只有一个最大点吗

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

我的代码如下所示:

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 correlating.
This is the template, cut from the original image

有人能告诉我我在这里可能做错了什么吗


Tags: thefrom定位test图像imageimportimg
2条回答

应用

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

在计算二维互相关之前corr应该给出预期的结果

清理代码,以获取完整示例:

from imageio import imread
from matplotlib import pyplot as plt
import scipy.signal as sp
import numpy as np

img = imread('https://i.stack.imgur.com/JL2LW.png', pilmode='L')
temp = imread('https://i.stack.imgur.com/UIUzJ.png', pilmode='L')

corr = sp.correlate2d(img - img.mean(), 
                      temp - temp.mean(),
                      boundary='symm',
                      mode='full')

# coordinates where there is a maximum correlation
max_coords = np.where(corr == np.max(corr))

plt.plot(max_coords[1], max_coords[0],'c*', markersize=5)
plt.imshow(corr, cmap='hot')

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

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

未经测试

相关问题 更多 >