前言
通过滑块调整图像的对比度和亮度。输出图像像素 = 对比度参数 * 原图像像素 +亮度参数 。通过两个花开改变两个参数进行调节。
一、使用步骤
1.主函数
代码如下(示例):
#include <iostream>
#include<opencv2/opencv.hpp>
#define _CRT_SECURE_NO_WARNINGS
using namespace std;
using namespace cv;
const int MaxValueIntensity = 300;
const int MaxValueContrast = 200;
int Intensity = 20; //对比度参数
int Contrast = 20;
void On_Intensity(int, void*);
Mat Img;
int main() {
Mat Img2, Img3, HSV, Imgs[3], HSV0, HSV1, HSV2, Im_color;
char IntensityControl[50]; //滑块字符
char ContrastControl[50]; //滑块字符
//加载图片
Img = imread("D:/test/homework/1.jpg");
Img2 = imread("D:/test/homework/2.bmp");
Img3 = imread("D:/test/homework/3.jpg", IMREAD_GRAYSCALE);
//创建串口
namedWindow("ImgWindow", WINDOW_AUTOSIZE);
sprintf_s(IntensityControl, "IntensityControl:%d", MaxValueIntensity);
sprintf_s(ContrastControl, "ContrastControl:%d", MaxValueContrast);
//创建滑块
createTrackbar(IntensityControl, "ImgWindow", &Intensity, MaxValueIntensity, On_Intensity);
createTrackbar(ContrastControl, "ImgWindow", &Contrast, MaxValueContrast, On_Intensity);
//将rgb图片转换为HSB图片
cvtColor(Img2, HSV, COLOR_BGR2HSV);
//将三通道图片进行分割为三个单通道
split(HSV, Imgs);
//单通道显示
HSV0 = Imgs[0];
HSV1 = Imgs[1];
HSV2 = Imgs[2];
//三通道合并
applyColorMap(Img3, Im_color, COLORMAP_JET);
waitKey(0);
return 0;
}
2.对比度回调函数
void On_Intensity(int, void*)
{
int height = Img.rows; //行数
int width = Img.cols; //列数
Mat dst = Mat::zeros(Img.size(), Img.type());
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
dst.at<Vec3b>(y, x)[0] = saturate_cast<uchar>((1.0 * Intensity / 100) * Img.at<Vec3b>(y, x)[0] + Contrast);//红色
dst.at<Vec3b>(y, x)[1] = saturate_cast<uchar>((1.0 * Intensity / 100) * Img.at<Vec3b>(y, x)[1] + Contrast);//绿色
dst.at<Vec3b>(y, x)[2] = saturate_cast<uchar>((1.0 * Intensity / 100) * Img.at<Vec3b>(y, x)[2] + Contrast);//蓝色
}
}
imshow("ImgWindow",dst);
}
3. 亮度回调函数
void On_Contrast(int, void*)
{
int height = Img.rows; //行数
int width = Img.cols; //列数
Mat dst = Mat::zeros(Img.size(), Img.type());
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
dst.at<Vec3b>(y, x)[0] = saturate_cast<uchar>((1.0 * Intensity / 100) * Img.at<Vec3b>(y, x)[0] + Contrast);//红色
dst.at<Vec3b>(y, x)[1] = saturate_cast<uchar>((1.0 * Intensity / 100) * Img.at<Vec3b>(y, x)[1] + Contrast);//绿色
dst.at<Vec3b>(y, x)[2] = saturate_cast<uchar>((1.0 * Intensity / 100) * Img.at<Vec3b>(y, x)[2] + Contrast);//蓝色
}
}
imshow("ImgWindow", dst);
}
总结
图像入门