Note
以下解释节选自Richard Szeliski所著 Computer Vision: Algorithms and Applications
#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;
}
一上来,我们要建立两个变量,以存储用户输入的 和 :
double alpha;
int beta;
然后,用 imread 载入图像,并将其存入一个Mat对象:
Mat image = imread( argv[1] );
此时,因为要对图像进行一些变换,所以我们需要一个新的Mat对象,以存储变换后的图像。我们希望这个Mat对象拥有下面的性质:
Mat new_image = Mat::zeros( image.size(), image.type() );
注意到, Mat::zeros 采用Matlab风格的初始化方式,用 image.size() 和 image.type() 来对Mat对象进行0初始化。
现在,为了执行运算 ,我们要访问图像的每一个像素。因为是对RGB图像进行运算,每个像素有三个值(R、G、B),所以我们要分别访问它们。下面是访问像素的代码片段:
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(0);
Note
我们可以不用 for 循环来访问每个像素,而是直接采用下面这个命令:
image.convertTo(new_image, -1, alpha, beta);
这里的 convertTo 将执行我们想做的 new_image = a*image + beta 。然而,我们想展现访问每一个像素的过程,所以选用了for循环的方式。实际上,这两种方式都能返回同样的结果。
运行代码,取参数 和
$ ./BasicLinearTransforms lena.jpg
Basic Linear Transforms
-------------------------
* Enter the alpha value [1.0-3.0]: 2.2
* Enter the beta value [0-100]: 50
我们将得到下面的结果:
loveisp@OpenCV中文网站 <loveispdvd [at] gmail.com>