# OpenCV 图像对比度的实践

## 实现原理

1.设置调整参数percent，取值为-100到100，类似PS中设置，归一化后为-1到1。

2.针对图像所有像素点单个处理。当percent大于等于0时，对比增强，调整后的RGB三通道数值为：

3.若percent小于0时，对比降低，此时调整后的图像RGB三通道值为：

4.若percent等于1时，大于thresh则等于255，小于则等于0。

// 对比度
cv::Mat Contrast(cv::Mat src, int percent)
{
float alpha = percent / 100.f;
alpha = max(-1.f, min(1.f, alpha));
cv::Mat temp = src.clone();
int row = src.rows;
int col = src.cols;
int thresh = 127;
for (int i = 0; i < row; ++i)
{
uchar *t = temp.ptr(i);
uchar *s = src.ptr(i);
for (int j = 0; j < col; ++j)
{
uchar b = s[3 * j];
uchar g = s[3 * j + 1];
uchar r = s[3 * j + 2];
int newb, newg, newr;
if (alpha == 1)
{
t[3 * j + 2] = r > thresh ? 255 : 0;
t[3 * j + 1] = g > thresh ? 255 : 0;
t[3 * j] = b > thresh ? 255 : 0;
continue;
}
else if (alpha >= 0)
{
newr = static_cast(thresh + (r - thresh) / (1 - alpha));
newg = static_cast(thresh + (g - thresh) / (1 - alpha));
newb = static_cast(thresh + (b - thresh) / (1 - alpha));
}
else {
newr = static_cast(thresh + (r - thresh) * (1 + alpha));
newg = static_cast(thresh + (g - thresh) * (1 + alpha));
newb = static_cast(thresh + (b - thresh) * (1 + alpha));

}
newr = max(0, min(255, newr));
newg = max(0, min(255, newg));
newb = max(0, min(255, newb));
t[3 * j + 2] = static_cast(newr);
t[3 * j + 1] = static_cast(newg);
t[3 * j] = static_cast(newb);
}
}
return temp;
}

C++测试代码

#include
#include
using namespace cv;
using namespace std;

cv::Mat Contrast(cv::Mat src, int percent);

int main()
{
cv::Mat src = imread("5.jpg");
cv::Mat result = Contrast(src, 50.f);
imshow("original", src);
imshow("result", result);
waitKey(0);
return 0;
}

// 对比度
cv::Mat Contrast(cv::Mat src, int percent)
{
float alpha = percent / 100.f;
alpha = max(-1.f, min(1.f, alpha));
cv::Mat temp = src.clone();
int row = src.rows;
int col = src.cols;
int thresh = 127;
for (int i = 0; i < row; ++i)
{
uchar *t = temp.ptr(i);
uchar *s = src.ptr(i);
for (int j = 0; j < col; ++j)
{
uchar b = s[3 * j];
uchar g = s[3 * j + 1];
uchar r = s[3 * j + 2];
int newb, newg, newr;
if (alpha == 1)
{
t[3 * j + 2] = r > thresh ? 255 : 0;
t[3 * j + 1] = g > thresh ? 255 : 0;
t[3 * j] = b > thresh ? 255 : 0;
continue;
}
else if (alpha >= 0)
{
newr = static_cast(thresh + (r - thresh) / (1 - alpha));
newg = static_cast(thresh + (g - thresh) / (1 - alpha));
newb = static_cast(thresh + (b - thresh) / (1 - alpha));
}
else {
newr = static_cast(thresh + (r - thresh) * (1 + alpha));
newg = static_cast(thresh + (g - thresh) * (1 + alpha));
newb = static_cast(thresh + (b - thresh) * (1 + alpha));

}
newr = max(0, min(255, newr));
newg = max(0, min(255, newg));
newb = max(0, min(255, newb));
t[3 * j + 2] = static_cast(newr);
t[3 * j + 1] = static_cast(newg);
t[3 * j] = static_cast(newb);
}
}
return temp;
}