图像亮度对比度
图像变换
- 像素变换——点操作
- 邻域变换——区域操作
调整图像的亮度对比度属于点操作
g
(
i
,
j
)
=
α
∗
f
(
i
,
j
)
+
β
g(i, j) = \alpha*f(i, j) + \beta
g(i,j)=α∗f(i,j)+β
其中,
α
>
0
\alpha>0
α>0, 用于调节对比度,
α
\alpha
α越大,对比度越大;
β
\beta
β是增益变量,用于调节亮度,
β
\beta
β越大,亮度越大
代码如下:
#include<iostream>
#include<opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main() {
Mat src, dst;
src = imread("F:/tupian/1.jpg");
if (!src.data) {
cout << "could not load ..." << endl;
return -1;
}
char input_win[] = "input image";
// BGR转变为灰度图
// cvtColor(src, src, CV_BGR2GRAY);
namedWindow(input_win, CV_WINDOW_AUTOSIZE);
imshow(input_win, src);
int height = src.rows;
int width = src.cols;
// 创建一张与原图像大小和类型一致的空白图像,像素值初始化为0
dst = Mat::zeros(src.size(), src.type());
float alpha = 1.2;
float beta = 30;
// Mat ml;
// 转变为32f
// src.convertTo(ml, CV_32F);
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];
// float b = ml.at<Vec3f>(row, col)[0];
// float g = ml.at<Vec3f>(row, col)[1];
// float r = ml.at<Vec3f>(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);
}
}
}
char output_title[] = "contrast and brightness change demo";
namedWindow(output_title, CV_WINDOW_AUTOSIZE);
imshow(output_title, dst);
waitKey(0);
return 0;
}