我是计算机视觉的新手,这是我的第一个任务。我正在尝试创建与文件夹中每个图像对应的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)
我运行脚本时出现以下错误:
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
你能否告诉我这里是否遗漏了什么?
答案 0 :(得分:3)
对您的上述代码进行了一些小修改,我在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])