- 截取圖片 crop()
- 詳細模板匹配 ExhaustiveTemplateMatching()
- 繪出矩形 Drawing.Rectangle()
- 加入 Stopwatch() 碼表計數影像處理時間。
- 以 crop() 方法截圖,再使用 ExhaustiveTemplateMatching() 比對原圖與截圖兩者相同處,最後用 Drawing.Rectangle() 繪製矩形至原圖來標示所截圖的位置。
- ExhaustiveTemplateMatching() 需要花用較多的處理時間,本文用兩圖測試花了:3分23秒、52秒。
Step1. 檔案 → 新增專案 → Windows Form 應用程式 → 拉物件 Form1.cs[設計] → 撰寫 Form1.cs
Step2. 方案總管 → 參考 → 右鍵加入參考 → 瀏灠(預設路徑) C:\Program Files (x86)\AForge.NET\Framework\Release → 加入參考:
- AForge.Imaging.dll
- AForge.Imaging.Formats.dll
Step3. Windows Form 拉入需要工具:
- pictureBox × 3
- button × 3
- textBox × 2
- Label × 2
- openFileDialog × 1
Step4. Coding
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 System.Drawing.Imaging; using System.Diagnostics; using AForge.Imaging; using AForge.Imaging.Formats; using AForge.Imaging.Filters; namespace CropAndMatch { public partial class Form1 : Form { Bitmap sourceImage, templateImage; Stopwatch stopWatch = new Stopwatch(); public Form1() { InitializeComponent(); } private void pictureBox3_Click(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { openFileDialog1.Filter = "所有檔案(*.*)|*.*"; if (openFileDialog1.ShowDialog() == DialogResult.OK) { sourceImage = ImageDecoder.DecodeFromFile(openFileDialog1.FileName); pictureBox1.Image = sourceImage; } } private void button2_Click(object sender, EventArgs e) { Crop filter = new Crop(new Rectangle(100, 150, 128, 128)); templateImage = filter.Apply(sourceImage); pictureBox3.Image = templateImage; } private void button3_Click(object sender, EventArgs e) { stopWatch.Reset(); stopWatch.Start(); // create template matching algorithm's instance ExhaustiveTemplateMatching tm = new ExhaustiveTemplateMatching(0.99f); // find all matchings with specified above similarity TemplateMatch[] matchings = tm.ProcessImage(sourceImage, templateImage); // highlight found matchings BitmapData data = sourceImage.LockBits( new Rectangle(0, 0, sourceImage.Width, sourceImage.Height), ImageLockMode.ReadWrite, sourceImage.PixelFormat); foreach (TemplateMatch m in matchings) { Drawing.Rectangle(data, m.Rectangle, Color.White); textBox2.Text = m.Rectangle.Location.ToString(); // do something else with matching } sourceImage.UnlockBits(data); pictureBox2.Image = sourceImage; stopWatch.Stop(); // Get the elapsed time as a TimeSpan value. TimeSpan ts = stopWatch.Elapsed; textBox1.Text = ts.ToString(); } private void Form1_Load(object sender, EventArgs e) { } private void textBox1_TextChanged(object sender, EventArgs e) { } private void textBox2_TextChanged(object sender, EventArgs e) { } } }
沒有留言:
張貼留言