解包的值太多(在读取图像的形状时)

too many values to unpack (while reading image's shape)

我正在尝试 运行 这个代码片段:

from scipy.stats import wasserstein_distance
from imageio import imread
import numpy as np

def get_histogram(img):
  h, w = img.shape
  hist = [0.0] * 256
  for i in range(h):
    for j in range(w):
      hist[img[i, j]] += 1
  return np.array(hist) / (h * w)

a = imread("./IMG_4835.jpg")
b = imread("./IMG_4836.jpg")
a_hist = get_histogram(a)
b_hist = get_histogram(b)
dist = wasserstein_distance(a_hist, b_hist)
print(dist)

但我在以下位置收到错误消息:

h, w = img.shape
b = imread('b.jpg', mode='L')
ValueError: too many values to unpack (expected 2)

原代码使用:

from scipy.ndimage import imread

读取图像文件,但由于我无法导入它,所以我改用了另一个库中的 imread。这与错误有什么关系吗?

h,w = img.shape[:2] 应该可以解决问题。

RGB 图像有 3 个通道,您的代码仅适用于 2 个通道。 您可以将图像转换为灰色:

from skimage.color import rgb2gray
from skimage import img_as_ubyte
img = img_as_ubyte(rgb2gray(img))

或者如果您不关心正确的 RGB 2 灰色: (参见 https://e2eml.school/convert_rgb_to_grayscale.html

img = np.mean(img, axis=2).astype(np.uint8)

但看起来你是在重新发明轮子。要获得直方图,请使用:

a_hist, _ = np.histogram(a, bins=256)
b_hist, _ = np.histogram(b, bins=256)