4

I am new to computer vision and this is my first assignment. I am trying to create rgb histogram corresponding to each image in a folder. Let's assume I have 10 images in test folder (which is inside my current working directory). And I want to create 10 histograms corresponding to each image. I wrote following script:

import os
import cv2
import numpy as np
from matplotlib import pyplot as plt
import pylab
images = []
for image in os.listdir("./test/"): 
    images.append(image)
color = ('b','g','r')
for image in images:
    img = cv2.imread(image) 
    for i, col in enumerate(color):
        hist = cv2.calcHist([img], [i], None, [256], [0,256])
        plt.plot(hist, color = col)
        plt.xlim([0,256])
        pylab.savefig(image)

While I run the script I get following error :

OpenCV Error: Assertion failed (j < nimages) in histPrepareImages, file /../../OpenCV/opencv-2.4.13/modules/imgproc/src/histogram.cpp, line 148
Traceback (most recent call last):
File "foo.py", line 23, in <module>
hist = cv2.calcHist([img], [i], None, [256], [0,256])
cv2.error: /../../OpenCV/opencv-2.4.13/modules/imgproc/src/histogram.cpp:148: error: (-215) j < nimages in function histPrepareImages

Can you please tell if I am missing out anything here?

Rahul K P
  • 9,913
  • 3
  • 28
  • 46
Dheeraj Singh
  • 625
  • 1
  • 11
  • 20

1 Answers1

5

There are some minor modifications to your above code and I have plotted the histograms for 2 dummy images inside the test folder.

import matplotlib.pyplot as plt
import cv2
import os

images = []
path = "../Mission Begins/test/"
for image in os.listdir(path):
    images.append(image)

for image in images:
     img = cv2.imread("%s%s"%(path, image))    # Load the image 
     channels = cv2.split(img)       # Set the image channels
     colors = ("b", "g", "r")        # Initialize tuple 
     plt.figure()    
     plt.title("Color Histogram")
     plt.xlabel("Bins")
     plt.ylabel("Number of Pixels")

     for (i, col) in zip(channels, colors):       # Loop over the image channels
          hist = cv2.calcHist([i], [0], None, [256], [0, 256])   # Create a histogram for current channel
          plt.plot(hist, color = col)      # Plot the histogram
          plt.xlim([0, 256])

Input Image

enter image description here

Histogram

enter image description here

Input Image

enter image description here

Histogram

enter image description here

Nickil Maveli
  • 24,795
  • 6
  • 65
  • 74