调整图像亮度和对比度(像素级操作)
- 邻域操作: 区域
- point点操作:像素变换
- 是增益变量
- 亮度就是像素值, 值越大越亮
- 对比度就是差值
- 常用相关API
- Mat dst = Mat::zeros(src.size(), src.type()):
- saturate_cast<uchar>(value)
- 确保像素值大小在0~255
- 是就返回该值, 否就返回0
- Mat.at<Vec3b>(y,x)[index]
- 获取像素点第index通道的值
- Mat.at<Vec3b>(y,x)[index] = value 赋值
#include "pch.h"
#include <iostream>
#include <opencv2/opencv.hpp>
#include <string>
using namespace std;
int main(int argc, char ** argv)
{
using namespace cv;
Mat src0, src1;
src0 = imread("C:\\Users\\xujin\\Desktop\\test0.JPG");
if (!src0.data)
{
cout << "no image";
return -1;
}
namedWindow("src0_image", WINDOW_AUTOSIZE);
imshow("src0_image", src0);
src1 = imread("C:\\Users\\xujin\\Desktop\\test1.JPG");
if (!src1.data)
{
cout << "no image";
return -1;
}
namedWindow("src1_image", WINDOW_AUTOSIZE);
imshow("src1_image", src1);
//调整亮度
Mat dst = src0.clone();
namedWindow("dst_image", WINDOW_AUTOSIZE);
imshow("dst_image", dst);
//对dst对象进行像素级操作
int height = dst.rows;
int width = dst.cols;
float alpha = 1.2;
float beta = 123;
for (int row = 0; row < height; row++)
{
for (int col = 0; col < width; col++)
{
if (dst.channels() == 3)
{
float b = dst.at<Vec3b>(row, col)[0]; //如果图片不是3f的数据,则必然error,所以要先转换成3f数据
float g = dst.at<Vec3b>(row, col)[1];
float r = dst.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 (dst.channels() == 1)
{
float piexl = dst.at<uchar>(row, col);
dst.at<Vec3f>(row, col) = saturate_cast<uchar>(piexl*alpha + beta);
}
else
{
cout << "channels error" << endl;
return -1;
}
}
}
string output = "output";
namedWindow(output, WINDOW_AUTOSIZE);
imshow(output, dst);
waitKey(0);
return 0;
}