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

问题描述

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

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)