C++ Opencv圖像直方圖


Mat image = imread("D:/ju.jpg");
    imshow("素材圖", image);
    int bins = 256;    //直條為256
    int hist_size[] = { bins };
    float range[] = { 0,256 };
    const float* ranges[] = { range };

    MatND redHist, greenHist, blueHist;
    //MAT數據為BGR
    int channels_r[] = { 2 }; //r通道
    calcHist(&image, 1, channels_r, Mat(), redHist, 1, hist_size, ranges, true, false);
    int channels_g[] = { 1 };
    calcHist(&image, 1, channels_g, Mat(), greenHist, 1, hist_size, ranges, true, false);
    int channels_b[] = { 0 };
    calcHist(&image, 1, channels_b, Mat(), blueHist, 1, hist_size, ranges, true, false);

    //准備參數繪制三色直方圖
    double maxValue_red, maxValue_green, maxValue_blue;
    minMaxLoc(redHist, 0, &maxValue_red, 0, 0);
    minMaxLoc(greenHist, 0, &maxValue_green, 0, 0);
    minMaxLoc(blueHist, 0, &maxValue_blue, 0, 0);

    int scale = 1;
    int histHeight = 256;
    //bins * 3 是因為要繪制三個通道,每個通道的像素取值在 0-bins
    Mat histImage = Mat::zeros(histHeight, bins * 3, CV_8UC3);

    //開始繪制
    for (int i = 0; i < bins; i++) {
        float binValue_red = redHist.at<float>(i);
        float binValue_green = greenHist.at<float>(i);
        float binValue_blue = blueHist.at<float>(i);

        //計算高度時的乘除與下面繪圖的 histHeight - intensity 是為了便於顯示,否則有的色度很低
        //要繪制的高度
        int intensity_red = cvRound(binValue_red * histHeight / maxValue_red);
        int intensity_green = cvRound(binValue_green * histHeight / maxValue_green);
        int intensity_blue = cvRound(binValue_blue * histHeight / maxValue_blue);
        rectangle(histImage, Point(i * scale, histHeight - 1),
            Point((i + 1) * scale - 1, histHeight - intensity_red),
            Scalar(255, 0, 0));
        rectangle(histImage, Point((i + bins) * scale, histHeight - 1),
            Point((i + bins + 1) * scale - 1, histHeight - intensity_green),
            Scalar(0, 255, 0));
        rectangle(histImage, Point((i + bins * 2) * scale, histHeight - 1),
            Point((i + bins * 2 + 1) * scale - 1, histHeight - intensity_blue),
            Scalar(0, 0, 255));
    }

    imshow("圖像的 RGB 直方圖", histImage);

效果如下:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM