Histogram method for image similarity calculation OpenCV implementation

Steps:

1. Load the image (grayscale or color) and make it the same size;

2. If it is a color image, add color space transformation, from RGB to HSV, if it is a grayscale image, no conversion is required;

3. If it is a grayscale image, directly calculate its histogram and normalize the histogram;

4. If it is a color image, calculate its color histogram and normalize the color histogram;

5. Calculate the similarity value using similarity formulas such as correlation coefficient, chi-square, intersection or Babbitt distance.

string strSrcImageName = "src.jpg";  
  
cv::Mat matSrc, matSrc1, matSrc2;  
  
matSrc = cv::imread(strSrcImageName, CV_LOAD_IMAGE_UNCHANGED);  
  
cv::resize(matSrc, matSrc1, cv::Size(357, 419), 0, 0, cv::INTER_NEAREST);  
cv::resize(matSrc, matSrc2, cv::Size(2177, 3233), 0, 0, cv::INTER_LANCZOS4);  
  
cv::Mat matDst1, matDst2;  
cv::Size sizeImage = cv::Size(500, 500);   
  
cv::resize(matSrc1, matDst1, sizeImage, 0, 0, cv::INTER_CUBIC);  
//cv::flip(matDst1, matDst1, 1);  
cv::resize(matSrc2, matDst2, sizeImage, 0, 0, cv::INTER_CUBIC);  
  
if (matSrc.channels() == 1) {  
    int histSize = 256;  
    float range[] = {0, 256};  
    const float* histRange = {range};  
    bool uniform = true;  
    bool accumulate = false;  
  
    cv::Mat hist1, hist2;  
  
    cv::calcHist(&matDst1, 1, 0, cv::Mat(), hist1, 1, &histSize, &histRange, uniform, accumulate);  
    cv::normalize(hist1, hist1, 0, 1, cv::NORM_MINMAX, -1, cv::Mat());  
  
    cv::calcHist(&matDst2, 1, 0, cv::Mat(), hist2, 1, &histSize, &histRange, uniform, accumulate);  
    cv::normalize(hist2, hist2, 0, 1, cv::NORM_MINMAX, -1, cv::Mat());  
  
    double dSimilarity = cv::compareHist(hist1, hist2, CV_COMP_CORREL);//,CV_COMP_CHISQR,CV_COMP_INTERSECT,CV_COMP_BHATTACHARYYA  
  
    cout<<"similarity = "<<dSimilarity<<endl;  
} else {  
    cv::cvtColor(matDst1, matDst1, cv::COLOR_BGR2HSV);  
    cv::cvtColor(matDst2, matDst2, cv::COLOR_BGR2HSV);  
  
    int h_bins = 50, s_bins = 60;  
    int histSize[] = {h_bins, s_bins};  
    float h_ranges[] = {0, 180};  
    float s_ranges[] = {0, 256};  
    const float* ranges[] = {h_ranges, s_ranges};  
    int channels[] = {0, 1};  
  
    cv::MatND hist1, hist2;  
  
    cv::calcHist(&matDst1, 1, channels, cv::Mat(), hist1, 2, histSize, ranges, true, false);  
    cv::normalize(hist1, hist1, 0, 1, cv::NORM_MINMAX, -1, cv::Mat());  
  
    cv::calcHist(&matDst2, 1, channels, cv::Mat(), hist2, 2, histSize, ranges, true, false);  
    cv::normalize(hist2, hist2, 0, 1, cv::NORM_MINMAX, -1, cv::Mat());  
  
    double dSimilarity = cv::compareHist(hist1, hist2, CV_COMP_CORREL);  
  
    cout<<"similarity = "<<dSimilarity<<endl;  
}  

 

 

 

 

 

 

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324377156&siteId=291194637