直方图用来查看图像整体的变化形式,其具有平移不变性,放缩不变性的特点。

    1. #include <opencv2\opencv.hpp>
    2. #include <iostream>
    3. using namespace cv;
    4. using namespace std;
    5. int main()
    6. {
    7. Mat img = imread("apple.jpg");
    8. if (img.empty())
    9. {
    10. cout << "请确认图像文件名称是否正确" << endl;
    11. return -1;
    12. }
    13. Mat gray;
    14. cvtColor(img, gray, COLOR_BGR2GRAY);
    15. //设置提取直方图的相关变量
    16. Mat hist; //用于存放直方图计算结果
    17. const int channels[1] = { 0 }; //通道索引
    18. float inRanges[2] = { 0,255 };
    19. const float* ranges[1] = { inRanges }; //像素灰度值范围
    20. const int bins[1] = { 256 }; //直方图的维度,其实就是像素灰度值的最大值
    21. calcHist(&gray, 1, channels, Mat(), hist, 1, bins, ranges); //计算图像直方图
    22. //准备绘制直方图
    23. int hist_w = 512;
    24. int hist_h = 400;
    25. int width = 2;
    26. Mat histImage = Mat::zeros(hist_h, hist_w, CV_8UC3);
    27. for (int i = 1; i <= hist.rows; i++)
    28. {
    29. rectangle(histImage, Point(width*(i - 1), hist_h - 1),
    30. Point(width*i - 1, hist_h - cvRound(hist.at<float>(i - 1) / 15)),
    31. Scalar(255, 255, 255), -1);
    32. }
    33. namedWindow("histImage", WINDOW_AUTOSIZE);
    34. imshow("histImage", histImage);
    35. imshow("gray", gray);
    36. waitKey(0);
    37. return 0;
    38. }

    图4-1.png