2013年2月7日 星期四

【AForge.NET】適應性門檻值二值化BradleyLocalThresholding

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AForge;
using AForge.Video;
using AForge.Video.DirectShow;
using AForge.Imaging;
using AForge.Imaging.Filters;

namespace MarcCS_TEST
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        public FilterInfoCollection USB_Webcams = null;
        public VideoCaptureDevice Cam = null;

        private void bt_start_Click(object sender, EventArgs e)
        {
            Cam.Start();//按下Start按鈕,啟動視訊    
        }

        private void bt_stop_Click(object sender, EventArgs e)
        {
            Cam.Stop();//按下Stop按鈕,停止視訊
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            USB_Webcams = new FilterInfoCollection(FilterCategory.VideoInputDevice);
            //可輸入視訊影像超過1台機器時執行
            if (USB_Webcams.Count > 0)
            {
                //Start按鈕為啟動時執行以下動作
                bt_start.Enabled = true;
                //從第一台視訊擷取畫面
                Cam = new VideoCaptureDevice(USB_Webcams[0].MonikerString);
                //啟動擷取視訊事件
                Cam.NewFrame += new NewFrameEventHandler(Cam_NewFrame);
            }
            else
            {    //Start按鈕為停止時執行以下動作
                bt_start.Enabled = false;
                MessageBox.Show("No video input device is connected.");
            }
        }
        void Cam_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            //將輸入影像解析度更改為320x240
            ResizeBilinear Resizefilter = new ResizeBilinear(320, 240);
            Bitmap CamImg = Resizefilter.Apply((Bitmap)eventArgs.Frame.Clone());
            Bitmap dstImg = CamImg.Clone() as Bitmap;

            MarcGrayScale(ref dstImg);
            MarcBradleyLocalThreshold(ref dstImg);

            //在pictureBox1上顯示影像
            pictureBox1.Image = CamImg;
            pictureBox2.Image = dstImg;
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (Cam != null)
                if (Cam.IsRunning)
                    Cam.Stop();
        }

        //RGB顏色空間轉GRAY顏色空間
        private void MarcGrayScale(ref Bitmap srcImg)
        {
            //設定一個灰階過濾鏡
            Grayscale grayscaleFilter = new Grayscale(0.299, 0.587, 0.114);
            srcImg = grayscaleFilter.Apply(srcImg);
        }
        
        //適應性門檻值二值化
        private void MarcBradleyLocalThreshold(ref Bitmap srcImg)
        {
            BradleyLocalThresholding BLTfilter = new BradleyLocalThresholding( );
            BLTfilter.ApplyInPlace(srcImg);
        }
    }
}



0 意見:

張貼留言