首页 > 解决方案 > 在 python 中比较两个图像时,我想获得 SSIM

问题描述

我正在尝试使用“compare_ssim”功能。我目前有两个 x,y 坐标的 2xN 矩阵,其中第一行是所有 x 坐标,第二行是两个图像中每一个的所有 y 坐标。如何计算这两个图像的 SSIM(如果有办法这样做)

例如我有:

X = np.array([[1,2,3], [4,5,6]])
Y = np.array([[3,4,5],[5,6,7]])

compare_ssim(X,Y)

但我得到了错误

ValueError: win_size exceeds image extent.  If the input is a multichannel (color) image, set multichannel=True.

我不确定我是否遗漏了一个参数,或者我是否应该以这种函数工作的方式转换矩阵。或者,如果有一种方法可以将我的坐标转换为灰度矩阵?我对函数参数的矩阵应该是什么样子有点困惑。我知道它们应该是 ndarray,但 type(Y) 和 type(Y) 都是 numpy.ndarray。

标签: pythonssim

解决方案


由于您没有提到您正在使用哪个框架/库,我假设您正在使用 skimage 的compare_ssim

有问题的错误是由于您的输入形状造成的。您可以在此处找到更多详细信息。

TL;DR: compare_ssim需要 (H, W, C) 尺寸的图像,但您的输入图像的尺寸为 (2, 3)。因此,函数混淆了将哪个维度视为通道维度。当multichannel=True时,最后一个维度被视为通道维度。

您的代码存在 3 个关键问题,

  1. compare_image 期望图像作为输入。所以你的 X 和 Y 矩阵的尺寸应该是 (H, W, C) 而不是 (2, 3)

  2. 它们应该是浮点数据类型。

下面我展示了一些演示代码(注意:从 skimage v1.7 开始,compare_ssim 已移至 skimage.metrics.structural_similarity)


import numpy as np  
from skimage.metrics import structural_similarity

img1 = np.random.randint(0, 255, size=(200, 200, 3)).astype(np.float32)
img2 = np.random.randint(0, 255, size=(200, 200, 3)).astype(np.float32)

ssim_score = structural_similarity(img1, img2, multichannel=True) #score: 0.0018769083894301646

ssim_score = structural_similarity(img1, img1, multichannel=True) #score: 1.0


推荐阅读