0

I'm trying to calculate the mean of histograms of several images from a folder and visualize it. Here is the approach I'm trying. I would calculate the histogram of each image with open cv, cv2.calcHist() function which returns a numpy.ndarray. I would loop through each image in the directory and append the resulting arrays to an empty list, pass the list into numpy.mean() and plot it, all with the following code:

import os
import matplotlib.pyplot as plt
import numpy as np
import cv2

img_list = os.listdir(r'\image_directory')

dir_path = r'\path'

list_arr = [] #array list
for file in img_list:
    img = os.path.join(dir_path, file)
    plot=plt.imread(img)
    hist=cv2.calcHist([plot],[0],None,[256],[0,256])
    list_arr.append(hist)

Calculating mean:

mean_hist = np.mean([list_arr],axis=0)

mean_hist.shape

Output: (154,256,1)

Plotting:

plt.plot(mean_hist)

I get this error:

ValueError: x and y can be no greater than 2-D, but have shapes (154,) and (154, 256, 1)

154 is the number of images in the directory, 256 is the max range of pixel intensity values of any given image.

But when I pass the hist arrays individually into np.mean() instead of a list all at once, it works.

Code:

im1 = plt.imread(r'...\Screenshot (166).jpg')
im2 = plt.imread(r'...\Screenshot (167).jpg')
im3 = plt.imread(r'...\Screenshot (168).jpg')
im4 = plt.imread(r'...\Screenshot (169).jpg')

hist_1 = cv2.calcHist([im1],[0],None,[256],[0,256])
hist_2 = cv2.calcHist([im2],[0],None,[256],[0,256])
hist_3 = cv2.calcHist([im3],[0],None,[256],[0,256])
hist_4 = cv2.calcHist([im4],[0],None,[256],[0,256])

mean_hist = np.mean([hist_1,hist_2,hist_3,hist_4], axis=0)

mean_hist.shape

Output in this case: (256,1)

And it plots the graph without any issue when I do:

plt.plot(mean_hist)

How to do this in a for loop without getting that above error?

1 Answer 1

1

Instead of

mean_hist = np.mean([list_arr],axis=0)

simply do

mean_hist = np.mean(list_arr, axis=0)
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.