OpenCVSharp 跑一遍OpenCV官方教程(全为手敲代码,如有雷同都是我的错)
击中或击不中
OpenCV教程链接:https://docs.opencv.org/4.5.0/db/d06/tutorial_hitOrMiss.html
核心语句
MorphologyEx()
using OpenCvSharp;
using System;
namespace ConsoleApp1
{
class tutorial6 : ITutorial
{
public void Run()
{
byte[] image = new byte[64]{
0, 0, 0, 0, 0, 0, 0, 0,
0, 255, 255, 255, 0, 0, 0, 255,
0, 255, 255, 255, 0, 0, 0, 0,
0, 255, 255, 255, 0, 255, 0, 0,
0, 0, 255, 0, 0, 0, 0, 0,
0, 0, 255, 0, 0, 255, 255, 0,
0, 255, 0, 255, 0, 0, 255, 0,
0, 255, 255, 255, 0, 0, 0, 0};
Mat input_image = new Mat(8, 8, MatType.CV_8UC1, image);
//short[,] k = new short[3, 3] { { 0, 1, 0 }, { 1, -1, 1 }, { 0, 1, 0 } };
short[] k = new short[9] {0, 1, 0 , 1, -1, 1 , 0, 1, 0};
Mat kernel = new Mat(3, 3, MatType.CV_16SC1, k);
//Console.WriteLine(Cv2.Format(kernel));
Mat output_image = new Mat();
Cv2.MorphologyEx(input_image, output_image, MorphTypes.HitMiss, kernel);
int rate = 50;
kernel = (kernel + 1) * 127;
//Console.WriteLine(Cv2.Format(kernel));
kernel.ConvertTo(kernel, MatType.CV_8UC1);
Console.WriteLine(Cv2.Format(kernel));
Cv2.Resize(kernel, kernel, new Size(), rate, rate, InterpolationFlags.Nearest);
Cv2.ImShow("kernel", kernel);
Cv2.MoveWindow("kernel", 0, 0);
Cv2.Resize(input_image, input_image, new Size(), rate, rate, InterpolationFlags.Nearest);
Cv2.ImShow("Original", input_image);
Cv2.MoveWindow("Original", 0, 200);
Cv2.Resize(output_image, output_image, new Size(), rate, rate, InterpolationFlags.Nearest);
Cv2.ImShow("Hit or Miss", output_image);
Cv2.MoveWindow("Hit or Miss", 500, 200);
Cv2.WaitKey(0);
}
}
}