对文件夹下所有图像做灰度转换,并做garma校正,产生不同的灰度亮度范围,方案用(13-14)
#pragma once
#include<stdio.h>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/core/core.hpp>
#include <cstdio>
#include <string>
#include <iostream>
#include <stdint.h>
#include "opencv2/core.hpp"
#include <opencv2/opencv.hpp>
#include <math.h>
#include <io.h>
using namespace std;
using namespace cv;
#ifdef _DEBUG
#pragma comment(lib,"opencv_world340d.lib")
#else
#pragma comment(lib,"opencv_world340.lib")
#endif
/*
1.读取整个文件夹中的所有图像
2.做灰度化处理,设置不同的灰度化方案,效果是,亮度不同
3.写入到不同的文件夹,文件夹命名不同
*/
void getFiles(string path, vector<string>& files)
{
intptr_t hFile = 0;//intptr_t和uintptr_t是什么类型:typedef long int/ typedef unsigned long int
struct _finddata_t fileinfo;
string p;
if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1)//assign方法可以理解为先将原字符串清空,然后赋予新的值作替换。
{
do
{
if ((fileinfo.attrib & _A_SUBDIR))//是否为文件夹
{
if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
getFiles(p.assign(path).append("\\").append(fileinfo.name), files);//子文件夹下递归访问
}
else//非文件夹
{
files.push_back(p.assign(path).append("\\").append(fileinfo.name));
}
} while (_findnext(hFile, &fileinfo) == 0);
_findclose(hFile);
}
}
void MyGammaCorrection(Mat& src, Mat& dst, float fGamma)
{
CV_Assert(src.data);
// accept only char type matrices
CV_Assert(src.depth() != sizeof(uchar));
// build look up table
unsigned char lut[256];
for (int i = 0; i < 256; i++)
{
lut[i] = saturate_cast<uchar>(pow((float)(i / 255.0), fGamma) * 255.0f);
}
dst = src.clone();
const int channels = dst.channels();
switch (channels)
{
case 1:
{
MatIterator_<uchar> it, end;
for (it = dst.begin<uchar>(), end = dst.end<uchar>(); it != end; it++)
//*it = pow((float)(((*it))/255.0), fGamma) * 255.0;
*it = lut[(*it)];
break;
}
case 3:
{
MatIterator_<Vec3b> it, end;
for (it = dst.begin<Vec3b>(), end = dst.end<Vec3b>(); it != end; it++)
{
(*it)[0] = lut[((*it)[0])];
(*it)[1] = lut[((*it)[1])];
(*it)[2] = lut[((*it)[2])];
}
break;
}
}
}
void RGBtoGray(string gallery_path, string form)
{
vector<string> gallery_folders;
getFiles(gallery_path, gallery_folders);
int nameNUM = 0;
vector<string> image_list;
for (int g = 0; g < gallery_folders.size(); g++)
{
if (gallery_folders[g].substr(gallery_folders[g].find_last_of(".") + 1) == form)
{//获取文件夹下指定格式(如jpg格式)的文件的路径(全路径)
Mat src, OutMat;
src = cv::imread(gallery_folders[g]);
cv::cvtColor(src, src, CV_BGR2GRAY);//彩色转灰度
MyGammaCorrection(src, src,1.0);
vector<Mat> vHls;
vHls.push_back(src);
vHls.push_back(src);
vHls.push_back(src);
merge(vHls, OutMat);//输出要求依然是三通道,所以,构建一个三通道都是灰度图像的新图像
imwrite(gallery_folders[g], OutMat);//写入到当前项目目录下
}
}
cout << "over";
}
调用方法:
void main()
{
//获得E:\\vincen\\OSG\\原始资料\\数据资料\\启明模型\\Models下面所有“jpg”格式文件,并做灰度转换和garma校正
RGBtoGray("E:\\vincen\\OSG\\原始资料\\数据资料\\启明模型\\Models", "jpg");
}