2013-04-02 245 views
0

嗨,任何人都可以提供一個簡單的開放式cv程序來加載兩個RGB圖像,將其轉換爲灰度,計算直方圖,然後比較它們的直方圖。我在開放的cv站點看到了一個類似的程序,但他們使用HSV而不是灰度級,它是一個C++程序。我可以查看流程和一切......我不知道使用哪些函數以及它們的參數意味着什麼...... Regards, Kiran比較opencv灰度圖像的直方圖

+0

你是什麼意思「比較直方圖」? – brotherofken

回答

10

以下是執行此操作的簡單代碼段。既然你沒有告訴你想如何比較直方圖,我建議直觀地做。

#include <opencv2/opencv.hpp> 

void show_histogram(std::string const& name, cv::Mat1b const& image) 
{ 
    // Set histogram bins count 
    int bins = 256; 
    int histSize[] = {bins}; 
    // Set ranges for histogram bins 
    float lranges[] = {0, 256}; 
    const float* ranges[] = {lranges}; 
    // create matrix for histogram 
    cv::Mat hist; 
    int channels[] = {0}; 

    // create matrix for histogram visualization 
    int const hist_height = 256; 
    cv::Mat3b hist_image = cv::Mat3b::zeros(hist_height, bins); 

    cv::calcHist(&image, 1, channels, cv::Mat(), hist, 1, histSize, ranges, true, false); 

    double max_val=0; 
    minMaxLoc(hist, 0, &max_val); 

    // visualize each bin 
    for(int b = 0; b < bins; b++) { 
     float const binVal = hist.at<float>(b); 
     int const height = cvRound(binVal*hist_height/max_val); 
     cv::line 
      (hist_image 
      , cv::Point(b, hist_height-height), cv::Point(b, hist_height) 
      , cv::Scalar::all(255) 
      ); 
    } 
    cv::imshow(name, hist_image); 
} 

int main (int argc, const char* argv[]) 
{ 
    // here you can use cv::IMREAD_GRAYSCALE to load grayscale image, see image2 
    cv::Mat3b const image1 = cv::imread("C:\\workspace\\horse.png", cv::IMREAD_COLOR); 
    cv::Mat1b image1_gray; 
    cv::cvtColor(image1, image1_gray, cv::COLOR_BGR2GRAY); 
    cv::imshow("image1", image1_gray); 
    show_histogram("image1 hist", image1_gray); 

    cv::Mat1b const image2 = cv::imread("C:\\workspace\\bunny.jpg", cv::IMREAD_GRAYSCALE); 
    cv::imshow("image2", image2); 
    show_histogram("image2 hist", image2); 

    cv::waitKey(); 
    return 0; 
} 

結果:

enter image description here

+0

非常感謝很多朋友......對不起,如果我含糊不清,但你給了我正在尋找的東西......再次感謝。 – user2236862

+2

請接受答案。謝謝。 – brotherofken