首页 > 解决方案 > 为什么 tf.image.ssim 总是返回 AttributeError: 'numpy.ndarray' object has no attribute 'get_shape'

问题描述

我正在尝试使用tf.image.ssim来获取 2 个图像之间的相似性,但是,它返回一个属性错误。由于我只是直接使用 TensorFlow 代码,因此我看不到任何调试此问题的方法。

import tensorflow as tf
from sklearn import datasets
import matplotlib.pyplot as plt
iris = datasets.load_iris()
x_train, y= tf.keras.datasets.mnist.load_data(
    path='mnist.npz'
)

tf.image.ssim(
    x_train[0][0], x_train[0][0], 255
)

标签: tensorflow

解决方案


MNIST 返回 2D 灰度图像,SSIM 要求图像为 3D。因此,只需扩展要比较的返回图像的暗度并在其上应用 SSIM。

import numpy as np

(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data(
    path='mnist.npz'
)

x_train_expanded = np.expand_dims(x_train[0], axis=2)
print(tf.image.ssim(x_train_expanded, x_train_expanded, 255))

它返回以下内容:

tf.Tensor(1.0, shape=(), dtype=float32)

返回的张量包含批量每个图像的 MS-SSIM 值。这些值在 [0, 1] 范围内,示例返回值 1,表示两个图像相同。


推荐阅读