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

标签 python opencv matplotlib computer-vision histogram

我是计算机视觉的新手,这是我的第一份作业。我正在尝试创建与文件夹中的每个图像相对应的 rgb 直方图。假设我在 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)

当我运行脚本时出现以下错误:

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

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

最佳答案

对上面的代码进行了一些小的修改,我在 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])

输入图片

enter image description here

直方图

enter image description here

输入图片

enter image description here

直方图

enter image description here

关于python - 在 python 中使用 cv2.calcHist 获取目录中多个图像的颜色直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37388671/

相关文章:

matplotlib:获取颜色图数组

python - Seaborn 热图自定义颜色图

java - Android 中的 Opencv ANN_MLP 训练

python - 有没有办法在matplotlib中获取xticklabel的坐标?

opencv - 如何将 Cloud Vision API 导出模型与 Open CV 程序结合使用?

opencv - 我们如何从图像中删除一种纯色?

python - 根据颜色图在条形图中的 y 值

python - 专门在 seaborn 集群图中更改热图的大小?

python - 在启动时将 python 脚本作为守护进程运行 (Ubuntu)

python - 这个 Python "static variable"hack 可以使用吗?