Opencv3 C++ VS2017 study notes 05 adjust image brightness and contrast

 Adjust image brightness and contrast (pixel level operation)


  • Neighborhood operation: area
    • Feature extraction
    • Image Identification
    • Detection and other applications
  • Point operation: pixel transformation
    • \large \large g\left ( i,j \right )=\alpha f(i.j)+\beta , \alpha >0,\betaIs the gain variable
    • Brightness is the pixel value, the larger the value, the brighter
    • Contrast is the difference
  • Commonly used related API
    • Mat dst = Mat::zeros(src.size(), src.type()):
      • Create a Mat object dst, the same size and type as src
    • saturate_cast<uchar>(value)
      • Make sure the pixel value is 0~255
      • If yes, return the value, if no, return 0
    • Mat.at<Vec3b>(y,x)[index]   
      • Get the value of the index channel of the pixel
      • Mat.at<Vec3b>(y,x)[index] = value assignment
#include "pch.h"
#include <iostream>
#include <opencv2/opencv.hpp>
#include <string>

using namespace std;


int main(int argc, char ** argv)
{
	using namespace cv;
	Mat src0, src1;
	src0 = imread("C:\\Users\\xujin\\Desktop\\test0.JPG");
	if (!src0.data)
	{
		cout << "no image";
		return -1;
	}
	namedWindow("src0_image", WINDOW_AUTOSIZE);
	imshow("src0_image", src0);
	src1 = imread("C:\\Users\\xujin\\Desktop\\test1.JPG");
	if (!src1.data)
	{
		cout << "no image";
		return -1;
	}
	namedWindow("src1_image", WINDOW_AUTOSIZE);
	imshow("src1_image", src1);


	//调整亮度

	Mat dst = src0.clone();
	namedWindow("dst_image", WINDOW_AUTOSIZE);
	imshow("dst_image", dst);

	//对dst对象进行像素级操作
	int height = dst.rows;
	int width = dst.cols;
	float alpha = 1.2;
	float beta = 123;
	
	for (int row = 0; row < height; row++)
	{
		for (int col = 0; col < width; col++)
		{
			if (dst.channels() == 3)
			{
				float b = dst.at<Vec3b>(row, col)[0];    //如果图片不是3f的数据,则必然error,所以要先转换成3f数据
				float g = dst.at<Vec3b>(row, col)[1];
				float r = dst.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 (dst.channels() == 1)
			{
				float piexl = dst.at<uchar>(row, col);
				dst.at<Vec3f>(row, col) = saturate_cast<uchar>(piexl*alpha + beta);
			}
			else
			{
				cout << "channels error" << endl;
				return -1;
			}
		}
	}

	string output = "output";
	namedWindow(output, WINDOW_AUTOSIZE);
	imshow(output, dst);
	waitKey(0);
	return 0;
}

 

Guess you like

Origin blog.csdn.net/Mrsherlock_/article/details/104492365