x89
x89

Reputation: 3470

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

I am trying to run this code snippet:

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)

but I get an error at:

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

The original code used:

from scipy.ndimage import imread

to read the image file but since I was unable to import it, I used imread from another library instead. Could that have anything to do with the error?

Upvotes: 0

Views: 2210

Answers (2)

ffsedd
ffsedd

Reputation: 305

RGB image has 3 channels, your code works with 2 channels only. You could convert your images to grey:

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

Or if you do not care about correct RGB 2 grey: (see https://e2eml.school/convert_rgb_to_grayscale.html)

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

But it looks like you are reinventing a wheel. To get histogram use:

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

Upvotes: 0

Prefect
Prefect

Reputation: 1777

h,w = img.shape[:2] should fix the problem.

Upvotes: 3

Related Questions