本人比较习惯于Opencv1的代码写法,看了最新一本关于Opencv2写法,虽然原理是一样的但是写法差别是很大的,所以我看了Opencv2访问像素写法后就尝试改变为Opencv1代码写法。
下面代码是网上的:修改图片的对比度与亮度代码如下所示,是使用Opencv2代码写法
Mat image = imread("./6.jpg");
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();
下面是我根据原理用Opencv1代码写法:
IplImage *src, *dst;
src = cvLoadImage("./6.jpg");
dst = cvCreateImage(cvGetSize(src), src->depth, src->nChannels);
cvZero(dst);
/// 初始化
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;
for( int x = 0; x < src->width ; x++ )
{
for( int y = 0; y < src->height; y++ )
{
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 );
((uchar *)(dst->imageData + dst->widthStep * y))[x * 3 + c] = saturate_cast<uchar>(alpha*((uchar *)(src->imageData + src->widthStep * y))[x * 3 + c]+beta);
}
}
}
cvNamedWindow("src");
cvNamedWindow("dst");
cvShowImage("src", src);
cvShowImage("dst", dst);
cvWaitKey();
//销毁窗口与释放内存
cvDestroyAllWindows();
cvReleaseImage(&src);
cvReleaseImage(&dst);
return 0;
原图与处理好图如下所示: