#include <iostream>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

Mat img1, img2, img3, img_result, img_gray1, img_gray2, img_gray3, img_hsv1,img_hsv2,img_hsv3;
MatND img_hist1,img_hist2,img_hist3;

char win1[] = "window1";
char win2[] = "window2";
char win3[] = "window3";
char win4[] = "window4";
char win5[] = "window5";

int threshold_value = 0;
int max_value = 255;
RNG rng(12345);

int Demo_Histogram_Compare();
string convertToString(double d);

int index = 0;

//Remap
int Demo_Histogram_Compare()
{
  img1 = imread("D://images//lion-1.jpg");
  img2 = imread("D://images//lion-4.jpg");
  img3 = imread("D://images//lion-5.jpg");
  if (img1.empty())
  {
    cout << "could not load image..." << endl;
    return 0;
  }
  //imshow(win1, img1);

  cvtColor(img1,img_hsv1,CV_BGR2HSV);
  cvtColor(img2, img_hsv2, CV_BGR2HSV);
  cvtColor(img3, img_hsv3, CV_BGR2HSV);

  int h_bins = 10;
  int s_bins = 12;
  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};

  calcHist(&img_hsv1, 1, channels, Mat(), img_hist1, 2, histSize, ranges, true, false);
  normalize(img_hist1, img_hist1, 0, 1, NORM_MINMAX, -1, Mat());

  calcHist(&img_hsv2, 1, channels, Mat(), img_hist2, 2, histSize, ranges, true, false);
  normalize(img_hist2, img_hist2, 0, 1, NORM_MINMAX, -1, Mat());

  calcHist(&img_hsv3, 1, channels, Mat(), img_hist3, 2, histSize, ranges, true, false);
  normalize(img_hist3, img_hist3, 0, 1, NORM_MINMAX, -1, Mat());

  double img_1_c_1 = compareHist(img_hist1, img_hist1, CV_COMP_INTERSECT);
  double img_1_c_2 = compareHist(img_hist1, img_hist2, CV_COMP_INTERSECT);
  double img_1_c_3 = compareHist(img_hist1, img_hist3, CV_COMP_INTERSECT);
  double img_2_c_3 = compareHist(img_hist2, img_hist3, CV_COMP_INTERSECT);

  img2.copyTo(img_result);
  putText(img1, convertToString(img_1_c_1), Point(50, 50), CV_FONT_HERSHEY_COMPLEX, 1, Scalar(0, 0, 255), 2, LINE_AA);
  putText(img2, convertToString(img_1_c_2), Point(50, 50), CV_FONT_HERSHEY_COMPLEX, 1, Scalar(0, 0, 255), 2, LINE_AA);
  putText(img3, convertToString(img_1_c_3), Point(50, 50), CV_FONT_HERSHEY_COMPLEX, 1, Scalar(0, 0, 255), 2, LINE_AA);
  putText(img_result, convertToString(img_2_c_3), Point(50, 50), CV_FONT_HERSHEY_COMPLEX, 1, Scalar(0, 0, 255), 2, LINE_AA);

  imshow(win1,img1);
  imshow(win2,img2);
  imshow(win3,img3);
  imshow(win4, img_result);
  return 0;
}

string convertToString(double d)
{
  ostringstream os;
  if (os<<d)
  {
    return os.str();
  }
  return "Invalid conversion...";
}

int main()
{
  Demo_Histogram_Compare();

  waitKey(0);
  return 0;
}

Opencv 直方图比较-LMLPHP

05-13 15:43