2013年2月7日 星期四

【AForge.NET】在影像上畫矩形CanvasFill

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
            {
                bt_start.Enabled = false;//Start按鈕為停止時執行以下動作
                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 CanvasImg = CamImg.Clone() as Bitmap;//複製影像
            pictureBox1.Image = CamImg;//在pictureBox1上顯示影像
            MarcCanvasFill(ref CanvasImg);
            pictureBox2.Image = CanvasImg;
            
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (Cam != null)
            {
                if (Cam.IsRunning)  
                {
                    Cam.Stop();  
                }
            }
        }
        //對影像畫矩形
        private void MarcCanvasFill(ref Bitmap srcImg)
        {
            //矩形(x座標,y座標,寬,高,顏色)
            CanvasFill filter = new CanvasFill(new Rectangle(
                        50, 50, srcImg.Width/2, srcImg.Height/2), Color.Blue);          
            filter.ApplyInPlace(srcImg);
        }
    }
}



0 意見:

張貼留言