最近在B站上学习OpenCv教程,学到图像直方图,后者描述的是不同色彩在整幅图像中所占的比例(统计不同色彩在图像中的出现次数),可以对灰度图、彩色图等计算并绘制图像直方图。本文学习OpenCvSharp中与计算直方图相关的函数,并采用SkiaSharp绘制简单的直方图。
新建Winfrom项目,在Nuget包管理器中搜索并安装以下包:
OpenCvSharp4
OpenCvSharp4.Extensions
OpenCvSharp4.Windows
SkiaSharp
SkiaSharp.Views.Forms
SkiaSharp.Views.Forms.WPF
SkiaSharp.Views.WPF
主要使用OpenCvSharp模块中的以下函数处理并计算图像直方图:
1)Cv2.ImRead:从本地加载图像;
2)Cv2.Split:将多通道图像数据集合拆分成单通道图像数据集合;
3)Cv2.CalcHist:计算图像直方图,其函数原型如下所示,各个参数的意义详见参考文献3。
public static void CalcHist(Mat[] images, int[] channels, InputArray? mask, OutputArray hist, int dims, int[] histSize, Rangef[] ranges, bool uniform = true, bool accumulate = false)
4)Cv2.Normalize:对直方图数据进行归一化处理。
以下是主要代码,由于接触OpenCvSharp不多,主要参照参考文献中的示例代码加上个人理解编写的代码,不确定用法是否正确。
Mat image = Cv2.ImRead(picImage.Tag.ToString());
Mat[] channels = Cv2.Split(image);
int channelIndex = -1;
if (rbB.Checked)
{
m_channel = 0;
}
else if (rbG.Checked)
{
m_channel = 1;
}
else if (rbR.Checked)
{
m_channel = 2;
}
m_size = Convert.ToInt32(txtSize.Text);
OpenCvSharp.Rangef range = new OpenCvSharp.Rangef(0, 256);
Mat outputArray = new Mat();
Cv2.CalcHist(channels, new int[] { m_channel }, null, outputArray, 1, new int[] { m_size }, new OpenCvSharp.Rangef[] { range });
Cv2.Normalize(outputArray, outputArray, 0, outputArray.Rows, NormTypes.MinMax, -1);
最后使用SkiaSharp的SKControl控件绘制简单的直方图,主要代码如下所示:
SKCanvas canvas = e.Surface.Canvas;
canvas.Clear();
SKPaint pen = new SKPaint();
switch (m_channel)
{
case 0:
pen.Color = SKColors.Blue;
break;
case 1:
pen.Color = SKColors.Green;
break;
case 2:
pen.Color = SKColors.Red;
break;
default:
pen.Color = SKColors.Black;
break;
}
pen.StrokeWidth = 1;
pen.Style = SKPaintStyle.Stroke;
double temp = 0;
for (int i = 0; i < m_size; i++)
{
canvas.DrawLine(50 + i, 300, 50 + i, 300 - m_mat.At<float>(i), pen);
}
最后是程序效果,如下图所示:
参考文献:
[1]https://baike.baidu.com/item/%E9%A2%9C%E8%89%B2%E7%9B%B4%E6%96%B9%E5%9B%BE/5194952?fr=ge_ala
[2]https://www.bilibili.com/video/BV1DT421m7S8?p=5&vd_source=db4a1f65c18549c78df3e9d579e59e19
[3]https://blog.csdn.net/TyroneKing/article/details/129279978
[4]https://www.jianshu.com/p/fe5fd81f22d4