图像变换可以看作如下:
-
像素变换 – 点操作
-
邻域操作 – 区域 调整图像亮度和对比度属于像素变换-点操作
Mat new_image = Mat::zeros( image.size(), image.type() ); 创建一张跟原图像大小和类型一致的空白图像、像素值初始化为0
saturate_cast<uchar>(value)确保值大小范围为0~255之间
Mat.at<Vec3b>(y,x)[index]=value 给每个像素点每个通道赋值
#include <opencv2/opencv.hpp>
#include <iostream>
#include <math.h>
using namespace cv;
int main(void) {
Mat src, src2, dst;
src = imread("C:/Users/Robin/Pictures/2.jpg");
src2 = imread("C:/Users/Robin/Pictures/3.jpg");
if (!src.data) {
std::cout << "could not load image1..\n";
return -1;
}
if (!src2.data) {
std::cout << "could not load image2..\n";
return -1;
}
char input_win[] = "input image";
namedWindow(input_win, CV_WINDOW_AUTOSIZE);
imshow(input_win, src);
int height = src.rows;
int width = src.cols;
dst = Mat::zeros(src.size(), src.type());
float alpha = 1.0f;//对比度
float beta = 10;//亮度
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];
float g = m1.at<Vec3f>(row, col)[1];
float r = m1.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 ouput_title[] = "contrast and brightess change";
namedWindow(ouput_title, CV_WINDOW_AUTOSIZE);
imshow(ouput_title, dst);
waitKey(0);
return 0;
}
#include <opencv2/opencv.hpp>
#include <iostream>
#include <math.h>
using namespace cv;
int main(void) {
Mat src, src2, dst;
src = imread("C:/Users/Robin/Pictures/2.jpg");
src2 = imread("C:/Users/Robin/Pictures/3.jpg");
if (!src.data) {
std::cout << "could not load image1..\n";
return -1;
}
if (!src2.data) {
std::cout << "could not load image2..\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;
dst = Mat::zeros(src.size(), src.type());
float alpha = 1.2f;//对比度
float beta = 10.0f;//亮度
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
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 ouput_title[] = "contrast and brightess change";
namedWindow(ouput_title, CV_WINDOW_AUTOSIZE);
imshow(ouput_title, dst);
waitKey(0);
return 0;
}