在图像处理的过程中,开发一个新的图像分析软件意味着首先能把这些文件读取为能直接访问像素值得内部格式,这些枯燥的工作需要大量的代码,而opencv为我们提供了这些基础设施,让我们有更多得精力集中在图像处理的算法中。
#include<io.h> #include<stdlib.h> #include<stdio.h> #include<iostream> #include<opencv2/opencv.hpp> using namespace cv; using namespace std; Mat creatOne(std::vector<cv::Mat> & images, int cols, int min_gap_size) { //首先找到最大的维度 int max_width = 0; int max_height = 0; for (int i = 0; i < images.size(); i++) { //检查类型是否是正确的 if (i > 0 && images[i].type() != images[i - 1].type()) { cerr << "警告:文件夹错误,不是同一类型的图片"; return cv::Mat(); } max_height = max(max_height, images[i].rows); max_width = max(max_width, images[i].cols); } //在Y方向上的图像数量 int rows = ceil(images.size() / cols); //创建结果矩阵 Mat result = cv::Mat::zeros(rows*max_height + (rows - 1)*min_gap_size,cols*max_width + (cols - 1)*min_gap_size, images[0].type()); size_t i = 0; int current_height = 0; int current_width = 0; for (int y = 0; y < rows; y++) { for (int x = 0; x < cols; x++) { if (i >images.size() - 1) //一般不会发生, 为了安全起见 return result; cv::Mat to(result, Range(current_height, current_height + images[i].rows), Range(current_width, current_width + images[i].cols)); images[i++].copyTo(to); current_width += max_width + min_gap_size; } current_width = 0; current_height += max_height + min_gap_size; } return result; } int main() { //IplImage *desimg, srcimg 1.X 版本的写法 Mat desimg, srcimg; Mat output; vector<Mat> my_images; //文件下加载多张图像 struct _finddata_t c_file; long hFile; char imageDirectory[] = "E:\\C++workspace\\MyProgram\\常用人脸库\\ORL\\ORL"; char imageFileType[] = "bmp"; char buffer[1000]; char fullImagePath[1000]; char str[100]; int i = 0; sprintf_s(buffer, "%s\\*.%s", imageDirectory, imageFileType); hFile =_findfirst(buffer,&c_file); //检查确保文件在文件库 if (hFile == -1L) printf("文件不在当前的文件库\n", imageFileType); else { //列出文件库的所有文件夹 printf("列出所有的文件\n"); // 加载所有的图像 do { _itoa(i + 1, str, 10); string s1(str); // 显示所有的问件名字 printf("\nOpening File: %s \n", c_file.name); sprintf_s(fullImagePath,"%s\\%s", imageDirectory,c_file.name); // 加载图像 // desimg = cvLoadImage(fullImagePath); desimg = imread(fullImagePath); Mat sized_dst =cv::Mat(Size(desimg.cols/2, desimg.rows/2), desimg.type()); resize(desimg,sized_dst,sized_dst.size()); imshow(s1, sized_dst); my_images.push_back(sized_dst); i++; } while (_findnext(hFile, &c_file) == 0); output = creatOne(my_images, 1, 5); imshow("output", output); //imwrite("output.bmp", output); // 关闭 _findclose(hFile); } waitKey(0); return 0; }