#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
// 히스토그램을 계산하고 정규화하는 함수
Mat calcHistNormalized(const Mat &src) {
Mat hsv;
cvtColor(src, hsv, COLOR_BGR2HSV);
// H 채널에 대한 히스토그램 계산
int h_bins = 256; // 히스토그램 빈의 수
int histSize[] = { h_bins };
float h_ranges[] = { 0, 256 };
const float* ranges[] = { h_ranges };
int channels[] = { 0 };
Mat hist;
calcHist(&hsv, 1, channels, Mat(), hist, 1, histSize, ranges, true, false);
// 히스토그램 정규화
normalize(hist, hist, 0, 1, NORM_MINMAX, -1, Mat());
return hist;
}
// 코사인 유사도를 계산하는 함수
double cosineSimilarity(const Mat &hist1, const Mat &hist2) {
return hist1.dot(hist2) / (norm(hist1) * norm(hist2));
}
int main() {
// 이미지 파일을 로드
Mat image1 = imread("image1.jpg");
Mat image2 = imread("image2.jpg");
if (image1.empty() || image2.empty()) {
cout << "Could not open or find the image(s)." << endl;
return -1;
}
// 히스토그램 계산 및 정규화
Mat hist1 = calcHistNormalized(image1);
Mat hist2 = calcHistNormalized(image2);
// 코사인 유사도 계산
double similarity = cosineSimilarity(hist1, hist2);
cout << "Cosine Similarity: " << similarity << endl;
return 0;
}