Pou*_*yan 2 c++ opencv image-processing
这是更改图像对比度和亮度的简单程序。我注意到,还有另一个程序,但有一个简单的区别:saturate_cast已添加到代码中。而且我不知道执行此操作的原因是什么,并且无需转换为无符号字符,或者uchar两个代码(使用saturate_cast<uchar>和不使用此代码)都输出相同的结果。我感谢任何人的帮助。
这是代码:
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <iostream>
#include "Source.h"
using namespace cv;
double alpha;
int beta;
int main(int, char** argv)
{
/// Read image given by user
Mat image = imread(argv[1]);
Mat image2 = Mat::zeros(image.size(), image.type());
/// Initialize values
std::cout << " Basic Linear Transforms " << std::endl;
std::cout << "-------------------------" << std::endl;
std::cout << "* Enter the alpha value [1.0-3.0]: ";std::cin >> alpha;
std::cout << "* Enter the beta value [0-100]: "; std::cin >> beta;
for (int x = 0; x < image.rows; x++)
{
for (int y = 0; y < image.cols; y++)
{
for (int c = 0; c < 3; c++)
{
image2.at<Vec3b>(x, y)[c] =
saturate_cast<uchar>(alpha*(image.at<Vec3b>(x, y)[c]) + beta);
}
}
/// Create Windows
namedWindow("Original Image", 1);
namedWindow("New Image", 1);
/// Show stuff
imshow("Original Image", image);
imshow("New Image", image2);
/// Wait until user press some key
waitKey();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
由于表达式的结果可能超出的有效范围uchar,即[0,255],最好始终使用saturate_cast。
在您的情况下,表达式:的结果alpha*(image.at<Vec3b>(x, y)[c]) + beta是双精度型,因此使用它来更saturate_cast<uchar>正确地钳位值更安全。
同样,由于可以很容易地看出您想要uchar表达式之外,因此可以提高可读性。
如果不使用saturate_cast,则可能会有意外的值:
uchar u1 = 257; // u1 = 1, why a very bright value is set to almost black?
uchar u2 = saturate_cast<uchar>(257); // u2 = 255, a very bright value is set to white
Run Code Online (Sandbox Code Playgroud)