一.理论部分:
1.图像变换可以看为:a.像素变换——点操作 b.领域操作——区域
2.调整图像亮度和对比度属于像素变换-点操作:
3.主要函数:
(1) Mat new_image = Mat::zeros( image.size(), image.type() ); 创建一张跟原图像大小和类型一致的空白图像、像素值初始化为0
(2) saturate_cast(value)确保值大小范围为0~255之间
(3) Mat.at(y,x)[index]=value 给每个像素点每个通道赋值
二.实现代码
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
int main(int argc, char** argv) {
Mat src, dst;
src = imread("E:/15.JPG");
if (!src.data) {
printf("could not load image...\n");
return -1;
}
char input_win[] = "input image";
//彩色转换为灰度
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 m1;
src.convertTo(m1, CV_32F);
for (int row = 0; row < height; row++) {
for (int col = 0; col < width; col++) {
if (src.channels() == 3) {
float b = m1.at<Vec3f>(row, col)[0];// blue
float g = m1.at<Vec3f>(row, col)[1]; // green
float r = m1.at<Vec3f>(row, col)[2]; // red
// output,给每个像素点每个通道赋值,saturate_cast函数确保值大小在0~255之间
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;
}