opencv 笔记05Core_Change

来源:互联网 发布:申请域名的网站 编辑:程序博客网 时间:2024/05/08 15:30
#include <opencv2/core/core.hpp>#include <opencv2/highgui/highgui.hpp>#include <iostream>using namespace std;using namespace cv;double alpha; /**< 控制对比度 */int beta;  /**< 控制亮度 */int main( int argc, char** argv ){    /// 读入用户提供的图像    Mat image = imread( argv[1] );    Mat new_image = Mat::zeros( image.size(), image.type() );    /// 初始化    cout << " Basic Linear Transforms " << endl;    cout << "-------------------------" << endl;    cout << "* Enter the alpha value [1.0-3.0]: ";    cin >> alpha;    cout << "* Enter the beta value [0-100]: ";    cin >> beta;    /// 执行运算 new_image(i,j) = alpha*image(i,j) + beta    for( int y = 0; y < image.rows; y++ )    {        for( int x = 0; x < image.cols; x++ )        {            for( int c = 0; c < 3; c++ )            {                new_image.at<Vec3b>(y,x)[c] = saturate_cast<uchar>( alpha*( image.at<Vec3b>(y,x)[c] ) + beta );            }        }    }    /// 创建窗口    namedWindow("Original Image", 1);    namedWindow("New Image", 1);    /// 显示图像    imshow("Original Image", image);    imshow("New Image", new_image);    /// 等待用户按键    waitKey();    return 0;}
  • 为了访问图像的每一个像素,我们使用这一语法: image.at<Vec3b>(y,x)[c] 其中, y 是像素所在的行, x 是像素所在的列, c是R、G、B(0、1、2)之一。
  • 因为 \alpha \cdot p(i,j) + \beta 的运算结果可能超出像素取值范围,还可能是非整数(如果 \alpha 是浮点数的话),所以我们要用 saturate_cast对结果进行转换,以确保它为有效值。

Note

 

我们可以不用 for 循环来访问每个像素,而是直接采用下面这个命令:

image.convertTo(new_image, -1, alpha, beta);

convertTo 将执行我们想做的 new_image = a*image + beta 。然而,我们想展现访问每一个像素的过程,所以选用了for循环的方式。实际上,这两种方式都能返回同样的结果。

原创粉丝点击