Qt+opencv picture brightness adjustment and contrast adjustment
1. Theoretical basis
g(i,j) = alpha * f(i,j) + beta
Among them, i and j represent the i-th row and j-th column of the pixel. g(i,j) is the pixel of the output image, alpha is the contrast control coefficient, and beta is the brightness control coefficient.
Of course, to change some values of pixels, you need to access the pixel values. Opencv provides some methods of pixel access. For 3-channel image pixels, access m_srcMat.at(i,
j)[0] //B
m_srcMat.at(i,j) )[1] //G
m_srcMat.at(i,j)[2] //R
2.Core code
int m_nContrastValue = 100; //对比度值
int m_nBrightValue = 0; //亮度值
Mat m_srcMat,m_dstMat; //原图像、输出图像
void BrightContrast::changeBrightContrast()
{
double alpha = m_nContrastValue*0.01;
int beta = m_nBrightValue;
int ch = m_srcMat.channels();
qDebug("alpha= %lf,beta= %d",alpha,beta);
#if 0
//m_dstMat(i,j) = alpha*m_srcMat(i,j) + beta
for(int row=0;row<m_srcMat.rows;row++)
{
for(int col=0;col<m_srcMat.cols;col++)
{
if(ch == 3)
{
for(int c=0;c<3;c++)
{
m_dstMat.at<Vec3b>(row,col)[c] = saturate_cast<uchar>(alpha*(m_srcMat.at<Vec3b>(row,col)[c]) + beta);
}
}
}
}
#else
m_srcMat.convertTo(m_dstMat, -1, alpha, beta);
#endif
bgrMat2Image(m_dstMat);
}
Two methods are shown here:
Method 1: Use a for loop to operate pixel by pixel.
Method 2: Use the function void convertTo(OutputArray m, int rtype, double alpha=1, double beta=0) const;
m: indicates the output result
rtype: -1 indicates the same as the original image
alpha: scale transformation factor
beta: scale transformation coefficient offset
3. Effect display
I posted the demo link, you can refer to:
https://download.csdn.net/download/haohaohaihuai/12442739
Author: Feima Programmer.
Welcome to technical exchange: QQ: 255895056.
Please indicate the source for reprinting. If there is any inappropriateness, please correct me.