2013年1月30日 星期三

【AForge.NET】RGB影像轉灰階影像GrayScale Image

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 System.Diagnostics;
using System.Runtime.InteropServices;
using AForge;
using AForge.Video;
using AForge.Video.DirectShow;
using AForge.Imaging;
using AForge.Imaging.Filters;

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

        private void Form1_Load(object sender, EventArgs e)
        {
            USB_Webcams = new FilterInfoCollection(FilterCategory.VideoInputDevice);
            if (USB_Webcams.Count > 0)
            {
                button1.Enabled = true;
                Cam = new VideoCaptureDevice(USB_Webcams[0].MonikerString);
                Cam.NewFrame += new NewFrameEventHandler(Cam_NewFrame);
            }
            else
            {
                button1.Enabled = false;
                MessageBox.Show("No video input device is connected.");
            }
        }

        void Cam_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            pictureBox1.Image = (Bitmap)eventArgs.Frame.Clone();
            RGBtoGrayImage((Bitmap)eventArgs.Frame.Clone());//轉灰階影像        
        }

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

        private void button1_Click(object sender, EventArgs e)
        {
            if (button1.Text == "Start")
            {
                button1.Text = "Stop";
                Cam.Start();  
            }
            else
            {
                button1.Text = "Start";
                Cam.Stop();  
            }
        }
        private void RGBtoGrayImage(Bitmap GrayImg)
        {
            Grayscale grayscaleFilter = new Grayscale(0.299, 0.587, 0.114);//設定一個灰階過濾鏡
            Bitmap bitmapGrayscale = grayscaleFilter.Apply(GrayImg);//執行灰階過濾鏡
            pbGrayscale.Image = bitmapGrayscale;//將灰階影像顯示在pbGrayscale的影像視窗
        }
    }
}

0 意見:

張貼留言