视觉模板匹配代码

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 VDSR;   //可要可不要
using System.Runtime.InteropServices;
using System.Threading;

namespace VDSR
{
    public partial class Form1 : Form
    {
        bool bIsLct;
        bool onelct=false;
        bool bIsMove;
        bool SerisCapture = false;
        bool SerisLct = false;
        bool isConnect = false;
        GCHandle hobject;
        IntPtr getImageBuffers;
        IntPtr data;
        GCHandle hj;
        int N =480;
        int M = 640;
        byte[] getImageBuffer;
        byte[] getModeImageBuffer;
        int lImageW;//定义图像的宽度   
        int lImageH;//定义图像的高度
        int model = -1;//模版函数返回变量初始值
        int mod_h = 0;//模版的高度
        int mod_w = 0;//模版的宽度
        bool bIsHitL;//矩形框向左拖动状态
        bool bIsHitR;//矩形框向右拖动状态
        bool bIsHitT;//矩形框向上拖动状态
        bool bIsHitB;//矩形框向下拖动状态
        bool bIsHitA;//移动矩形框状态
        int lOldX;//中间点位x
        int lOldY;//中间点位y
        Rectangle lRect = new Rectangle();       
        int lPosL = 50;//初始化矩形框左x
        int lPosR = 150;//初始化矩形框右x
        float theta=1;
        int lPosT = 50;//初始化矩形框上y
        int lPosB = 150;//初始化矩形框下y
        //*************定位参数**********
        float fMatch=0;
        float fScale=0;
        float fLctX=0;
        float fLctY=0;
        float angle = 0;
        int panternum=-1;
        //*****************************
        bool bIsLearned = false;
        Rcts rcts = new Rcts();
        List<Rcts> list = new List<Rcts>();
        int num=-1;
        byte countmodel=2;
        byte[]  modelnum = new byte[5];
     
        public Form1()
        {
            InitializeComponent();
           
        }


        private void Bt_Connect_Click(object sender, EventArgs e)
        {
          
           Bt_Connect.BackColor = SystemColors.Control;
            Bt_Connect.Text = "连接中。。。。";
           // Application.DoEvents();
           int Conect=SR.open_camera("192.168.1.183", 2002);
           Application.DoEvents();
           isConnect = Conect == 0;
          if (Conect == 0)
          {
              Bt_Connect.Enabled = false;
              Bt_Connect.Text = "连接成功";
              Bt_Connect.BackColor = Color.Green;
              button_calibration.Enabled = true;
              SR.get_CamModel( ref countmodel);


              if (countmodel == '1')
              {
                  if (true == (radioButton2.Checked = true))
                  {
                      M = int.Parse(radioButton2.Text.Split('*')[0]);
                      N = int.Parse(radioButton2.Text.Split('*')[1]);
                      pictureBox1.Width = M / 2;
                      pictureBox1.Height = N / 2;
                  }

              }
              else if(countmodel=='0')

              {
                  if (true == (radioButton1.Checked = true))
                  {
                      M = int.Parse(radioButton1.Text.Split('*')[0]);
                      N = int.Parse(radioButton1.Text.Split('*')[1]);
                      pictureBox1.Width = M;
                      pictureBox1.Height = N;
                  }
              }


              //*************** 分配内存****************
              getImageBuffer = new byte[M * N];
              hobject = GCHandle.Alloc(getImageBuffer, GCHandleType.Pinned);
              getImageBuffers = hobject.AddrOfPinnedObject();
              getModeImageBuffer = new byte[M * N];
              hj = GCHandle.Alloc(getModeImageBuffer, GCHandleType.Pinned);
              data = hj.AddrOfPinnedObject();
              //***************分配内存****************

              SR.get_modelCount(modelnum);
              comboBox1.Items.Clear();
              for (int i = 0; i < 5; i++)
              {
                          
                      comboBox1.Items.Add("模版" + i.ToString());            
                      rcts.Add(50, 150, 50, 150, true, new Rectangle(50, 50, 150 - 50, 150 - 50), i + 1, ref list);
                  
              }
            // comboBox1.SelectedIndex =0;
         //   model=Get_Model(ref mod_w, ref mod_h,0);

          }
          else

          {
              Bt_Connect.Text = "连接失败";
              Bt_Connect.Enabled = true;
              Bt_Connect.BackColor = Color.Red;

          }
            
        }
        //定位
        private void Bt_Lct_Click(object sender, EventArgs e)
        {
            Bt_Lct.Enabled = false;
            bIsMove = false;
            bIsLct = !bIsMove;         
            onelct = true;
            if (!SerisCapture)
            {
                Bt_Lct.Enabled = true;
            }       
        }
        //取图
        private void Bt_Pic_Click(object sender, EventArgs e)
        {
            Bt_Pic.Enabled = !SerisCapture;
            do
            {
                lImageW = M;
                lImageH = N;
                if (isConnect)

                {      
                  bool Aqure=AcquireAndShowImage();
                  isConnect = Aqure;
                  if (isConnect)
                  {
                      panternum = comboBox1.SelectedIndex;
                      LocatePic(ref onelct, (byte)panternum, ref fMatch, ref fLctX, ref fLctY, ref angle, ref fScale, SerisLct);
                  }

                }
                Application.DoEvents();
            }

            while (SerisCapture && isConnect);

            Bt_Pic.Enabled = !(SerisCapture &isConnect);
            Bt_Lct.Enabled = !(SerisCapture & isConnect);

            if (isConnect == false)
            {
                SR.close_camera();
                Bt_Connect.Enabled = true;
                Bt_Connect.BackColor = SystemColors.Control;
                Bt_Connect.Text = "连接相机";
            }
        }


