一 理论:
图像变换有两种操作:
1:点操作 – 像素变换
2:区域操作 --邻域像素操作,图像周围的像素操作
调整图像亮度和对比度属于像素变换的点操作。
g
(
x
,
y
)
=
α
f
(
x
,
y
)
+
β
g(x,y)=\alpha f(x,y) + \beta
g(x,y)=αf(x,y)+β
其
中
系
数
α
>
0
,
β
是
增
益
值
其中 系数 \alpha \gt0 , \beta 是增益值
其中系数α>0,β是增益值
说明:alpha值越大,像素之间的差值越大,对比度越强烈。 beta值是用于提高图片亮度增益值
二 演示:
代码:
static void Main(string[] args)
{
string imagePath = @"C:\Users\whx\Desktop\opcvImage\m3.jpg";
Funtion1(imagePath);
}
public static void Funtion1(string path)
{
//读入的图像是RGB 但是像素顺序是BGR
using (Mat src = Cv2.ImRead(path, ImreadModes.AnyColor | ImreadModes.AnyDepth))
using (Mat dst = new Mat(src.Size(),src.Type()))
{
int height = src.Rows;
int width = src.Cols;
int cn = src.Channels(); //通道数
float alpha = 1.2f; //系数
float beta = 60f; //增益
for (int row = 0; row < height; row++)
{
for (int col = 0; col < width; col++)
{
if(cn==1)
{
float color = src.At<float>(row, col);
dst.Set<float>(row, col, color);
}
else if(cn==3)
{
Vec3b color = new Vec3b
{
Item0 = (byte)Saturate.Saturate_cast((src.At<Vec3b>(row, col).Item0) * alpha + beta), //B
Item1 = (byte)Saturate.Saturate_cast((src.At<Vec3b>(row, col).Item1) * alpha + beta), //G
Item2 = (byte)Saturate.Saturate_cast((src.At<Vec3b>(row, col).Item2) * alpha + beta) //R
};
//Vec3f:也可以 要转换 src.ConvertTo(src, MatType.CV_32F); //转换后 Vec3f float类型 C# 报错 ,C++ 中可以
//Vec3f color = new Vec3f
//{
// Item0 = Saturate.Saturate_cast((src.At<Vec3f>(row, col).Item0) * alpha + beta), //B
// Item1 = Saturate.Saturate_cast((src.At<Vec3f>(row, col).Item1) * alpha + beta), //G
// Item2 = Saturate.Saturate_cast((src.At<Vec3f>(row, col).Item2) * alpha + beta) //R
//};
dst.Set<Vec3b>(row, col, color);
}
}
}
using(new Window("dst Image",WindowMode.Normal,dst))
using (new Window("src Image", WindowMode.Normal, src))
{
Cv2.WaitKey(0);
}
}
}
输出结果:
对比度和亮度提高很明显。
修改系数 和增益值 float alpha = 1f; float beta = 60f; 再次输出图像
float alpha = 1f; float beta = 60f 对比度没有变化,亮度提高了。可以调整这两个参数来达到预期的效果。