改变图像的对比度和亮度(saturate_cast 防溢出)

http://www.opencv.org.cn/opencvdoc/2.3.2/html/doc/tutorials/core/basic_linear_transform/basic_linear_transform.html#basic-linear-transform

  • 两种常用的点过程(即点算子),是用常数对点进行 乘法加法 运算:

    g(x) = \alpha f(x) + \beta

  • 两个参数 \alpha > 0\beta 一般称作 增益偏置 参数。我们往往用这两个参数来分别控制 对比度亮度

  • 你可以把 f(x) 看成源图像像素,把 g(x) 看成输出图像像素。

因为 \alpha \cdot p(i,j) + \beta 的运算结果可能超出像素取值范围,还可能是非整数(如果 \alpha 是浮点数的话),所以我们要用 saturate_cast 对结果进行转换,以确保它为有效值。

saturate_cast函数的作用就是:限制数据范围为0~255,超过255的值取255,小于0的值取0

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>

using namespace std;
using namespace cv;

double alpha; /**< 控制对比度 */
int beta;  /**< 控制亮度 */

int main()
{
	/// 读入用户提供的图像
	Mat image = imread("C:\\Users\\Win10\\Desktop\\0.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);
			}
		}
	}
	/// 显示图像
	imshow("Original Image", image);
	imshow("New Image", new_image);

	/// 等待用户按键
	waitKey();
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值