一、前言
做图像处理相关项目时,有时候需要大量的图像样本,然而通过网络搜集得到的图像集属性参差不齐,需要经过转换才能得到一个规范的数据样本,本文内容是通过在VS平台利用程序代码实现对图像集属性的批量更改(将BGR图像转为灰度图像、以及更改尺寸)。
二、程序代码
软件环境:WIN10系统、VS2012开发平台、OpenCV3
BatchBgrConvertGray.h文件包含函数声明
#ifndef BATCHBGRCONVERTGRAY_H_
#define BATCHBGRCONVERTGRAY_H_
#include <opencv2/contrib/contrib.hpp>
#include <iostream>
using namespace std;
bool get_filelist_from_dir(string path,vector<string>& files);
bool BatchBgrConvertGray(string srcPath,string srcFormat,char dstPath[]);
bool BatchBgrConvertGray(string srcPath,string srcFormat,char dstPath[],int width,int height);
#endif
BatchBgrConvertGray.cpp文件是函数的具体实现
#include "BatchBgrConvertGray.h"
#include <iostream>
#include <io.h>
#include <opencv2/contrib/contrib.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <cv.h>
using namespace std;
bool get_filelist_from_dir(string path,vector<string>& files)
{
long hFile=0;
struct _finddata_t fileinfo;
files.clear();
if((hFile =_findfirst(path.c_str(),&fileinfo))!=-1){
do{
if(!(fileinfo.attrib &_A_SUBDIR))
files.push_back(fileinfo.name);
}while(_findnext(hFile,& fileinfo)==0);
_findclose(hFile);
return true;
}
else
return false;
}
/*
*函数功能:将BGR图像批量转化为灰度图像
*输入参数:源图像路径、源图像格式、目标图像存储路径
*输出:灰度图像
*/
bool BatchBgrConvertGray(string srcPath,string srcFormat,char dstPath[]){
string file_path =srcPath;
string search_path=file_path +srcFormat;
vector<string>file_list;
if(!get_filelist_from_dir(search_path,file_list))
cout<<"open file error!"<<endl;
char filename[200];
for(int i=0;i< file_list.size();i++)
{
string image_path=file_path +file_list[i];
cv::Mat image=cv::imread(image_path);
cv::Mat dstImage;
cv::Mat outImage;
cv::cvtColor(image,dstImage,CV_BGR2GRAY);
sprintf_s(filename,dstPath,i+1);
cv::imwrite(filename,dstImage);
}
return true;
}
/*
*函数功能:将BGR图像批量转化为灰度图像并改变图像大小
*输入参数:源图像路径、源图像格式、目标图像存储路径、目标图像宽、目标图像高
*输出:改变尺寸后的灰度图像
*/
bool BatchBgrConvertGray(string srcPath,string srcFormat,char dstPath[],int width,int height){
string file_path =srcPath;
string search_path=file_path +srcFormat;
vector<string>file_list;
if(!get_filelist_from_dir(search_path,file_list))
cout<<"open file error!"<<endl;
char filename[200];
for(int i=0;i< file_list.size();i++)
{
string image_path=file_path +file_list[i];
cv::Mat image=cv::imread(image_path);
cv::Mat dstImage;
cv::Mat outImage;
cv::cvtColor(image,dstImage,CV_BGR2GRAY);
cv::resize(dstImage,outImage,cv::Size(width,height),0,0,CV_INTER_AREA);
sprintf_s(filename,dstPath,i+1);
cv::imwrite(filename,outImage);
}
return true;
}
main.cpp文件调用函数进行测试
#include "BatchBgrConvertGray.h"
#include <iostream>
using namespace std;
int main(){
string file_path ="SrcImage/";
string search_path = "*.jpg";
char dst_path[] ="OutImage/%d.jpg";
if(BatchBgrConvertGray(file_path,search_path,dst_path))
cout<<"The photos of BGR batchly convert to Gray is successful!"<<endl;
return 0;
}
提示:源图像或者目标图像存储文件夹如果是工程文件同级目录下可以使用相对路径,如果是其他区域需要使用绝对路径。