大宇私人领地伊甸园丨宁愿做了后悔,也不要错过后悔[www.mrdayu.com]
注册

24小时联系邮箱:[email protected]

所有文章
大宇私人伊甸园: 首页 > 所有文章 > 编程人生 > 开源库 > opencv > [001.07]调整图像亮度与对比度

[001.07]调整图像亮度与对比度

发布时间:2018/07/12 opencv 标签opencv阅读:24

调整图像亮度与对比度:

理论:

图像变换可以看作如下:

 像素变换 点操作

 邻域操作 区域

调整图像亮度和对比度属于像素变换点操作

重要的API:

Mat new_image = Mat::zeros( image.size(), image.type() );  创建一张跟原图像大小和类型一致的空白图像、像素值初始化为0

saturate_cast<uchar>(value)确保值大小范围为0~255之间

Mat.at<Vec3b>(y,x)[index]=value 给每个像素点每个通道赋值

实现代码:

测试BGR图片:

#include <opencv2/opencv.hpp>
#include <iostream>

using namespace std;
using namespace cv;

int main(int argc, char **argv) {
	Mat src, ds;
	src = imread("d:/test.jpg");
	if (!src.data) {
		printf("error form open image");
		return -1;
	}
	namedWindow("input");
	imshow("input",src);

	int height = src.rows;
	int weight = src.cols;
	double alpha = 1.2;
	double beat = 50;
	ds = Mat::zeros(src.size(),src.type());
	for (int x = 0; x < height;x++) {
		for (int y = 0; y < weight; y++) {
			if (src.channels() == 3) {
				ds.at<Vec3b>(x, y)[0] = saturate_cast<uchar>(alpha*src.at<Vec3b>(x, y)[0] + beat);
				ds.at<Vec3b>(x, y)[1] = saturate_cast<uchar>(alpha*src.at<Vec3b>(x, y)[1] + beat);
				ds.at<Vec3b>(x, y)[2] = saturate_cast<uchar>(alpha*src.at<Vec3b>(x,y)[2]+beat);
			}
			else if (src.channels() == 1) {
				ds.at<uchar>(x, y) = saturate_cast<uchar>(alpha*src.at<uchar>(x, y) + beat);
			}
		}
	}
	namedWindow("new image");
	imshow("new image",ds);
	waitKey(0);
	return true;
}

测试灰度图:

#include <opencv2/opencv.hpp>
#include <iostream>

using namespace std;
using namespace cv;

int main(int argc, char **argv) {
	Mat src, ds;
	src = imread("d:/test.jpg", IMREAD_GRAYSCALE);
	if (!src.data) {
		printf("error form open image");
		return -1;
	}
	namedWindow("input");
	imshow("input",src);

	int height = src.rows;
	int weight = src.cols;
	double alpha = 1.2;
	double beat = 50;
	ds = Mat::zeros(src.size(),src.type());
	for (int x = 0; x < height;x++) {
		for (int y = 0; y < weight; y++) {
			if (src.channels() == 3) {
				ds.at<Vec3b>(x, y)[0] = saturate_cast<uchar>(alpha*src.at<Vec3b>(x, y)[0] + beat);
				ds.at<Vec3b>(x, y)[1] = saturate_cast<uchar>(alpha*src.at<Vec3b>(x, y)[1] + beat);
				ds.at<Vec3b>(x, y)[2] = saturate_cast<uchar>(alpha*src.at<Vec3b>(x,y)[2]+beat);
			}
			else if (src.channels() == 1) {
				ds.at<uchar>(x, y) = saturate_cast<uchar>(alpha*src.at<uchar>(x, y) + beat);
			}
		}
	}
	namedWindow("new image");
	imshow("new image",ds);
	waitKey(0);
	return true;
}

也可以使用cvtColor:参考:http://www.mrdayu.com/archives/2464.html

结论:

通过此种方法是不是明显能感觉出已经将图片亮度提高了不少,对比度也提高了很多。

The bottom line, for me, is simple.

Let’s hope it doesn’t take 500 years for a discipline of testing to becomes the standard for software developers.

From:dayu
相关推荐

您好!请登录

合作网站快捷登录:
点击取消回复

已有1评论

    大宇博客

    点击这里给我发消息点击这里给我发消息