请你扮演一个精通opencv的高手,使用opencv写一个c++代码,输入两个彩色图片名称分别为“原始图片.jpg”“待匹配图片.jpg”,完成直方图匹配
时间: 2024-05-21 07:10:09 浏览: 82
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main(int argc, char** argv)
{
//读取原始图片和待匹配图片
Mat srcImg = imread("原始图片.jpg");
Mat matchImg = imread("待匹配图片.jpg");
//将原始图片和待匹配图片转换为灰度图像
Mat srcGray, matchGray;
cvtColor(srcImg, srcGray, COLOR_BGR2GRAY);
cvtColor(matchImg, matchGray, COLOR_BGR2GRAY);
//计算原始图片和待匹配图片的直方图
Mat srcHist, matchHist;
const int histSize = 256;
float range[] = { 0, 256 };
const float* histRange = { range };
calcHist(&srcGray, 1, 0, Mat(), srcHist, 1, &histSize, &histRange);
calcHist(&matchGray, 1, 0, Mat(), matchHist, 1, &histSize, &histRange);
//归一化直方图
normalize(srcHist, srcHist, 0, 1, NORM_MINMAX, -1, Mat());
normalize(matchHist, matchHist, 0, 1, NORM_MINMAX, -1, Mat());
//计算直方图的累积分布函数
Mat srcCDF, matchCDF;
srcCDF = srcHist.clone();
matchCDF = matchHist.clone();
for (int i = 1; i < histSize; ++i)
{
srcCDF.at<float>(i) += srcCDF.at<float>(i - 1);
matchCDF.at<float>(i) += matchCDF.at<float>(i - 1);
}
//进行直方图匹配
Mat lut(1, histSize, CV_8U);
for (int i = 0; i < histSize; ++i)
{
int j = histSize - 1;
while (j >= 0 && matchCDF.at<float>(j) > srcCDF.at<float>(i))
--j;
lut.at<uchar>(i) = saturate_cast<uchar>(j);
}
//应用查找表
Mat result;
LUT(matchGray, lut, result);
//显示结果
namedWindow("Original Image", WINDOW_NORMAL);
namedWindow("Matched Image", WINDOW_NORMAL);
imshow("Original Image", srcImg);
imshow("Matched Image", result);
waitKey(0);
return 0;
}
阅读全文