1.介绍
对于图像的对比度和亮度的调整,我不多介绍了,这都是基本功,主要是根据公式dst = alpha * src + beta(alpha控制对比度,beta控制亮度)。对于它的实现方法,其实有多种,比如for循环遍历(无上下文依赖关系,可用SSE来优化)、查表法(输出在0-255之间)和本文的猪脚convertTo。
2.代码
#include<opencv2\opencv.hpp>
#include<iostream>
using namespace std;
using namespace cv;
double alpha = 1;
double beta = 50;
void changeContrastAndBright(const Mat& src, Mat& dst) {
for (int i = 0; i < src.rows; i++)
{
for (int j = 0; j < src.cols; j++)
{
for (int k = 0; k < 3; k++)
{
dst.at<Vec3b>(i, j)[k] =
saturate_cast<uchar>(alpha*(src.at<Vec3b>(i, j)[k]) + beta);
}
}
}
}
int main() {
Mat src = imread("test.png");
Mat dst1;
Mat dst2 = Mat::zeros(src.size(), src.type());
double time0 = static_cast<double>(getTickCount());
changeContrastAndBright(src, dst2);
time0 = ((double)getTickCount() - time0) / getTickFrequency();
cout << "直接遍历方法运行时间为:" << time0 << "秒" << endl;
time0 = static_cast<double>(getTickCount());
src.convertTo(dst1, src.type(), alpha, beta);
time0 = ((double)getTickCount() - time0) / getTickFrequency();
cout << "convertTo方法运行时间为:" << time0 << "秒" << endl;
imshow("src", src);
imshow("dst1", dst1);
imshow("dst2", dst2);
waitKey();
return 0;
}
Debug和Release下运行,都表明convertTo法比较快
3.扩展应用
convertTo实现的功能就是dst = alpha * src + beta,比如进行反色也是可以的,和这个有得一拼:Opencv之高效函数LUT,建议读者也看看。
来源:https://blog.csdn.net/u013289254/article/details/102759759