我阅读了关于如何绘制直方图的OpenCV documentation,并且我已经根据我的需要调整了教程中的代码,因此输出是这样的条形直方图:
我正在寻找一种方法来添加带有标签和索引的轴。有没有任何无痛的解决方案来实现这一目标?
答案 0 :(得分:0)
如果您仍然需要解决方案,并且不介意使用gnuplot。
这里有一个示例,我读取彩色图像,将其变为灰色,计算直方图,然后绘制直方图。
main.cpp
#include <iostream>
#include <vector>
#include <opencv2/opencv.hpp>
#include "gnuplot-iostream.h"
int main(int argc, char* argv[])
{
cv::Mat image = cv::imread(argv[1], CV_LOAD_IMAGE_COLOR);
if (!image.data)
{
LOGMSG_ERR_S_C() << "No image data\n";
return -1;
}
cv::cvtColor(image, image, cv::COLOR_BGR2GRAY);
// construct a grayscale histogram
int binNumber = 256;
int channels[] = {0};
int numImages = 1;
int histDim = 1;
int histSize[] = {binNumber};
float grayRange[] = {0, 256};
const float* ranges[] = {grayRange};
cv::MatND hist;
cv::calcHist(&image, numImages, channels, cv::Mat(), hist, histDim, histSize, ranges);
// plot the historgram
std::vector<std::pair<double, double> > data;
for (int bin = 0; bin < binNumber; bin++)
{
data.emplace_back(bin, hist.at<float>(bin));
}
Gnuplot gp;
gp << "plot" << gp.file1d(data) << "with lines title 'hist'" << std::endl;
cv::imshow("gray", image);
// show the image and wait for a keypress
cv::waitKey(0);
cv::destroyAllWindows();
return 0;
}
您可能需要对#include "gnuplot-iostream.h"
使用升压
CMakeLists.txt
# Handle Boost
find_package(Boost COMPONENTS system iostreams filesystem REQUIRED) # gnuplot needed: system iostreams filesystem
include_directories(
${CMAKE_CURRENT_SOURCE_DIR}
${Boost_INCLUDE_DIR})
target_link_libraries(${targetName}
${Boost_LIBRARIES}
${OpenCV_LIBS})