使用C++版opencv,如何给图像设置统一的亮度和对比度
时间: 2023-12-27 08:02:25 浏览: 142
要给图像设置统一的亮度和对比度,可以使用以下代码:
```c++
cv::Mat image = cv::imread("image.jpg");
double alpha = 1.5; // 对比度增益
int beta = 50; // 亮度增益
cv::Mat new_image = cv::Mat::zeros(image.size(), image.type());
// 应用亮度和对比度调整
image.convertTo(new_image, -1, alpha, beta);
```
在上面的代码中,我们首先读取了一张图像,然后设置了对比度增益和亮度增益。接着我们创建了一个新的图像 `new_image`,并且使用 `convertTo` 函数将像素值转换为指定的数据类型,同时应用亮度和对比度的调整。
注意,上述代码中的 `convertTo` 函数第一个参数指定了输出图像的数据类型,如果需要输出灰度图像,可以将其设置为 `CV_8UC1`。第二个参数指定了输出图像的通道数,如果输入图像是灰度图像,可以将其设置为 `-1`。
相关问题
使用C++版opencv,如何给图像设置亮度和对比度
要给图像设置亮度和对比度,可以使用以下代码:
```c++
cv::Mat image = cv::imread("image.jpg");
double alpha = 1.5; // 对比度增益
int beta = 50; // 亮度增益
cv::Mat new_image = cv::Mat::zeros(image.size(), image.type());
// 应用亮度和对比度调整
for (int y = 0; y < image.rows; ++y) {
for (int x = 0; x < image.cols; ++x) {
for (int c = 0; c < image.channels(); ++c) {
new_image.at<cv::Vec3b>(y, x)[c] = cv::saturate_cast<uchar>(alpha * image.at<cv::Vec3b>(y, x)[c] + beta);
}
}
}
```
在上面的代码中,我们首先读取了一张图像,然后设置了对比度增益和亮度增益。接着我们创建了一个新的图像 `new_image`,并且使用 `saturate_cast` 函数将像素值转换为 8 位无符号整数。最后,我们将亮度和对比度的调整应用到每个像素上。
注意,上述代码只适用于彩色图像,如果要处理灰度图像,需要将代码中的 `cv::Vec3b` 换成 `uchar`。
用c++结合OpenCV库实现调整图片亮度和对比度的算法
可以使用以下代码来调整图片的亮度和对比度:
```
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main(int argc, char** argv)
{
// 读入图像
Mat image = imread("image.jpg");
// 创建窗口
namedWindow("Original Image");
namedWindow("Adjusted Image");
// 显示原始图像
imshow("Original Image", image);
// 调整亮度和对比度
Mat adjusted;
image.convertTo(adjusted, -1, 1.2, 50); // 参数分别为:输出图像、输出图像的深度、亮度系数、对比度系数
// 显示调整后的图像
imshow("Adjusted Image", adjusted);
waitKey(0);
return 0;
}
```
其中,`image.convertTo` 函数用于调整图像的亮度和对比度。该函数的第一个参数是输出图像,第二个参数是输出图像的深度,第三个参数是亮度系数,第四个参数是对比度系数。
注意:在使用 OpenCV 库之前,需要先在程序中包含头文件 `#include <opencv2/opencv.hpp>`。
阅读全文
相关推荐














