Meh*_*had 4 matlab numpy image-processing scipy python-2.7
我想比较两个图像块,如果它们完全相同,则结果必须为 1,如果它们匹配 60%,则答案必须为 0.6。
在 Matlab 中,我可以使用corr2命令来执行此操作,但在 python 中我找不到方法。我试过,numpy.corrcoef但它返回一个矩阵并scipy.signal.correlate2d返回相同的。
这是我尝试过的:
import numpy as np
import matplotlib.pyplot as plt
from skimage.filter import threshold_otsu
import matplotlib.cm as cm
import Image
import scipy
from PIL import Image as im
fname = 'testi.jpg'
image = Image.open(fname).convert("L")
arr = np.asarray(image)
global_thresh = threshold_otsu(arr)
global_otsu = arr >= global_thresh
global_otsu = np.invert(global_otsu).astype(int)
a1 = global_otsu[80:150,1350:1350+160]
fname1 = 'testi2.jpg'
image1 = Image.open(fname1).convert("L")
arr1 = np.asarray(image1)
global_thresh1 = threshold_otsu(arr1)
global_otsu1 = arr1 >= global_thresh1
global_otsu1 = np.invert(global_otsu1).astype(int)
a2 = global_otsu1[80:150,1350:1350+160]
co = scipy.signal.correlate2d(a1,a2)
plt.gray()
plt.subplot(121)
plt.imshow(a1)
plt.subplot(122)
plt.imshow(a2)
plt.show()
Run Code Online (Sandbox Code Playgroud)
结果是:
[[0 0 0 ..., 0 0 0]
[0 0 0 ..., 0 0 0]
[0 0 0 ..., 0 0 0]
...,
[0 0 0 ..., 0 0 0]
[0 0 0 ..., 0 0 0]
[0 0 0 ..., 0 0 0]]
Run Code Online (Sandbox Code Playgroud)
这些是我想要比较的图像:
由于您想逐个像素地比较,您可以对展平的图像执行相关性,:
cm = np.corrcoef(a1.flat, a2.flat)
Run Code Online (Sandbox Code Playgroud)
cm包含对称相关矩阵,其中非对角元素是相关系数。你得到它
r = cm[0, 1]
Run Code Online (Sandbox Code Playgroud)
编辑: 使用相关性比较图像存在问题。如果它们中的任何一个是完全平坦的(所有像素都具有相同的值),则相关性是不确定的。
如果图像是二进制的,您可以简单地计算相等像素的百分比:
agreement = np.sum(a == b) / a.size
Run Code Online (Sandbox Code Playgroud)