python中使用cv2.calcHist的目录中多个图像的颜色直方图

Dhe*_*ngh 4 python opencv matplotlib histogram computer-vision

我是计算机视觉的新手,这是我的第一个任务。我正在尝试创建rgb histogram对应于文件夹中的每个图像。假设我在test文件夹中有 10 张图像(在我当前的工作目录中)。我想为每个图像创建 10 个直方图。我写了以下脚本:

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)
Run Code Online (Sandbox Code Playgroud)

当我运行脚本时,我收到以下错误:

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
Run Code Online (Sandbox Code Playgroud)

你能告诉我这里是否遗漏了什么吗?

Nic*_*eli 5

对上面的代码进行了一些小的修改,我在test文件夹中绘制了 2 个虚拟图像的直方图。

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])
Run Code Online (Sandbox Code Playgroud)

输入图像

在此处输入图片说明

直方图

在此处输入图片说明

输入图像

在此处输入图片说明

直方图

在此处输入图片说明