06 OpenCV调整图像亮度与对比度

三世轮回 提交于 2020-02-03 02:04:26

一、原理及相关API

  • dst = alpha*src + beta alpha > 0 控制图像对比度,beta是增益变量,控制图像亮度
  • Mat new_img = Mat::zeros(img.size(),img.type()); 创建一张和原图像大小和类型一致的空白图像,像素值初始化为0
  • saturate_cast<uchar>(value) 确保值范围在0~255之间
  • Mat.at<Vec3b>(y,x)[index] = value; 给每个像素点每个通道赋值

二、通过读写像素的方式调整亮度与对比度

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

using namespace std;
using namespace cv;

int main()
{
	Mat src, dst;
	src = imread("images/02.png");
	if (!src.data) {
		cout << "could not load image1..." << endl;
		return -1;
	}
	namedWindow("input_image", CV_WINDOW_AUTOSIZE);
	imshow("input_image", src);

	int height = src.rows;
	int width = src.cols;

	dst = Mat::zeros(src.size(), src.type());
	float alpha = 1.5;
	float beta = 10;
	for (int row = 0; row < height; row++)
	{
		for (int col = 0; col < width; col++)
		{
			if (src.channels() == 3)
			{
				float b = src.at<Vec3b>(row, col)[0];
				float g = src.at<Vec3b>(row, col)[1];
				float r = src.at<Vec3b>(row, col)[2];

				dst.at<Vec3b>(row, col)[0] = saturate_cast<uchar>(b * alpha + beta);
				dst.at<Vec3b>(row, col)[1] = saturate_cast<uchar>(g * alpha + beta);
				dst.at<Vec3b>(row, col)[2] = saturate_cast<uchar>(r * alpha + beta);

			}
			else if (src.channels() == 1)
			{
				float v = src.at<uchar>(row, col);
				dst.at<uchar>(row, col) = saturate_cast<uchar>(v * alpha + beta);
			}

		}
	}

	namedWindow("contrast and brightness images",CV_WINDOW_AUTOSIZE);
	imshow("contrast and brightness images", dst);
	waitKey();
	return 0;

}

三、通过像素指针的方式调整图像亮度与对比度

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

using namespace std;
using namespace cv;

int main()
{
	Mat src, dst;
	src = imread("images/02.png");
	if (!src.data) {
		cout << "could not load image1..." << endl;
		return -1;
	}
	namedWindow("input_image", CV_WINDOW_AUTOSIZE);
	imshow("input_image", src);

//通过像素指针的方式调整图像的对比度和亮度
    int rows = src.rows;
    int cols = src.cols;
    int channels = src.channels();
    Mat dst(src.size(), src.type());

    for(int row=0; row<rows; row++) {
        const uchar* currentSrcRow = src.ptr<uchar>(row);
        uchar* currentDstRow = dst.ptr<uchar>(row);
        for(int col=0; col<cols*channels; col++) {
            currentDstRow[col] = saturate_cast<uchar>(alpha * currentSrcRow[col] + beta);
        }
    }

	namedWindow("contrast and brightness images",CV_WINDOW_AUTOSIZE);
	imshow("contrast and brightness images", dst);
	waitKey();
	return 0;

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!