【问题标题】:percentage difference between two images in python using correlation coefficient使用相关系数在python中两个图像之间的百分比差异
【发布时间】:2016-04-18 04:32:59
【问题描述】:

我想比较两个图像块,如果它们完全相同,则结果必须为 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()

结果是:

[[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]]

这些是我要比较的图像:

【问题讨论】:

  • 图片大小一样吗?
  • 是的,它们的大小相同。
  • @EvilTak 图片大小相同
  • 图像中有多少像素不相同的百分比差异?
  • @EvilTak 是的,因为 corr2 在 matlab 中返回

标签: matlab python-2.7 numpy image-processing scipy


【解决方案1】:

由于您想逐像素比较,您可以对展平的图像执行相关性,:

cm = np.corrcoef(a1.flat, a2.flat)

cm包含对称相关矩阵,其中非对角元素是相关系数。你得到它

r = cm[0, 1]

编辑: 使用相关性来比较图像存在问题。如果其中任何一个是完全平坦的(所有像素值相同),则相关性未定义。

如果图像是二进制的,您可以简单地计算相等像素的百分比:

agreement = np.sum(a == b) / a.size

【讨论】:

  • 这仍然适用于彩色图像吗?还是只用于灰度或二进制?
  • 使用这种方法,您将获得类似于所有图像通道的平均相关性。如果这是您定义彩色图像相关性的方式,它应该可以工作。
猜你喜欢
  • 2016-02-07
  • 2012-02-28
  • 1970-01-01
  • 1970-01-01
  • 2017-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-24
相关资源
最近更新 更多