一、原理及相关API
dst = alpha*src + beta
alpha > 0 控制图像对比度,beta是增益变量,控制图像亮度Mat new_img = Mat::zeros(img.size(),img.type());
创建一张和原图像大小和类型一致的空白图像,像素值初始化为0saturate_cast<uchar>(value)
确保值范围在0~255之间Mat.at<Vec3b>(y,x)[index] = value;
给每个像素点每个通道赋值
二、通过读写像素的方式调整亮度与对比度
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;
int main()
{
Mat src, dst;
src = imread("images/02.png");
if (!src.data) {
cout << "could not load image1..." << endl;
return -1;
}
namedWindow("input_image", CV_WINDOW_AUTOSIZE);
imshow("input_image", src);
int height = src.rows;
int width = src.cols;
dst = Mat::zeros(src.size(), src.type());
float alpha = 1.5;
float beta = 10;
for (int row = 0; row < height; row++)
{
for (int col = 0; col < width; col++)
{
if (src.channels() == 3)
{
float b = src.at<Vec3b>(row, col)[0];
float g = src.at<Vec3b>(row, col)[1];
float r = src.at<Vec3b>(row, col)[2];
dst.at<Vec3b>(row, col)[0] = saturate_cast<uchar>(b * alpha + beta);
dst.at<Vec3b>(row, col)[1] = saturate_cast<uchar>(g * alpha + beta);
dst.at<Vec3b>(row, col)[2] = saturate_cast<uchar>(r * alpha + beta);
}
else if (src.channels() == 1)
{
float v = src.at<uchar>(row, col);
dst.at<uchar>(row, col) = saturate_cast<uchar>(v * alpha + beta);
}
}
}
namedWindow("contrast and brightness images",CV_WINDOW_AUTOSIZE);
imshow("contrast and brightness images", dst);
waitKey();
return 0;
}
三、通过像素指针的方式调整图像亮度与对比度
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;
int main()
{
Mat src, dst;
src = imread("images/02.png");
if (!src.data) {
cout << "could not load image1..." << endl;
return -1;
}
namedWindow("input_image", CV_WINDOW_AUTOSIZE);
imshow("input_image", src);
//通过像素指针的方式调整图像的对比度和亮度
int rows = src.rows;
int cols = src.cols;
int channels = src.channels();
Mat dst(src.size(), src.type());
for(int row=0; row<rows; row++) {
const uchar* currentSrcRow = src.ptr<uchar>(row);
uchar* currentDstRow = dst.ptr<uchar>(row);
for(int col=0; col<cols*channels; col++) {
currentDstRow[col] = saturate_cast<uchar>(alpha * currentSrcRow[col] + beta);
}
}
namedWindow("contrast and brightness images",CV_WINDOW_AUTOSIZE);
imshow("contrast and brightness images", dst);
waitKey();
return 0;
}
来源:CSDN
作者:xinzhihen1998
链接:https://blog.csdn.net/xinzhihen1998/article/details/104146027