2017-01-26 104 views
0

这是一个简单的程序来改变图像的对比度和亮度。我注意到有一个简单的差异程序:saturate_cast被添加到代码中。 而我不知道这样做的原因是什么,没有必要转换为无符号字符或uchar这两个代码(与saturate_cast<uchar>和不使用此)正在输出相同的结果。我很感激,如果有人帮助。使用saturate_cast或不使用

这是代码:

#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; 
} 
+0

'阿尔法*(image.at (X,Y)[C])+ beta'不再是一个'uchar',并且可以超出范围[0,255]。因此,使用'saturate_cast'来正确地限制结果值 – Miki

+0

外出的原因是什么? –

+0

'2.0 *(255 + 4)'在 – Miki

回答

4

因为你的表达可能会超出有效范围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