更改图像亮度和对比度:
公式:
代码:
1 #include <opencv2\opencv.hpp> 2 #include <iostream> 3 #include <string> 4 5 #pragma comment( linker, "/subsystem:\"windows\" /entry:\"mainCRTStartup\"" ) 6 7 using namespace std; 8 using namespace cv; 9 10 void Show(std::string name,Mat img) 11 { 12 namedWindow(name, CV_WINDOW_AUTOSIZE); 13 imshow(name, img); 14 } 15 16 int main() 17 { 18 Mat img = imread("lena.png"); 19 Mat new_img = Mat::zeros(img.size(), img.type()); 20 21 double alpha = 2.2; 22 int beta = 50; 23 for (int y = 0; y < img.rows; ++y) 24 { 25 for (int x = 0; x < img.cols; ++x) 26 { 27 for (int c = 0; c < 3; ++c) 28 { 29 new_img.at<Vec3b>(y, x)[c] = static_cast<uchar>(alpha*(img.at<Vec3b>(y, x)[c]) + beta); 30 } 31 } 32 } 33 Show("Re", img); 34 Show("Bright", new_img); 35 imwrite("./after/bright.png", new_img); 36 waitKey(); 37 return 0; 38 }
结果:
(不知为何我的结果和示例的不一样,可能计算错误)
其中我们是用
new_img.at<Vec3b>(y, x)[c]
获取通道的值,使用saturate_cast做数据溢出保护;
另外还可以使用较为简便的函数方式直接转换:
1 #include <opencv2\opencv.hpp> 2 #include <iostream> 3 #include <string> 4 5 #pragma comment( linker, "/subsystem:\"windows\" /entry:\"mainCRTStartup\"" ) 6 7 using namespace std; 8 using namespace cv; 9 10 void Show(std::string name,Mat img) 11 { 12 namedWindow(name, CV_WINDOW_AUTOSIZE); 13 imshow(name, img); 14 } 15 16 int main() 17 { 18 Mat img = imread("lena.png"); 19 Mat new_img = Mat::zeros(img.size(), img.type()); 20 double alpha = 2.2; 21 int beta = 50; 22 img.convertTo(new_img, -1, alpha, beta); 23 Show("After", new_img); 24 waitKey(); 25 return 0; 26 }
此时结果就和示例相仿了:
时间: 2024-11-05 01:32:51