Emgu 邊緣檢測,LineSegment2D[]畫直線,CircleF[]畫圓
阿新 • • 發佈:2019-01-09
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Emgu.CV;
using Emgu.CV.CvEnum;
using Emgu.CV.Structure;
namespace CannyEdgeDetector
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string strFileName = string.Empty;
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == DialogResult.OK)
{
Image<Bgr, Byte> img1 = new Image<Bgr, Byte>(ofd.FileName);
pictureBox1.Image = img1.ToBitmap();
//轉成灰度圖
Image<Gray, Byte> gray1 = img1.Convert<Gray, Byte>();
//Canny 邊緣檢測
Image<Gray, Byte> cannyGray = gray1.Canny(120, 180);
pictureBox2.Image = cannyGray.ToBitmap();
}
}
private void button2_Click(object sender, EventArgs e)
{
//從pictureBox2中載入影象
Image<Gray, Byte> cannyGray = new Image<Gray, byte>(new Bitmap(pictureBox2.Image));
//呼叫 HoughLinesBinary檢測直線 ,返回一個 LineSegment2D[][]陣列
LineSegment2D[] lines = cannyGray.HoughLinesBinary(1, Math.PI / 45.0, 20, 30, 10)[0];
//畫線
Image<Bgr, Byte> imageLines = new Image<Bgr, byte>(cannyGray.Width, cannyGray.Height);
//遍歷二維直線陣列
foreach (LineSegment2D line in lines)
{
///在imageLines上將直線畫出
imageLines.Draw(line, new Bgr(Color.DeepSkyBlue), 5);
}
//顯示結果
pictureBox2.Image = imageLines.ToBitmap();
}
private void button3_Click(object sender, EventArgs e)
{
string strFileName = string.Empty;
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == DialogResult.OK)
{
Image<Bgr, Byte> img1 = new Image<Bgr, Byte>(ofd.FileName);
pictureBox1.Image = img1.ToBitmap();
//轉灰度圖
Image<Gray, Byte> gray1 = img1.Convert<Gray, Byte>();
//呼叫HoughCircles (Canny included)檢測圓形
CircleF[] circles = gray1.HoughCircles(
new Gray(180), //cannyThreshold
new Gray(120), //accumulatorThreshold
2.0, //dp
15.0, //minDist
5, //minRadius
0 //maxRadius
)[0];
//畫圓
//img1.CopyBlank()直接複製上一步建立的空白影象
Image<Bgr, Byte> imageCircles = img1.CopyBlank();
foreach (CircleF circle in circles)
{
imageCircles.Draw(circle, new Bgr(Color.Yellow), 5);
}
//顯示結果
pictureBox2.Image = imageCircles.ToBitmap();
}
}
}
}