montage源码
#include <opencv2/opencv.hpp>
#include <iostream>
#include <vector>
#include <cstdio>
#include <cstring>
using namespace cv;
using namespace std;
int main(int argc, char const* argv[])
{
int image_count = 39;
Mat srcImage = imread("E:/cat_data/xihu1.jpg");
cout << srcImage.size() << endl;
resize(srcImage, srcImage, Size(1920, 1080));
cout << srcImage.size() << endl;
vector<Mat> source_images;
char filenames[30];
for (int i = 1; i <= 39; i++)
{
Mat src_img;
sprintf_s(filenames, "E:/cat_data/cat%d.jpg", i);
src_img = imread(filenames);
resize(src_img, src_img, Size(30, 30), 0, 0, INTER_NEAREST);
source_images.push_back(src_img);
}
cout << source_images.size() << endl;
imshow("first", source_images[2]);
int width = 1920;
int height = srcImage.rows;
Mat montageImage;
resize(srcImage, montageImage, Size(1920, 1080));
int bins = 128;
int hist_sizes[] = { bins, bins, bins };
float range[] = { 0,255 };
const float* ranges[] = { range, range, range };
int channels[] = { 0, 1, 2 };
vector<MatND> hist_list;
for (int i = 0; i < image_count; i++)
{
MatND hist_RGB;
Mat frame;
source_images[i].copyTo(frame);
calcHist(&frame, 1, channels, Mat(), hist_RGB, 3, hist_sizes, ranges, true, false);
hist_list.push_back(hist_RGB);
}
int number_order = 0;
for (int y = 0; y < height; y = y + 30)
{
for (int x = 0; x < width; x = x + 30)
{
Mat roiImage = montageImage(Rect(x, y, 30, 30));
MatND hist_roi;
double match_max = 0.0;
calcHist(&roiImage, 1, channels, Mat(), hist_roi, 3, hist_sizes, ranges, true, false);
for (int i = 0; i < image_count; i++)
{
double match = 0;
match = compareHist(hist_roi, hist_list[i], HISTCMP_CORREL);
if (match > match_max)
{
number_order = i;
match_max = match;
}
}
source_images[number_order].copyTo(roiImage);
printf_s("正在生成中:\033[01;32m %.2f%% \r", (y / (double)1080 + x / (double)1920 / 100) * 100);
fflush(stdout);
}
}
Mat dstImage;
addWeighted(montageImage, 0.2, srcImage, 0.8, 3, dstImage);
imwrite("dstImage.jpg", dstImage);
imshow("montage", dstImage);
waitKey(0);
return (0);
}
效果图
![](https://i-blog.csdnimg.cn/blog_migrate/15fa9b26b65a8bb9874b72b0382ff9f0.png)