        private bool LocatePic( ref bool oneLocate, byte partenindex,ref float fMatch, ref float fLctX, ref  float fLctY, ref float angle, ref float fScale ,bool serlct)
        {
            if (oneLocate)
            {
                if (serlct==false )
                {
                    oneLocate = false;
                    Bt_Lct.Enabled = true;
                             
                }
                else
                {
                    oneLocate = true;
                }
                if ((int)partenindex == -1)
                {
                    return false;
                }

                lct(partenindex, ref fMatch, ref fLctX, ref fLctY, ref angle, ref fScale);
                return true;
            }
            else
            {
                return false ;
            }      
        }

        private  bool lct(byte partenindex, ref float fMatch, ref float fLctX, ref float fLctY, ref float angle, ref float fScale)
        {
            int pos_p = SR.position_pattern(ref fMatch, ref fLctX, ref fLctY, ref angle, ref fScale, partenindex);
            if (pos_p == 0)
            {
                if (fMatch > 0.5)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }


        //读取模版
        private void Bt_Save_Click(object sender, EventArgs e)
        {    int w=0;
             int h=0;
             int index = comboBox1.SelectedIndex;
             if (index == -1)
             {
                 return;
             }
             pictureBox2.Image = null;
             if (modelnum[index] == 1)
             { int stus = Get_Model(ref w, ref h, (byte)index); 


        }
        //增加模版
        private void Bt_AddMode_Click(object sender, EventArgs e)
        {
            if (!SerisLct)
            {
                if (comboBox1.Items.Count <= 4)
                {
                    int Modelcount = comboBox1.Items.Count + 1;
                    comboBox1.Items.Add("模版" + Modelcount.ToString());
                    comboBox1.SelectedIndex = Modelcount - 1;
                    rcts.Add(50, 150, 50, 150, true, new Rectangle(50, 50, 150 - 50, 150 - 50), comboBox1.SelectedIndex + 1, ref list);
                }

                if (comboBox1.Items.Count > 4)
                {
                    MessageBox.Show("模版个数超过5个");
                }

            }
        }
        //断开相机
        private void Bt_disconnect_Click(object sender, EventArgs e)
        {
            checkBox1.Checked = false;
            checkBox2.Checked = false;
            int status=SR.close_camera();
            isConnect = false;
            Bt_Connect.Enabled = true;
            Bt_Connect.BackColor = SystemColors.Control;
            Bt_Connect.Text = "连接相机";
            button_calibration.Enabled = false;
            bIsMove = false;
            list.Clear();
            
        }
        //连续取图
        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {

            SerisCapture = !SerisCapture;      
        }
        //连续定位
        private void checkBox2_CheckedChanged(object sender, EventArgs e)
        {
            SerisLct = !SerisLct;

            if (!SerisLct)
            {
                bIsMove = true;
                bIsLct = false;
            }
        }


        //取图函数
        private bool AcquireAndShowImage()
        {

            int getVide0=SR.get_src_video(lImageW, lImageH, getImageBuffers);
            bool bRst = 0 == getVide0;
          if (bRst)
            {
                int w = lImageW;
                int h = lImageH;
                Bitmap mImg=null;
                byte[] mBuffer = new byte[w * h ];
                Marshal.Copy(getImageBuffers, mBuffer, 0, mBuffer.Length);
                BitmapFactory.CreateBitmap(ref mImg, w, h, false);
                BitmapFactory.UpdateBitmap(mImg, mBuffer, w, h, false);
                pictureBox1.Image = mImg;
                pictureBox1.Refresh();
                Application.DoEvents();        
                mImg = null;
                mBuffer = null;
                GC.Collect();
               // GC.WaitForFullGCComplete();
            }
            return bRst;
        }


        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            radioButton1.Checked = !radioButton2.Checked;
            if (radioButton1.Checked == true)
            {
                M = int.Parse(radioButton1.Text.Split('*')[0]);
                N = int.Parse(radioButton1.Text.Split('*')[1]);
                pictureBox1.Width = M;
                pictureBox1.Height = N;
                theta = 0.5f;
            }
            else
            {
                M = int.Parse(radioButton2.Text.Split('*')[0]);
                N = int.Parse(radioButton2.Text.Split('*')[1]);
                pictureBox1.Width = M / 2;
                pictureBox1.Height = N / 2;
                theta = 1f;
            }
       
        }

        private void radioButton2_CheckedChanged(object sender, EventArgs e)
        {
            radioButton2.Checked = !radioButton1.Checked;
            if (radioButton1.Checked == true)
            {
                M = int.Parse(radioButton1.Text.Split('*')[0]);
                N = int.Parse(radioButton1.Text.Split('*')[1]);
                pictureBox1.Width = M;
                pictureBox1.Height = N;
                theta = 0.5f;
            }
            else
            {
                M = int.Parse(radioButton2.Text.Split('*')[0]);
                N = int.Parse(radioButton2.Text.Split('*')[1]);
                pictureBox1.Width = M / 2;
                pictureBox1.Height = N / 2;
                theta = 1f;
            }
   
        }
        
        private void pictureBox1_Paint(object sender, PaintEventArgs e)
        {
            Pen lPen = new Pen(Color.Green, 1);
            if (pictureBox1.Image != null)
            {
                e.Graphics.DrawLine(lPen, new Point(0, pictureBox1.Height / 2), new Point(pictureBox1.Width, pictureBox1.Height / 2));
                e.Graphics.DrawLine(lPen, new Point(pictureBox1.Width / 2, 0), new Point(pictureBox1.Width / 2, pictureBox1.Height));
            }
            if (bIsMove)
            {
                foreach (Rcts s in list)
                {
                    if (list != null)
                    {
                         
                            lPen.Color = Color.LimeGreen;
                            lPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Solid;
                            e.Graphics.DrawRectangle(lPen, s.Rct);
                            e.Graphics.DrawString(s.Rectnum.ToString(), new Font("宋体", 20, FontStyle.Regular), new SolidBrush(Color.Green), new PointF((s.Rct.X + s.Rct.Width / 2), (s.Rct.Y + lRect.Height / 2)));
                    }
                }
            }
      
            if (bIsLct)
            {

                if (fMatch > 0.5)
                {
                    lPen.Color = Color.Red;
                   
                    lRect.X = (int)(fLctX / (2 * theta)) - (list[panternum].LPosR - list[panternum].LPosL) / 2;
                    lRect.Y = (int)(fLctY / (2 * theta)) - (list[panternum].LPosB - list[panternum].LPosT) / 2;
                    lRect.Width = list[panternum].LPosR - list[panternum].LPosL;
                    lRect.Height = list[panternum].LPosB - list[panternum].LPosT;
                    lPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Solid;
                    lPen.DashOffset = 0f;
                    e.Graphics.TranslateTransform(fLctX / (2 * theta), fLctY / (2 * theta));
                    e.Graphics.RotateTransform(angle, System.Drawing.Drawing2D.MatrixOrder.Prepend);
                    e.Graphics.TranslateTransform(-fLctX / (2 * theta), -fLctY / (2 * theta));
                    e.Graphics.DrawLine(lPen, fLctX / (2 * theta) - 25, fLctY / (2 * theta), fLctX / (2 * theta) + 25, fLctY / (2 * theta));
                    e.Graphics.DrawLine(lPen, fLctX / (2 * theta), fLctY / (2 * theta) - 25, fLctX / (2 * theta), fLctY / (2 * theta) + 25);
                    e.Graphics.DrawRectangle(lPen, lRect);
                }
            }      
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            checkBox1.Checked = false;
            SR.close_camera();
        }


        private int Get_Model(ref int ww, ref int hh,  byte index)
        {
            try
            {
                uint w = 0;
                uint h = 0;
                byte[] cc = new byte[640 * 480];
                int st = SR.read_pattern(data, ref w, ref h, index);
                if (st == -1)
                {
                    return st;
                }
                if (st == -2)
                {
                    return -1;
                }
                ww = (int)w;
                hh = (int)h;
                byte[] mBuffer = new byte[ww * hh];
                Marshal.Copy(data, mBuffer, 0, mBuffer.Length);
                Bitmap bp = null;
                BitmapFactory.CreateBitmap(ref bp, ww, hh, false);
                BitmapFactory.UpdateBitmap(bp, mBuffer, ww, hh, false);
                pictureBox2.Image = bp;
                pictureBox2.Refresh();
                return 0;
            }
            catch (Exception)
            {
                return -1;
            }

        }

        private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
        {
             num = -1;
            foreach (Rcts s in list)
            {
                
                if (list.Count > 0 && list != null)

                {
                    if (e.X >s.LPosL && e.X <s.LPosR && e.Y >s.LPosT && e.Y <s.LPosB)
                    {
                        num = s.Rectnum-1;
                    }

                    if (Math.Abs(e.X - s.LPosL) <=3+0.1 || Math.Abs(e.X - s.LPosR) <=3+0.1 || Math.Abs(e.Y - s.LPosT) <=3+0.1 || Math.Abs(e.Y - s.LPosB) <=3+0.1)
                    {
                        num = s.Rectnum - 1;
                    }
                }
            }
            if (num != -1)
            {
                lPosL = list[num].LPosL;
                lPosR = list[num].LPosR;
                lPosB = list[num].LPosB;
                lPosT = list[num].LPosT;

            }
  
            if (!bIsMove ) return;

            bIsHitL = HitRectV(e.X, e.Y, true, 3);
            bIsHitR = HitRectV(e.X, e.Y, false, 3);
            bIsHitT = HitRectH(e.X, e.Y, true, 3);
            bIsHitB = HitRectH(e.X, e.Y, false, 3);
            bIsHitA = HitRectArea(e.X, e.Y, 3);
            if (bIsHitA)
            {
                lOldX = e.X;
                lOldY = e.Y;
            }
        }


        private void pictureBox1_MouseLeave(object sender, EventArgs e)
        {
            Cursor = Cursors.Arrow;
        }

        private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
        {
            if (!bIsMove) return;
            Cursor = Cursors.Arrow;
            if (bIsHitL)
            {
                Cursor = Cursors.SizeWE;
                lPosL = e.X;
               
                list[num].LPosL =lPosL;
                list[num].Rct = new Rectangle(lPosL, lPosT, lPosR - lPosL, lPosB - lPosT);
                pictureBox1.Invalidate();
            }
            else
            {
                if (HitRectV(e.X, e.Y, true, 3)) Cursor = Cursors.SizeWE;
                bIsHitL = false;
            }


            if (bIsHitR)
            {
                Cursor = Cursors.SizeWE;
                lPosR = e.X;               
                list[num].LPosR = lPosR;
                list[num].Rct = new Rectangle(lPosL, lPosT, lPosR - lPosL, lPosB - lPosT);
                pictureBox1.Invalidate();
            }
            else
            {
                if (HitRectV(e.X, e.Y, false, 3)) Cursor = Cursors.SizeWE;
                bIsHitR = false;
            }

            if (bIsHitT)
            {
                Cursor = Cursors.SizeNS;
                lPosT = e.Y;            
                list[num].LPosT = lPosT;
                list[num].Rct = new Rectangle(lPosL, lPosT, lPosR - lPosL, lPosB - lPosT);
                pictureBox1.Invalidate();
            }
            else
            {
                if (HitRectH(e.X, e.Y, true, 3)) Cursor = Cursors.SizeNS;
                bIsHitT = false;
            }


            if (bIsHitB)
            {
                Cursor = Cursors.SizeNS;
                lPosB = e.Y;            
                list[num].LPosB = lPosB;
                list[num].Rct = new Rectangle(lPosL, lPosT, lPosR - lPosL, lPosB - lPosT);
                pictureBox1.Invalidate();
            }
            else
            {
                if (HitRectH(e.X, e.Y, false, 3)) Cursor = Cursors.SizeNS;
                bIsHitB = false;
            }
            if (bIsHitA)
            {
                Cursor = Cursors.SizeAll;

                int lMoveX = e.X - lOldX;
                int lMoveY = e.Y - lOldY;
                lPosT = lPosT + lMoveY;
                lPosB = lPosB + lMoveY;
                lPosL = lPosL + lMoveX;
                lPosR = lPosR + lMoveX;
                lOldX = e.X;
                lOldY = e.Y;
                list[num].LPosL = lPosL;
                list[num].LPosR = lPosR;
                list[num].LPosT = lPosT;
                list[num].LPosB = lPosB;
                list[num].Rct = new Rectangle(lPosL, lPosT, lPosR - lPosL, lPosB - lPosT);
                pictureBox1.Invalidate();
            }
            else
            {
                if (HitRectArea(e.X, e.Y, 3)) Cursor = Cursors.SizeAll;
                bIsHitA = false;
            }
        }

        private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
        {
            bIsHitL = false;
            bIsHitR = false;
            bIsHitT = false;
            bIsHitB = false;
            bIsHitA = false;
        }
        private bool HitRectV(int lX, int lY, bool bIsLeft, int allowedDeviation )
        {
            double lDeviation = allowedDeviation + 0.1;
            int lPos;
            if (bIsLeft) lPos = lPosL;
            else lPos = lPosR;
            if (Math.Abs(lPos - lX) < lDeviation && (lY > lPosT + lDeviation && lY < lPosB + lDeviation))
                return true;
            else
                return false;
        }


        private bool HitRectH(int lX, int lY, bool bIsTop, int allowedDeviation )
        {
            double lDeviation = allowedDeviation + 0.1;
            int lPos;
            if (bIsTop) lPos = lPosT;
            else lPos = lPosB;
            if (Math.Abs(lPos - lY) < lDeviation && (lX > lPosL + lDeviation && lX < lPosR + lDeviation))
                return true;
            else
                return false;
        }


        private bool HitRectArea(int lX, int lY, int allowedDeviation)
        {
            double lDeviation = allowedDeviation + 0.1;
            if ((lX > lPosL + lDeviation) && (lX < lPosR - lDeviation) && (lY > lPosT + lDeviation) && (lY < lPosB - lDeviation))
                return true;
            else
                return false;
        }


        private void comboBox1_TextChanged(object sender, EventArgs e)
        {
            if (SerisLct == false)
            {
                bIsMove = true;
                bIsLct=false ;
            }
            else
            {
                bIsMove =false;
                bIsLct = true;
            }

            pictureBox1.Invalidate();
        }
        //学习模版
        private void button1_Click(object sender, EventArgs e)
        {
          if(!SerisLct)
            {
            
              int index = comboBox1.SelectedIndex;
           
            if(index== -1)
            {
                return;
            }
               Rcts MidRct = list[index];            
               int x =(int)((( float) (MidRct.Rct.X)) * 2*theta) ;
               int y = (int)(((float)(MidRct.Rct.Y)) * 2 * theta);
               int Theta=(int)(2/theta);
               int width = (MidRct.Rct.Width / Theta) * 4;
               int height = (MidRct.Rct.Height /Theta) * 4;                    
               int lRst = SR.choice_pattern(x, y, width ,height,(byte)index);
               bIsLearned=lRst == 0;
            if(bIsLearned)
            {
                modelnum[index] = 1;
            }
            }
        }
        //保存模版
        private void button2_Click(object sender, EventArgs e)
        {
            if (bIsLearned)
            {
                int index =  comboBox1.SelectedIndex;
                if (index == -1)
                {
                    return;
                }
                int c = SR.save_pattern((byte)index);
                bIsLearned = false;
            }
        }
   
        //标定
        private void button_calibration_Click(object sender, EventArgs e)
        {
            float a = 0;
            float b = 0;
            PointF firstw = new PointF(0,0);
            PointF secondw = new PointF(10,0);
            PointF firsti = new PointF(300,512);
            PointF secondi = new PointF(700,600);
            float isnum=0;
            bool isdigit=float.TryParse(textBox1.Text,out isnum );
            if (!isdigit)
            {
                return;
            }
            firstw.X = isnum;
            isdigit = float.TryParse(textBox2.Text, out isnum);
            if (!isdigit)
            {
                return;
            }
            firstw.Y = isnum;


            isdigit = float.TryParse(textBox5.Text, out isnum);
            if (!isdigit)
            {
                return;
            }
            firsti.X = isnum;
            isdigit = float.TryParse(textBox6.Text, out isnum);
            if (!isdigit)
            {
                return;
            }

            firsti.Y = isnum;

            isdigit = float.TryParse(textBox3.Text, out isnum);
            if (!isdigit)
            {
                return;
            }
           secondw.X= isnum;

           isdigit = float.TryParse(textBox4.Text, out isnum);
           if (!isdigit)
           {
               return;
           }
           secondw.Y = isnum;
           isdigit = float.TryParse(textBox7.Text, out isnum);
           if (!isdigit)
           {
               return;
           }
           secondi.X = isnum;

           isdigit = float.TryParse(textBox8.Text, out isnum);
           if (!isdigit)
           {
               return;
           }
           secondi.Y = isnum;

           SR.get_calibrate(firstw, secondw, firsti, secondi, ref a, ref b);
            textBox9.Text = a.ToString("f3");
            textBox10.Text = b.ToString("f3");
        }
       
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值