用OpenCVSharp 4.5 跑一遍 OpenCV官方教程
原官方教程链接:
核心函数:equalizeHist,split,calcHist,normalize
using System;
using OpenCvSharp;
namespace ConsoleApp1
{
class tutorial20 : ITutorial
{
public void Run()
{
using (Mat src = new Mat("I:\\csharp\\images\\lena.png", ImreadModes.Color))
using(Mat dst = new Mat())
{
Cv2.CvtColor(src, src, ColorConversionCodes.BGR2GRAY);
Cv2.EqualizeHist(src, dst);
using( new Window("Source image", src))
using (new Window("Equalized Image", dst))
Window.WaitKey();
}
}
}
}
using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class tutorial19 : ITutorial
{
public void Run()
{
using (Mat src = new Mat("I:\\csharp\\images\\lena.png", ImreadModes.Color))
{
Mat[] bgr_planes = new Mat[3];
Cv2.Split(src, out bgr_planes);
int[] histSize = { 256 };
Rangef[] histRange = { new Rangef(0, 256) }; //the upper boundary is exclusive
bool uniform = true, accumulate = false;
Mat b_hist = new Mat();
Mat g_hist = new Mat();
Mat r_hist = new Mat();
Cv2.CalcHist(bgr_planes, new int[] { 0 }, null, b_hist, 1, histSize, histRange, uniform, accumulate);
Cv2.CalcHist(bgr_planes, new int[] { 1 }, null, g_hist, 1, histSize, histRange, uniform, accumulate);
Cv2.CalcHist(bgr_planes, new int[] { 2 }, null, r_hist, 1, histSize, histRange, uniform, accumulate);
int hist_w = 512, hist_h = 400;
int bin_w = (int)Math.Round((double)hist_w / histSize[0]);
Mat histImage = new Mat(hist_h, hist_w, MatType.CV_8UC3, new Scalar(0, 0, 0));
Cv2.Normalize(b_hist, b_hist, 0, histImage.Rows, NormTypes.MinMax, -1, null);
Cv2.Normalize(g_hist, g_hist, 0, histImage.Rows, NormTypes.MinMax, -1, null);
Cv2.Normalize(r_hist, r_hist, 0, histImage.Rows, NormTypes.MinMax, -1, null);
for (int i = 1; i < histSize[0]; i++)
{
Cv2.Line(histImage,
new Point(bin_w * (i - 1), hist_h - Math.Round(b_hist.At<float>(i - 1))),
new Point(bin_w * (i), hist_h - Math.Round(b_hist.At<float>(i))),
new Scalar(255, 0, 0),
2,
LineTypes.Link8,
0);
Cv2.Line(histImage,
new Point(bin_w * (i - 1), hist_h - Math.Round(g_hist.At<float>(i - 1))),
new Point(bin_w * (i), hist_h - Math.Round(g_hist.At<float>(i))),
new Scalar(0, 255, 0),
2,
LineTypes.Link8,
0);
Cv2.Line(histImage,
new Point(bin_w * (i - 1), hist_h - Math.Round(r_hist.At<float>(i - 1))),
new Point(bin_w * (i), hist_h - Math.Round(r_hist.At<float>(i))),
new Scalar(0, 0, 255),
2,
LineTypes.Link8,
0);
}
using (new Window("Source image", src))
using (new Window("calcHist Demo", histImage))
Window.WaitKey();
}
}
}
}