在好例子网,分享、交流、成长!
您当前所在位置:首页C# 开发实例C#语言基础 → 一个视觉定位的贴标机项目实例

一个视觉定位的贴标机项目实例

C#语言基础

下载此实例
  • 开发语言:C#
  • 实例大小:26.70M
  • 下载次数:388
  • 浏览次数:1815
  • 发布时间:2020-11-25
  • 实例类别:C#语言基础
  • 发 布 人:hp609400568
  • 文件格式:.zip
  • 所需积分:10
 相关标签: BASLER C# dev Halcon

实例介绍

【实例简介】实例中包涵视觉定位,halcon读标签

1,根据大视野自动计算出产品位置,根据小视野计算可以贴标签的位置

2,项目中使用basler相机取向,halcon视觉计算

【实例截图】from clipboard

【核心代码】


using CommunicationServer.Class;
using FPCInspection.Config;
//using HalconDotNet;
using Nobug.Model.Camera;
using Nobug.Utility;
using Nobug.Vision;
using Nobug.Vision.Algrithom;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using FindBarcodeLog;

namespace FindBarcode
{
    public partial class FormMain : Form
    {
        private Thread showImageThread;
        private Thread calculateBigThread;
        private Thread calculateSmallThread;
        private MesServer serverBig;
        private MesServer serverSmall;
        public BaslerCamera BigCam;
        public BaslerCamera SmallCam;

        /// <summary>
        /// 声明委托 和 事件
        /// </summary>
        /// <param name="value"></param>
        private delegate void SetRichTextSN(System.Windows.Forms.RichTextBox pButton, string mStr, Color pColor, string iType);

        private Log pLog = new Log();

        public FormMain()
        {
            InitializeComponent();
            this.Size = new Size(1532, 1138);
        }

        private void btn_LoadImage_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "图像文件(*.bmp)|*.bmp";
            DialogResult dr = ofd.ShowDialog();
            if (dr == DialogResult.OK)
            {
                System.Drawing.Image img = System.Drawing.Image.FromFile(ofd.FileName);
                this.drawingBoard1.OriginalImage = new Bitmap(img);
                this.drawingBoard2.OriginalImage = new Bitmap(img);
                //this.drawingBoard1.ClearAll();
                img.Dispose();
                drawingBoard1.CreatedShapes.Clear();
                this.drawingBoard1.Fit2Screen();
            }
        }

        private void showLabel(bool isLabelFound, Rectangle2NB rect, int position, string message, Color color)
        {
            if (isLabelFound)
            {
                rect.LineWidth = 2;
                rect.PaintColor2 = Color.Red;
                drawingBoard1.CreatedShapes.Add(rect);
                this.drawingBoard1.CreatedShapes.Add(new TextNB()
                {
                    Angle = rect.Angle,
                    FontSize = 60,
                    StartPoint = new PointF((float)rect.Center.X, (float)rect.Center.Y),
                    Text = string.Format("R:{0},C:{1},A:{2}",
                                         rect.Center.X.ToString("0.00"),
                                         rect.Center.Y.ToString("0.00"),
                                         (rect.Angle * 360 / 6.28).ToString("0.00")),
                    PaintColor2 = Color.OrangeRed
                });
                this.drawingBoard1.CreatedShapes.Add(new PointNB()
                {
                    LineWidth = 2,
                    CrossSize = 30,
                    Center = new PointF((float)rect.Center.X, (float)rect.Center.Y)
                });
                this.drawingBoard1.CreatedShapes.Add(new TextNB()
                {
                    FontSize = 120,
                    StartPoint = new PointF(20, position),
                    Text = string.Format("找到{0}标签!", message),
                    PaintColor2 = color
                });
            }
            else
            {
                this.drawingBoard1.CreatedShapes.Add(new TextNB()
                {
                    FontSize = 120,
                    StartPoint = new PointF(20, position),
                    Text = string.Format("未找到{0}标签!", message),
                    PaintColor2 = color
                });
            }
        }

        //手自动公用变量
        //所有可能有条码的区域
        private List<Rectangle2NB> AllLabelRects = null;
        //所有可能直接贴标的区域
        private List<Rectangle2NB> AllPasteRects = null;
        //ReelId区域
        private Rectangle2NB ReelIdRect = null;
        //ReelId的条码内容
        private string ReelIdContent;
        //在没有可直接贴标区域时,计算出来的可贴标区域
        private Rectangle2NB PasteRect;
        //覆盖老贴标区域的贴标位置
        private Rectangle2NB PasteRectOld;
        //拍大视野是否已经找到贴条码区域
        private bool IsPasteAreaFound = false;

        //大视野相机计算 1.查找是否有已经贴过的类似于Reel但颜色不同的标签
        //               2.查找Reel标签
        //               3.查找可能的标签区域
        private void btn_DrawRoi_Click(object sender, EventArgs e)
        {
            bool showCandiReg = true;
            drawingBoard1.CreatedShapes.Clear();
            List<Rectangle2NB> labelRectsCandi = null;
            long time = 0;
            Bitmap bmp = drawingBoard1.OriginalImage;
            try
            {
                VisionAlgrithom.BigSearch(VisionAlgrithom.Bitmap2HObjectBpp32(bmp),
                                          GlobalVariable.CurrentSystemConfig.ReelLowVal, GlobalVariable.CurrentSystemConfig.ReelHighVal,
                                          GlobalVariable.CurrentSystemConfig.BlueLowVal, GlobalVariable.CurrentSystemConfig.BlueHighVal,
                                          GlobalVariable.CurrentSystemConfig.OrangeLowVal, GlobalVariable.CurrentSystemConfig.OrangeHighVal,
                                          GlobalVariable.CurrentSystemConfig.YellowLowVal, GlobalVariable.CurrentSystemConfig.YellowHighVal,
                                          25000, 3000000,
                                          128, 150, 180, 100000,
                                          GlobalVariable.CurrentSystemConfig.BarcodeThreshold, GlobalVariable.CurrentSystemConfig.BarcodeWidth, 200, GlobalVariable.CurrentSystemConfig.AngleExtend, GlobalVariable.CurrentSystemConfig.ClosingArea,
                                          out AllPasteRects,
                                          out AllLabelRects,
                                          out labelRectsCandi,
                                          out time);
                bmp.Dispose();
                if (AllPasteRects != null && AllPasteRects.Count > 0)
                {
                    for (int i = 0; i < AllPasteRects.Count; i )
                    {
                        AllPasteRects[i].LineWidth = 2;
                        AllPasteRects[i].PaintColor2 = Color.Red;
                        drawingBoard1.CreatedShapes.Add(AllPasteRects[i]);
                        this.drawingBoard1.CreatedShapes.Add(new TextNB()
                        {
                            Angle = AllPasteRects[i].Angle,
                            FontSize = 60,
                            StartPoint = new PointF((float)AllPasteRects[i].Center.X, (float)AllPasteRects[i].Center.Y),
                            Text = string.Format("R:{0},C:{1},A:{2}",
                                                 AllPasteRects[i].Center.X.ToString("0.00"),
                                                 AllPasteRects[i].Center.Y.ToString("0.00"),
                                                 (AllPasteRects[i].Angle * 360 / 6.28).ToString("0.00")),
                            PaintColor2 = Color.OrangeRed
                        });
                        this.drawingBoard1.CreatedShapes.Add(new PointNB()
                        {
                            LineWidth = 2,
                            CrossSize = 30,
                            Center = new PointF((float)AllPasteRects[i].Center.X, (float)AllPasteRects[i].Center.Y)
                        });
                        this.drawingBoard1.CreatedShapes.Add(new TextNB()
                        {
                            FontSize = 120,
                            StartPoint = new PointF(20, 280),
                            Text = string.Format("找到{0}个贴标区,如红色框所示!", AllPasteRects.Count),
                            PaintColor2 = Color.LimeGreen
                        });
                    }
                    PasteRectOld = AllPasteRects[0];
                }
                if (AllLabelRects != null && AllLabelRects.Count > 0)
                {
                    for (int i = 0; i < AllLabelRects.Count; i )
                    {
                        AllLabelRects[i].LineWidth = 2;
                        AllLabelRects[i].PaintColor2 = Color.Blue;
                        drawingBoard1.CreatedShapes.Add(AllLabelRects[i]);
                        this.drawingBoard1.CreatedShapes.Add(new TextNB()
                        {
                            Angle = AllLabelRects[i].Angle,
                            FontSize = 60,
                            StartPoint = new PointF((float)AllLabelRects[i].Center.X, (float)AllLabelRects[i].Center.Y),
                            Text = string.Format("R:{0},C:{1},A:{2}",
                                                 AllLabelRects[i].Center.X.ToString("0.00"),
                                                 AllLabelRects[i].Center.Y.ToString("0.00"),
                                                 (AllLabelRects[i].Angle * 360 / 6.28).ToString("0.00")),
                            PaintColor2 = Color.OrangeRed
                        });
                        this.drawingBoard1.CreatedShapes.Add(new PointNB()
                        {
                            LineWidth = 2,
                            CrossSize = 30,
                            Center = new PointF((float)AllLabelRects[i].Center.X, (float)AllLabelRects[i].Center.Y)
                        });
                    }
                    this.drawingBoard1.CreatedShapes.Add(new TextNB()
                    {
                        FontSize = 120,
                        StartPoint = new PointF(20, 560),
                        Text = string.Format("找到{0}个读条码区,如蓝色框所示!", AllLabelRects.Count),
                        PaintColor2 = Color.LimeGreen
                    });
                }
                if (showCandiReg)
                {
                    if (labelRectsCandi != null && labelRectsCandi.Count > 0)
                    {
                        for (int i = 0; i < labelRectsCandi.Count; i )
                        {
                            labelRectsCandi[i].LineWidth = 1;
                            labelRectsCandi[i].PaintColor2 = Color.Pink;
                            drawingBoard1.CreatedShapes.Add(labelRectsCandi[i]);
                        }
                    }
                }
                this.drawingBoard1.CreatedShapes.Add(new TextNB()
                {
                    FontSize = 120,
                    StartPoint = new PointF(20, 730),
                    Text = string.Format("总耗时: {0} ms", time),
                    PaintColor2 = Color.White
                });
                drawingBoard1.Repaint();
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btn_SmallReadBarcode_Click(object sender, EventArgs e)
        {
            bool isExistReel = false;
            string reel = "";
            drawingBoard2.CreatedShapes.Clear();
            List<string> barcodeStr = new List<string>();
            List<Rectangle2NB> barcodeRects = null;
            VisionAlgrithom.SmallRead(VisionAlgrithom.Bitmap2HObjectBpp32(drawingBoard2.OriginalImage),
                                      out barcodeStr,
                                      out barcodeRects,
                                      out PasteRect,
                                      out isExistReel,
                                      out reel);
            if (barcodeRects != null && barcodeRects.Count > 0)
            {
                for (int i = 0; i < barcodeRects.Count; i )
                {
                    barcodeRects[i].LineWidth = 1;
                    barcodeRects[i].PaintColor2 = Color.Blue;
                    drawingBoard2.CreatedShapes.Add(barcodeRects[i]);
                    this.drawingBoard2.CreatedShapes.Add(new TextNB()
                    {
                        FontSize = 45,
                        StartPoint = new PointF((float)barcodeRects[i].Center.X, (float)barcodeRects[i].Center.Y),
                        Angle = barcodeRects[i].Angle,
                        Text = string.Format(barcodeStr[i]),
                        PaintColor2 = Color.OrangeRed
                    });
                    this.drawingBoard2.CreatedShapes.Add(new PointNB()
                    {
                        LineWidth = 2,
                        CrossSize = 30,
                        Center = new PointF((float)barcodeRects[i].Center.X, (float)barcodeRects[i].Center.Y)
                    });
                }
            }
            if(PasteRect != null)
            {
                PasteRect.LineWidth = 2;
                PasteRect.PaintColor2 = Color.White;
                this.drawingBoard2.CreatedShapes.Add(PasteRect);
            }
            drawingBoard2.Repaint();
            if (!isExistReel)
                MessageBox.Show("未找到ReelId", "ReelId", MessageBoxButtons.OK, MessageBoxIcon.Information);
            else
                MessageBox.Show(string.Format("ReelId:{0}", reel), "ReelId", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void btn_Cali_Click(object sender, EventArgs e)
        {
        }

        private void cB_Rule_CheckedChanged(object sender, EventArgs e)
        {
            drawingBoard1.ShowRuler = cB_Rule.Checked;
            drawingBoard2.ShowRuler = cB_Rule.Checked;
        }

        private void btn_AddPoint_Click(object sender, EventArgs e)
        {
            if(tC_9Point.SelectedTab == tP_Big)
            {
                if (cB_Rectangle.Checked)
                    this.drawingBoard1.DrawRectangle2 = true;
                else
                    this.drawingBoard1.DrawCircle = true;
            }
            else if(tC_9Point.SelectedTab == tP_Small)
            {
                if (cB_Rectangle.Checked)
                    this.drawingBoard2.DrawRectangle2 = true;
                else
                    this.drawingBoard2.DrawCircle = true;
            }
        }

        private void FormMain_Load(object sender, EventArgs e)
        {
            SetRunLog("启动程式");
            #region System 
            LogHelper.Init(this);
            GlobalVariable.CurrentSystemConfig = new SystemConfig();
            //SystemConfig.Save(@"C:\\test.xml", GlobalVariable.CurrentSystemConfig);
            SystemConfig.Load(@"C:\\test.xml", out GlobalVariable.CurrentSystemConfig);
            nUD_BigAngleOffset.Value = (decimal)GlobalVariable.CurrentSystemConfig.BigAngleOffset;
            nUD_SmallAngleOffset.Value = (decimal)GlobalVariable.CurrentSystemConfig.SmallAngleOffset;

            this.drawingBoard1.DrawFinishHandler = DrawingBoard1_DrawFinishHandler;
            this.drawingBoard2.DrawFinishHandler = DrawingBoard2_DrawFinishHandler;
            #endregion
            SetRunLog("连接相机");
            #region Camera
            List<string> camNames = CameraBase.EnumerateCamera(CameraType.BaslerCamera);
            //Basler acA2500-14gm (21497018)
            BigCam = new BaslerCamera("CamBig (23162592)");
            //BigCam = new BaslerCamera("CamBig (23333162592)");
            BigCam.CameraMode = CameraMode.Auto;
            SmallCam = new BaslerCamera("CamSmall (22443331)");
            //SmallCam = new BaslerCamera("Basler acA2500-14gm (21497018)");
            SmallCam.CameraMode = CameraMode.Auto;
            if (BigCam.Open())
            {
                //BigCam.ShowImage = showImage;
                tSSL_BigCam.Image = Properties.Resources.Green_Rect;
                //if (tabControl1.SelectedTab == tP_Big)
                    nUD_Exposure.Value = (decimal)BigCam.GetExposureTime();
            }
            else
            {
                tSSL_BigCam.Image = Properties.Resources.Yellow_Rect;
                MessageBox.Show("大视野相机打开失败!", "相机", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            if (SmallCam.Open())
            {
                //SmallCam.ShowImage = showImage;
                tSSL_SmallCam.Image = Properties.Resources.Green_Rect;
                //if (tabControl1.SelectedTab != tP_Big)
                    //nUD_Exposure.Value = (decimal)SmallCam.GetExposureTime();
            }
            else
            {
                tSSL_SmallCam.Image = Properties.Resources.Yellow_Rect;
                MessageBox.Show("小视野相机打开失败!", "相机", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            SetRunLog("打开服务连接");
            serverBig = new MesServer("6001", "BigCam");
            serverBig.posorneg = "Big";
            serverBig.MesServerRunDisplayEvent = showComStatus;
            serverBig.Start();
            serverSmall = new MesServer("6002", "SmallCam");
            serverSmall.posorneg = "Small";
            serverSmall.MesServerRunDisplayEvent = showComStatus;
            serverSmall.Start();
            showImageThread = new Thread(showImage);
            showImageThread.Start();
            //netComThread = new Thread(netCom);
            //netComThread.Start();
            calculateBigThread = new Thread(calculateBig);
            calculateBigThread.Start();
            calculateSmallThread = new Thread(calculateSmall);
            calculateSmallThread.Start();
            #endregion
            SetRunLog("启动完成");
        }

        private void DrawingBoard1_DrawFinishHandler(object sender, EventArgs e)
        {
            if (cB_Rectangle.Checked)
            {
                Rectangle2NB rect = (Rectangle2NB)((DrawEventArgs)e).Shape;
                this.dGV_BigPixel9Point.Rows.Add();
                this.dGV_BigPixel9Point.Rows[this.dGV_BigPixel9Point.Rows.Count - 1].Cells[0].Value = rect.Center.Y.ToString("0.0");
                this.dGV_BigPixel9Point.Rows[this.dGV_BigPixel9Point.Rows.Count - 1].Cells[1].Value = rect.Center.X.ToString("0.0");
            }
            else
            {
                CircleNB circle;
                HObject img = VisionAlgrithom.Bitmap2HObjectBpp32(this.drawingBoard1.OriginalImage);

                VisionAlgrithom.FindCaliMark(img, ((DrawEventArgs)e).Shape, out circle);
                if (circle.Center.X != 0 && circle.Center.Y != 0)
                {
                    PointNB center = new PointNB()
                    {
                        Center = new PointF(circle.Center.X, circle.Center.Y),
                        LineWidth = 3,
                        CrossSize = 20,
                    };
                    this.drawingBoard1.CreatedShapes.Add(center);
                    circle.LineWidth = 2;
                    circle.PaintColor2 = Color.Red;
                    this.drawingBoard1.CreatedShapes.Add(circle);
                    this.drawingBoard1.Repaint();
                    this.dGV_BigPixel9Point.Rows.Add();
                    this.dGV_BigPixel9Point.Rows[this.dGV_BigPixel9Point.Rows.Count - 1].Cells[0].Value = circle.Center.Y.ToString("0.0");
                    this.dGV_BigPixel9Point.Rows[this.dGV_BigPixel9Point.Rows.Count - 1].Cells[1].Value = circle.Center.X.ToString("0.0");
                }
            }
        }

        private void DrawingBoard2_DrawFinishHandler(object sender, EventArgs e)
        {
            if (cB_Rectangle.Checked)
            {
                Rectangle2NB rect = (Rectangle2NB)((DrawEventArgs)e).Shape;
                this.dGV_Small9Point.Rows.Add();
                this.dGV_Small9Point.Rows[this.dGV_Small9Point.Rows.Count - 1].Cells[0].Value = rect.Center.Y.ToString("0.0");
                this.dGV_Small9Point.Rows[this.dGV_Small9Point.Rows.Count - 1].Cells[1].Value = rect.Center.X.ToString("0.0");
            }
            else
            {
                CircleNB circle;
                HObject img = VisionAlgrithom.Bitmap2HObjectGray(this.drawingBoard2.OriginalImage);
                VisionAlgrithom.FindCaliMark(img, ((DrawEventArgs)e).Shape, out circle);
                if (circle.Center.X != 0 && circle.Center.Y != 0)
                {
                    PointNB center = new PointNB()
                    {
                        Center = new PointF(circle.Center.X, circle.Center.Y),
                        LineWidth = 3,
                        CrossSize = 20,
                    };
                    this.drawingBoard2.CreatedShapes.Add(center);
                    circle.LineWidth = 2;
                    circle.PaintColor2 = Color.Red;
                    this.drawingBoard2.CreatedShapes.Add(circle);
                    this.drawingBoard2.Repaint();
                    this.dGV_Small9Point.Rows.Add();
                    this.dGV_Small9Point.Rows[this.dGV_Small9Point.Rows.Count - 1].Cells[0].Value = circle.Center.Y.ToString("0.0");
                    this.dGV_Small9Point.Rows[this.dGV_Small9Point.Rows.Count - 1].Cells[1].Value = circle.Center.X.ToString("0.0");
                }
            }
        }

        //bool firstShowBig = true;
        //bool firstShowSmall = true;
        //private void showImage(Bitmap bm)
        //{
        //    this.BeginInvoke(new Action(() =>
        //    {
        //        if (rB_Big.Checked)
        //        {
        //            drawingBoard1.OriginalImage = bm;
        //            if (firstShowBig)
        //            {
        //                drawingBoard1.Fit2Screen();
        //                firstShowBig = false;
        //            }
        //            firstShowSmall = true;
        //        }
        //        else
        //        {
        //            drawingBoard1.OriginalImage = bm;
        //            if (firstShowSmall)
        //            {
        //                drawingBoard1.Fit2Screen();
        //                firstShowSmall = false;
        //            }
        //            firstShowBig = true;
        //        }
        //    }));
        //}


        private void btn_ContiGrab_Click(object sender, EventArgs e)
        {
            if (selectBigCam)
            {
                if(BigCam.CameraMode == CameraMode.Auto)
                {
                    MessageBox.Show("请先切换至手动模式!", "相机采集", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                if (btn_ContiGrab.Text == "连续采集")
                {
                    BigCam.Grab(true);
                    btn_ContiGrab.Text = "停止采集";
                }
                else
                {
                    BigCam.Stop();
                    btn_ContiGrab.Text = "连续采集";
                }
            }
            else
            {
                if (SmallCam.CameraMode == CameraMode.Auto)
                {
                    MessageBox.Show("请先切换至手动模式!", "相机采集", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                if (btn_ContiGrab.Text == "连续采集")
                {
                    SmallCam.Grab(true);
                    btn_ContiGrab.Text = "停止采集";
                }
                else
                {
                    SmallCam.Stop();
                    btn_ContiGrab.Text = "连续采集";
                }
            }
        }

        private void btn_GrabImage_Click(object sender, EventArgs e)
        {
            drawingBoard1.CreatedShapes.Clear();
            if (selectBigCam)
            {
                if (BigCam.CameraMode == CameraMode.Auto)
                {
                    MessageBox.Show("请先切换至手动模式!", "相机采集", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                if (btn_ContiGrab.Text == "停止采集")
                {
                    MessageBox.Show("请先停止采集", "采集", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                BigCam.Grab(false);
            }
            else
            {
                if (SmallCam.CameraMode == CameraMode.Auto)
                {
                    MessageBox.Show("请先切换至手动模式!", "相机采集", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                if (btn_ContiGrab.Text == "停止采集")
                {
                    MessageBox.Show("请先停止采集", "采集", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                SmallCam.Grab(false);
            }
        }

        private bool selectBigCam = true;
        private void showImage()
        {
            bool first = true;
            Bitmap bmp = null;

            while (true)
            {
                if (!BigCam.GrabbedImages.IsEmpty && selectBigCam)
                {
                    BigCam.GrabbedImages.TryDequeue(out bmp);
                    drawingBoard1.OriginalImage = bmp;
                    if (first)
                    {
                        first = false;
                        drawingBoard1.Fit2Screen();
                    }
                }
                if (!SmallCam.GrabbedImages.IsEmpty && !selectBigCam)
                {
                    SmallCam.GrabbedImages.TryDequeue(out bmp);
                    drawingBoard2.OriginalImage = bmp;
                    if (first)
                    {
                        first = false;
                        drawingBoard2.Fit2Screen();
                    }
                }
                Thread.Sleep(1);
            }
        }
        private void calculateBig()
        {
            while(true)
            {
                if(!serverBig.RcvStrQueue.IsEmpty)
                {
                    string message = "";
                    lock(serverBig.RcvStrQueue)
                    {
                        serverBig.RcvStrQueue.TryDequeue(out message);
                    }
                    LogHelper.Info($"收到大视野相机客户端数据: {message}");
                    switch(message)
                    {
                        case "Request_Big_Cam\r\n":
                            LogHelper.Info("大视野相机拍照");
                            this.drawingBoard1.Clear();
                            LogHelper.Info("this.drawingBoard1.Clear()");
                            BigCam.SetExposureTime(4500);
                            LogHelper.Info("BigCam.SetExposureTime;");
                            while (!BigCam.Grab(false))
                            {
                                MessageBox.Show("大视野拍照失败!点击确定重拍", "大视野拍照", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                Thread.Sleep(100);
                            }
                            int emptyTimes = 0;
                            Thread.Sleep(100);
                            while (BigCam.AutoGrabbedImages.IsEmpty)
                            {
                                emptyTimes ;
                                SetRunLog("BigCam:" emptyTimes "");
                                Thread.Sleep(100);
                                if (emptyTimes > 50)
                                {
                                    SetRunLog("BigCam.AutoGrabbedImages.IsEmpty的while判断异常,直接NG处理。");
                                    break;
                                }
                            }
                            if (!BigCam.AutoGrabbedImages.IsEmpty)
                            {
                                Bitmap bmp;
                                BigCam.AutoGrabbedImages.TryDequeue(out bmp);
                                LogHelper.Info("BigCam.AutoGrabbedImages.TryDequeue(out bmp);");
                                bool isPastePositionAlreadyFound;

                                List<Rectangle2NB> labelRectsCandi;
                                long time;
                                VisionAlgrithom.BigSearch(VisionAlgrithom.Bitmap2HObjectBpp32(bmp),
                                                          GlobalVariable.CurrentSystemConfig.ReelLowVal, GlobalVariable.CurrentSystemConfig.ReelHighVal,
                                                          GlobalVariable.CurrentSystemConfig.BlueLowVal, GlobalVariable.CurrentSystemConfig.BlueHighVal,
                                                          GlobalVariable.CurrentSystemConfig.OrangeLowVal, GlobalVariable.CurrentSystemConfig.OrangeHighVal,
                                                          GlobalVariable.CurrentSystemConfig.YellowLowVal, GlobalVariable.CurrentSystemConfig.YellowHighVal,
                                                          35000, 100000,
                                                          128, 150, 180, 100000,
                                                          GlobalVariable.CurrentSystemConfig.BarcodeThreshold, GlobalVariable.CurrentSystemConfig.BarcodeWidth, 200, GlobalVariable.CurrentSystemConfig.AngleExtend, GlobalVariable.CurrentSystemConfig.ClosingArea,
                                                          out AllPasteRects,
                                                          out AllLabelRects,
                                                          out labelRectsCandi,
                                                          out time);
                                bmp.Save(@"D:\NGImageBig\" DateTime.Now.ToString("yyyyMMddhhmmssfff") ".bmp", System.Drawing.Imaging.ImageFormat.Bmp);
                                LogHelper.Info("bmp.Save");
                                //结果显示
                                this.drawingBoard1.OriginalImage = bmp;
                                this.drawingBoard2.Fit2Screen();
                                //是否找到了可贴标区,这几个变量自动运行时没用
                                IsPasteAreaFound = AllPasteRects != null && AllPasteRects.Count > 0;
                                if (AllPasteRects != null && AllPasteRects.Count > 0)
                                {
                                    for (int i = 0; i < AllPasteRects.Count; i )
                                    {
                                        AllPasteRects[i].LineWidth = 2;
                                        AllPasteRects[i].PaintColor2 = Color.Red;
                                        drawingBoard1.CreatedShapes.Add(AllPasteRects[i]);
                                        this.drawingBoard1.CreatedShapes.Add(new TextNB()
                                        {
                                            Angle = AllPasteRects[i].Angle,
                                            FontSize = 60,
                                            StartPoint = new PointF((float)AllPasteRects[i].Center.X, (float)AllPasteRects[i].Center.Y),
                                            Text = string.Format("R:{0},C:{1},A:{2}",
                                                                 AllPasteRects[i].Center.X.ToString("0.00"),
                                                                 AllPasteRects[i].Center.Y.ToString("0.00"),
                                                                 (AllPasteRects[i].Angle * 360 / 6.28).ToString("0.00")),
                                            PaintColor2 = Color.OrangeRed
                                        });
                                        this.drawingBoard1.CreatedShapes.Add(new PointNB()
                                        {
                                            LineWidth = 2,
                                            CrossSize = 30,
                                            Center = new PointF((float)AllPasteRects[i].Center.X, (float)AllPasteRects[i].Center.Y)
                                        });
                                        this.drawingBoard1.CreatedShapes.Add(new TextNB()
                                        {
                                            FontSize = 120,
                                            StartPoint = new PointF(20, 280),
                                            Text = string.Format("找到{0}个贴标区,如红色框所示!", AllPasteRects.Count),
                                            PaintColor2 = Color.LimeGreen
                                        });
                                        SetRunLog("找到" AllPasteRects.Count "个贴标区,如红色框所示!");
                                        //如果大视野直接找到了彩色标签 则可直接计算出贴标位置
                                        ////为了防止出现手动可以判断出需要覆盖的标签而自动状态获取不到,所做的措施。
                                        //bool isPastePositionAlreadyFoundBackup = false;
                                        ////贴标坐标
                                        //PointF pastePositionBackup = new PointF();
                                        ////贴标角度
                                        //double pasteAngleBackup = 0;
                                        //if (AllPasteRects != null && AllPasteRects.Count > 0)
                                        //{
                                        //    isPastePositionAlreadyFoundBackup = true;
                                        //    VisionAlgrithom.CalculatePasteWorldPosition(AllPasteRects[0], @"C:\", GlobalVariable.CurrentSystemConfig.BigAngleOffset, out pastePositionBackup, out pasteAngleBackup);
                                        //}
                                        //else
                                        //    isPastePositionAlreadyFoundBackup = false;
                                    }
                                }
                                //显示所有的找到的可能有条码的区域
                                if (AllLabelRects != null && AllLabelRects.Count > 0)
                                {
                                    for (int i = 0; i < AllLabelRects.Count; i )
                                    {
                                        AllLabelRects[i].LineWidth = 2;
                                        AllLabelRects[i].PaintColor2 = Color.Blue;
                                        drawingBoard1.CreatedShapes.Add(AllLabelRects[i]);
                                        this.drawingBoard1.CreatedShapes.Add(new TextNB()
                                        {
                                            Angle = AllLabelRects[i].Angle,
                                            FontSize = 60,
                                            StartPoint = new PointF((float)AllLabelRects[i].Center.X, (float)AllLabelRects[i].Center.Y),
                                            Text = string.Format("R:{0},C:{1},A:{2}",
                                                                 AllLabelRects[i].Center.X.ToString("0.00"),
                                                                 AllLabelRects[i].Center.Y.ToString("0.00"),
                                                                 (AllLabelRects[i].Angle * 360 / 6.28).ToString("0.00")),
                                            PaintColor2 = Color.OrangeRed
                                        });
                                        this.drawingBoard1.CreatedShapes.Add(new PointNB()
                                        {
                                            LineWidth = 2,
                                            CrossSize = 30,
                                            Center = new PointF((float)AllLabelRects[i].Center.X, (float)AllLabelRects[i].Center.Y)
                                        });
                                    }
                                    this.drawingBoard1.CreatedShapes.Add(new TextNB()
                                    {
                                        FontSize = 120,
                                        StartPoint = new PointF(20, 560),
                                        Text = string.Format("找到{0}个读条码区,如蓝色框所示!", AllLabelRects.Count),
                                        PaintColor2 = Color.LimeGreen
                                    });
                                }
                                bool showCandiReg = true;
                                if (showCandiReg)
                                {
                                    if (labelRectsCandi != null && labelRectsCandi.Count > 0)
                                    {
                                        for (int i = 0; i < labelRectsCandi.Count; i )
                                        {
                                            labelRectsCandi[i].LineWidth = 1;
                                            labelRectsCandi[i].PaintColor2 = Color.Pink;
                                            drawingBoard1.CreatedShapes.Add(labelRectsCandi[i]);
                                        }
                                    }
                                }
                                this.drawingBoard1.CreatedShapes.Add(new TextNB()
                                {
                                    FontSize = 120,
                                    StartPoint = new PointF(20, 730),
                                    Text = string.Format("总耗时: {0} ms", time),
                                    PaintColor2 = Color.White
                                });

                                //如果大视野直接找到了彩色标签 则可直接计算出贴标位置
                                //贴标坐标
                                PointF pastePosition = new PointF();
                                //贴标角度
                                double pasteAngle = 0;
                                if (AllPasteRects != null && AllPasteRects.Count > 0)
                                {
                                    isPastePositionAlreadyFound = true;
                                    VisionAlgrithom.CalculatePasteWorldPosition(AllPasteRects[0], @"C:\", GlobalVariable.CurrentSystemConfig.BigAngleOffset, out pastePosition, out pasteAngle);
                                    SetRunLog("isPastePositionAlreadyFound的值为 = " isPastePositionAlreadyFound);
                                    SetRunLog("大视野获取到所需覆盖标签的位置!");
                                }
                                else
                                {
                                    isPastePositionAlreadyFound = false;
                                    SetRunLog("isPastePositionAlreadyFound的值为 = " isPastePositionAlreadyFound);
                                    SetRunLog("大视野没有获取到所需覆盖标签的位置!");
                                }
                                List<PointF> labelPositions;
                                string sendStr;
                                //通过大视野读取到的可能条码区域 其中第一个为Reel标签区域(如果有的话),计算出小视野XY拍照位置
                                if (!VisionAlgrithom.CalculateLabelWorldPosition(AllLabelRects, ReelIdRect, @"C:\", out labelPositions))
                                {
                                    sendStr = "NG;\r\n";
                                }
                                else
                                {
                                    if (labelPositions != null && labelPositions.Count > 0)
                                    {
                                        sendStr = "OK;";
                                        if (isPastePositionAlreadyFound)
                                        {
                                            sendStr = $"{pastePosition.X.ToString("0.00")},{pastePosition.Y.ToString("0.00")},{pasteAngle.ToString("0.00")};";
                                            SetRunLog("大视野获取所需覆盖的标签坐标为 = " $"{pastePosition.X.ToString("0.00")},{pastePosition.Y.ToString("0.00")},{pasteAngle.ToString("0.00")};");
                                        }

                                        else
                                        {
                                            sendStr = "0,0,0;";
                                            SetRunLog("大视野获取所需覆盖的标签坐标为 = " "0,0,0;");
                                        }

                                        foreach (PointF rect in labelPositions)
                                        {
                                            sendStr = $"{rect.X.ToString("0.00")},{rect.Y.ToString("0.00")};";
                                        }
                                        sendStr = "\r\n";
                                    }
                                    else
                                        sendStr = "NG;\r\n";
                                }
                                SetRunLog("视觉发送字符串为 = " sendStr);
                                serverBig.Send(sendStr);
                                LogHelper.Info($"发送给大视野相机客户端: {sendStr}");
                            }
                            else
                            {
                                string sendStr = "NG;\r\n";
                                SetRunLog("大视野发送字符串为 = " sendStr);
                                SetRunLog("NG原因:BigCam.AutoGrabbedImages.IsEmpty");
                                serverBig.Send(sendStr);
                                LogHelper.Info($"发送给大视野相机客户端: {sendStr}");
                            }
                            break;
                    }
                }
                Thread.Sleep(2);
             }
        }
        private void calculateSmall()
        {
            while(true)
            {
                if (!serverSmall.RcvStrQueue.IsEmpty)
                {
                    LogHelper.Info("小视野相机拍照 !serverSmall.RcvStrQueue.IsEmpty");
                    string message = "";
                    LogHelper.Info("小视野相机拍照 serverSmall.RcvStrQueue");
                    lock (serverSmall.RcvStrQueue)
                    {
                        serverSmall.RcvStrQueue.TryDequeue(out message);
                        LogHelper.Info("小视野相机拍照 serverSmall.RcvStrQueue.TryDequeue(out message);");
                    }
                    SetRunLog($"收到小视野相机客户端数据: {message}");
                    LogHelper.Info($"收到小视野相机客户端数据: {message}");
                    SetRunLog("小视野开始拍照");
                    string sendStr = "";
                    if (message.Contains("Request_Small_Cam"))
                    {
                        SetRunLog("接收标准请求头Request_Small_Cam");
                        LogHelper.Info("小视野相机拍照");
                        this.drawingBoard2.Clear();
                        SetRunLog("this.drawingBoard2.Clear");
                        SmallCam.SetExposureTime(500);
                        while(!SmallCam.Grab(false))
                        {
                            MessageBox.Show("小视野拍照失败!点击确定重拍", "小视野拍照", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            Thread.Sleep(100);
                        }
                        Thread.Sleep(100);
                        int SmallCamEmptyTimes = 0;
                        while (SmallCam.AutoGrabbedImages.IsEmpty)
                        {
                            SmallCamEmptyTimes ;
                            SetRunLog("SmallCam:" SmallCamEmptyTimes "");
                            Thread.Sleep(100);
                            if (SmallCamEmptyTimes > 50)
                            {
                                SetRunLog("SmallCam.AutoGrabbedImages.IsEmpty的while判断异常,直接进入NG处理");
                                break;
                            }
                        }
                        if (!SmallCam.AutoGrabbedImages.IsEmpty)
                        {
                            Bitmap bmp;
                            SmallCam.AutoGrabbedImages.TryDequeue(out bmp);
                            //小视野典型字符串为:
                            //Request_Small_Cam;x,y,a;xc,yc,ac;
                            string[] strs = message.Split(';');
                            //reel是否已经由大视野相机找到
                            bool pastealreadyfound = strs[1] != "0,0,0";

                            List<string> barcodeStr;
                            List<Rectangle2NB> barcodeRects;
                            bool isExistReel;
                            string reel;
                            VisionAlgrithom.SmallRead(VisionAlgrithom.Bitmap2HObjectBpp32(bmp),
                                                      out barcodeStr,
                                                      out barcodeRects,
                                                      out PasteRect,
                                                      out isExistReel,
                                                      out reel);
                            bmp.Save(@"D:\NGImageSmall\" DateTime.Now.ToString("yyyyMMddhhmmssfff") ".bmp", System.Drawing.Imaging.ImageFormat.Bmp);
                            this.drawingBoard2.OriginalImage = bmp;
                            this.drawingBoard2.Fit2Screen();
                            if (barcodeRects != null && barcodeRects.Count > 0)
                            {
                                for (int i = 0; i < barcodeRects.Count; i )
                                {
                                    barcodeRects[i].LineWidth = 1;
                                    barcodeRects[i].PaintColor2 = Color.Blue;
                                    drawingBoard2.CreatedShapes.Add(barcodeRects[i]);
                                    this.drawingBoard2.CreatedShapes.Add(new TextNB()
                                    {
                                        FontSize = 45,
                                        StartPoint = new PointF((float)barcodeRects[i].Center.X, (float)barcodeRects[i].Center.Y),
                                        Angle = barcodeRects[i].Angle,
                                        Text = string.Format(barcodeStr[i]),
                                        PaintColor2 = Color.OrangeRed
                                    });
                                    this.drawingBoard2.CreatedShapes.Add(new PointNB()
                                    {
                                        LineWidth = 2,
                                        CrossSize = 30,
                                        Center = new PointF((float)barcodeRects[i].Center.X, (float)barcodeRects[i].Center.Y)
                                    });
                                }
                            }
                            if (PasteRect != null)
                            {
                                PasteRect.LineWidth = 2;
                                PasteRect.PaintColor2 = Color.White;
                                this.drawingBoard2.CreatedShapes.Add(PasteRect);
                            }

                            if (!isExistReel)
                            {
                                sendStr = "NG;\r\n";
                                serverSmall.Send(sendStr);
                                SetRunLog($"发送小视野相机客户端数据: {sendStr}");
                                LogHelper.Info($"发送小视野相机客户端数据: {sendStr}");
                            }
                            else
                            {
                                PointF pastePosition;
                                double pasteAngle;
                                if (pastealreadyfound)
                                    sendStr = $"OK;{reel};{strs[1]}\r\n";
                                else
                                {
                                    PointF currentSmallHeadWorld = new PointF(Convert.ToSingle(strs[2].Split(',')[0]), Convert.ToSingle(strs[2].Split(',')[1]));
                                    VisionAlgrithom.CalculatePasteWorldPosition2(PasteRect, @"C:\", currentSmallHeadWorld, GlobalVariable.CurrentSystemConfig.SmallAngleOffset, out pastePosition, out pasteAngle);
                                    sendStr = $"OK;{reel};{pastePosition.X.ToString("0.00")},{pastePosition.Y.ToString("0.00")},{pasteAngle.ToString("0.00")};\r\n";
                                }
                                serverSmall.Send(sendStr);
                                SetRunLog($"发送小视野相机客户端数据: {sendStr} , 原因为SmallCam.AutoGrabbedImages.IsEmpty");
                                LogHelper.Info($"发送小视野相机客户端数据: {sendStr}");
                            }
                        }
                        else
                        {
                            sendStr = "NG;\r\n";
                            serverSmall.Send(sendStr);
                            SetRunLog($"发送小视野相机客户端数据: {sendStr}");
                            LogHelper.Info($"发送小视野相机客户端数据: {sendStr}");
                        }
                    }
                    else
                    {
                        sendStr = "NG;\r\n";
                        serverSmall.Send(sendStr);
                        SetRunLog("请求头不符合要求;此盘NG!");
                    }
                }
                Thread.Sleep(2);
            }
        }

        public void showComStatus(string message, string posorneg)
        {
            this.BeginInvoke(new Action(() =>
            {
                if(posorneg == "Big")
                    tSSL_ComStatus.Text = message;
                if (posorneg == "Small")
                    tSSL_ComStatus2.Text = message;
            }));
        }

        //关闭
        private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            serverBig.Close();
            serverSmall.Close();
            if (BigCam != null)
            {
                BigCam.Stop();
                BigCam.Close();
            }
            if (SmallCam != null)
            {
                SmallCam.Stop();
                SmallCam.Close();
            }
            if (showImageThread != null)
                showImageThread.Abort();
            if (calculateBigThread != null)
                calculateBigThread.Abort();
            if (calculateSmallThread != null)
                calculateSmallThread.Abort();
        }

        private void rB_Big_CheckedChanged(object sender, EventArgs e)
        {
            //if (rB_Big.Checked)
            //    nUD_Exposure.Value = (decimal)BigCam.GetExposureTime();
        }

        private void rB_Small_CheckedChanged(object sender, EventArgs e)
        {
            //if (rB_Small.Checked)
            //    nUD_Exposure.Value = (decimal)SmallCam.GetExposureTime();
        }

        private void groupBox5_Enter(object sender, EventArgs e)
        {

        }

        private void btn_SaveImage_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "图像文件(*.bmp)|*.bmp";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                if(selectBigCam)
                    this.drawingBoard1.OriginalImage.Save(sfd.FileName, System.Drawing.Imaging.ImageFormat.Bmp);
                else
                    this.drawingBoard2.OriginalImage.Save(sfd.FileName, System.Drawing.Imaging.ImageFormat.Bmp);
                //MessageBox.Show("保存成功!", "保存", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void nUD_Exposure_ValueChanged(object sender, EventArgs e)
        {
            
        }

        private void btn_SetExposure_Click(object sender, EventArgs e)
        {
            if (selectBigCam)
            {
                BigCam.SetExposureTime((float)nUD_Exposure.Value);
            }
            else
            {
                SmallCam.SetExposureTime((float)nUD_Exposure.Value);
            }
        }

        private void btn_AddCoordinate_Click(object sender, EventArgs e)
        {
            if (tC_9Point.SelectedTab == tP_Small)
            {
                this.dGV_Small9Point.Rows.Add();
                this.dGV_Small9Point.Rows[this.dGV_Small9Point.Rows.Count - 1].Cells[0].Value = "0.0";
                this.dGV_Small9Point.Rows[this.dGV_Small9Point.Rows.Count - 1].Cells[1].Value = "0.0";
            }
            else if (tC_9Point.SelectedTab == tP_Paste)
            {
                this.dGV_Paste9Point.Rows.Add();
                this.dGV_Paste9Point.Rows[this.dGV_Paste9Point.Rows.Count - 1].Cells[0].Value = "0.0";
                this.dGV_Paste9Point.Rows[this.dGV_Paste9Point.Rows.Count - 1].Cells[1].Value = "0.0";
            }
            else if (tC_9Point.SelectedTab == tP_SmallXY)
            {
                this.dGV_SmallXY9Point.Rows.Add();
                this.dGV_SmallXY9Point.Rows[this.dGV_SmallXY9Point.Rows.Count - 1].Cells[0].Value = "0.0";
                this.dGV_SmallXY9Point.Rows[this.dGV_SmallXY9Point.Rows.Count - 1].Cells[1].Value = "0.0";
            }
        }

        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (tC_9Point.SelectedTab == tP_Small && dGV_Small9Point.SelectedRows.Count > 0)
            {
                dGV_Small9Point.Rows.Remove(dGV_Small9Point.SelectedRows[0]);
            }
            else if (tC_9Point.SelectedTab == tP_Paste && dGV_Paste9Point.SelectedRows.Count > 0)
            {
                dGV_Paste9Point.Rows.Remove(dGV_Paste9Point.SelectedRows[0]);
            }
            else if (tC_9Point.SelectedTab == tP_Big && dGV_BigPixel9Point.SelectedRows.Count > 0)
            {
                dGV_BigPixel9Point.Rows.Remove(dGV_BigPixel9Point.SelectedRows[0]);
            }
        }

        private void btn_Cali_Click_1(object sender, EventArgs e)
        {
            if((cB_Cam1.SelectedItem.ToString() == "大视野" ||
                cB_Cam2.SelectedItem.ToString() == "大视野" ) &&
                dGV_BigPixel9Point.Rows.Count < 6)
            {
                MessageBox.Show("标定点数不足!请增加标定点或坐标点!");
                return;
            }
            if ((cB_Cam1.SelectedItem.ToString() == "小视野" ||
                 cB_Cam2.SelectedItem.ToString() == "小视野") &&
                 dGV_Small9Point.Rows.Count < 6)
            {
                MessageBox.Show("标定点数不足!请增加标定点或坐标点!");
                return;
            }
            if ((cB_Cam1.SelectedItem.ToString() == "贴标头" ||
                 cB_Cam2.SelectedItem.ToString() == "贴标头") &&
                 dGV_Paste9Point.Rows.Count < 6)
            {
                MessageBox.Show("标定点数不足!请增加标定点或坐标点!");
                return;
            }
            if(cB_Cam1.SelectedItem.ToString() == "大视野" &&
               cB_Cam2.SelectedItem.ToString() == "小视野" &&
               (dGV_BigPixel9Point.Rows.Count != dGV_Small9Point.Rows.Count))
            {
                MessageBox.Show("标定点数不相等!");
                return;
            }
            if (cB_Cam1.SelectedItem.ToString() == "小视野" &&
                cB_Cam2.SelectedItem.ToString() == "贴标头" &&
               (dGV_Paste9Point.Rows.Count != dGV_Small9Point.Rows.Count))
            {
                MessageBox.Show("标定点数不相等!");
                return;
            }


            //大视野找条码区域,小视野移动过去拍照   两个相机间的标定
            if (cB_Cam1.SelectedItem.ToString() == "大视野" &&
                cB_Cam2.SelectedItem.ToString() == "小视野")
            {
                PointF[] crdFrom = new PointF[dGV_BigPixel9Point.Rows.Count];
                PointF[] crdTo = new PointF[dGV_BigPixel9Point.Rows.Count];
                int index = 0;
                foreach(DataGridViewRow dgvr in dGV_BigPixel9Point.Rows)
                {
                    crdFrom[index] = new PointF();
                    crdFrom[index].X = (float)Convert.ToDouble(dgvr.Cells[0].Value.ToString());
                    crdFrom[index].Y = (float)Convert.ToDouble(dgvr.Cells[1].Value.ToString());
                    index ;
                }
                index = 0;
                foreach (DataGridViewRow dgvr in dGV_Small9Point.Rows)
                {
                    crdTo[index] = new PointF();
                    crdTo[index].X = (float)Convert.ToDouble(dgvr.Cells[0].Value.ToString());
                    crdTo[index].Y = (float)Convert.ToDouble(dgvr.Cells[1].Value.ToString());
                    index ;
                }

                VisionAlgrithom.NinePointsCalibrate("Big", "Small", @"C:\", crdFrom, crdTo);
            }

            //大视野找到彩色标签,直接确定贴标位置
            if (cB_Cam1.SelectedItem.ToString() == "大视野" &&
                cB_Cam2.SelectedItem.ToString() == "贴标头")
            {
                PointF[] crdFrom = new PointF[dGV_BigPixel9Point.Rows.Count];
                PointF[] crdTo = new PointF[dGV_Paste9Point.Rows.Count];
                int index = 0;
                foreach (DataGridViewRow dgvr in dGV_BigPixel9Point.Rows)
                {
                    crdFrom[index] = new PointF();
                    crdFrom[index].X = (float)Convert.ToDouble(dgvr.Cells[0].Value.ToString());
                    crdFrom[index].Y = (float)Convert.ToDouble(dgvr.Cells[1].Value.ToString());
                    index ;
                }
                index = 0;
                foreach (DataGridViewRow dgvr in dGV_Paste9Point.Rows)
                {
                    crdTo[index] = new PointF();
                    crdTo[index].X = (float)Convert.ToDouble(dgvr.Cells[0].Value.ToString());
                    crdTo[index].Y = (float)Convert.ToDouble(dgvr.Cells[1].Value.ToString());
                    index ;
                }
                VisionAlgrithom.NinePointsCalibrate("Big", "Paste", @"C:\", crdFrom, crdTo);
            }

            //小视野XY和贴标头XY之间的标定 
            if (cB_Cam1.SelectedItem.ToString() == "小视野XY" &&
                cB_Cam2.SelectedItem.ToString() == "贴标头")
            {
                PointF[] crdFrom = new PointF[dGV_SmallXY9Point.Rows.Count];
                PointF[] crdTo = new PointF[dGV_SmallXY9Point.Rows.Count];
                int index = 0;
                foreach (DataGridViewRow dgvr in dGV_SmallXY9Point.Rows)
                {
                    crdFrom[index] = new PointF();
                    crdFrom[index].X = (float)Convert.ToDouble(dgvr.Cells[0].Value.ToString());
                    crdFrom[index].Y = (float)Convert.ToDouble(dgvr.Cells[1].Value.ToString());
                    index ;
                }
                index = 0;
                foreach (DataGridViewRow dgvr in dGV_Paste9Point.Rows)
                {
                    crdTo[index] = new PointF();
                    crdTo[index].X = (float)Convert.ToDouble(dgvr.Cells[0].Value.ToString());
                    crdTo[index].Y = (float)Convert.ToDouble(dgvr.Cells[1].Value.ToString());
                    index ;
                }

                VisionAlgrithom.NinePointsCalibrate("SmallHeader", "Paste", @"C:\", crdFrom, crdTo);
            }
            //小视野 相机和小视野XY之间的标定
            if (cB_Cam1.SelectedItem.ToString() == "小视野" &&
                cB_Cam2.SelectedItem.ToString() == "小视野XY")
            {
                PointF[] crdFrom = new PointF[dGV_SmallXY9Point.Rows.Count];
                PointF[] crdTo = new PointF[dGV_SmallXY9Point.Rows.Count];
                int index = 0;
                foreach (DataGridViewRow dgvr in dGV_Small9Point.Rows)
                {
                    crdFrom[index] = new PointF();
                    crdFrom[index].X = (float)Convert.ToDouble(dgvr.Cells[0].Value.ToString());
                    crdFrom[index].Y = (float)Convert.ToDouble(dgvr.Cells[1].Value.ToString());
                    index ;
                }
                index = 0;
                foreach (DataGridViewRow dgvr in dGV_SmallXY9Point.Rows)
                {
                    crdTo[index] = new PointF();
                    crdTo[index].X = (float)Convert.ToDouble(dgvr.Cells[0].Value.ToString());
                    crdTo[index].Y = (float)Convert.ToDouble(dgvr.Cells[1].Value.ToString());
                    index ;
                }

                VisionAlgrithom.NinePointsCalibrate("Small", "SmallHeader", @"C:\", crdFrom, crdTo);
            }
        }

        private void btn_LabelCrd_Click(object sender, EventArgs e)
        {
            List<PointF> labelPositions;
            //通过大视野读取到的可能条码区域 及 Reel区域(如果有的话),计算出小视野XY拍照位置
            if (!VisionAlgrithom.CalculateLabelWorldPosition(AllLabelRects, ReelIdRect, @"C:\", out labelPositions))
            {
                MessageBox.Show("找不到可以读码的区域!", "位置", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            //PointF point = new PointF();
            //VisionAlgrithom.ConvertCoordinate("Big", "Small", @"C:\", new PointF(1633f, 2849F), out point);
            if (labelPositions != null && labelPositions.Count > 0)
            {
                string str = "";
                foreach (PointF p in labelPositions)
                {
                    str = p.X.ToString("0.00") "," p.Y.ToString("0.00") "\n";
                }
                MessageBox.Show(str, "位置", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void btn_BarCrd_Click(object sender, EventArgs e)
        {
            if(PasteRectOld == null && PasteRect == null)
            {
                MessageBox.Show("请先进行读码!", "贴标坐标", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            PointF pastePosition = new PointF();
            double pasteAngle = 0;
            if (PasteRectOld != null)
                VisionAlgrithom.CalculatePasteWorldPosition(PasteRectOld, @"C:\", GlobalVariable.CurrentSystemConfig.BigAngleOffset, out pastePosition, out pasteAngle);
            else if (PasteRect != null)
                VisionAlgrithom.CalculatePasteWorldPosition2(PasteRect, @"C:\", new PointF(95.91f,92.78f), GlobalVariable.CurrentSystemConfig.SmallAngleOffset, out pastePosition, out pasteAngle);
            PasteRectOld = null;
            PasteRect = null;

            string str = pastePosition.X.ToString("0.00") "," pastePosition.Y.ToString("0.00") "," pasteAngle.ToString("0.00") "\n";
            MessageBox.Show(str, "位置", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void btn_SetBigParam_Click(object sender, EventArgs e)
        {
            FormBigParam bigParam = new FormBigParam(GlobalVariable.CurrentSystemConfig.ReelHighVal,
                                                     GlobalVariable.CurrentSystemConfig.ReelLowVal,
                                                     GlobalVariable.CurrentSystemConfig.BlueHighVal,
                                                     GlobalVariable.CurrentSystemConfig.BlueLowVal,
                                                     GlobalVariable.CurrentSystemConfig.OrangeHighVal,
                                                     GlobalVariable.CurrentSystemConfig.OrangeLowVal,
                                                     GlobalVariable.CurrentSystemConfig.YellowHighVal,
                                                     GlobalVariable.CurrentSystemConfig.YellowLowVal,
                                                     GlobalVariable.CurrentSystemConfig.BarcodeThreshold,
                                                     GlobalVariable.CurrentSystemConfig.BarcodeWidth,
                                                     GlobalVariable.CurrentSystemConfig.AngleExtend,
                                                     GlobalVariable.CurrentSystemConfig.ClosingArea);
            if(bigParam.ShowDialog() == DialogResult.OK)
            {
                GlobalVariable.CurrentSystemConfig.ReelHighVal = bigParam.ReelHighVal;
                GlobalVariable.CurrentSystemConfig.ReelLowVal = bigParam.ReelLowVal;
                GlobalVariable.CurrentSystemConfig.BlueHighVal = bigParam.BlueHighVal;
                GlobalVariable.CurrentSystemConfig.BlueLowVal = bigParam.BlueLowVal;
                GlobalVariable.CurrentSystemConfig.OrangeHighVal = bigParam.OrangeHighVal;
                GlobalVariable.CurrentSystemConfig.OrangeLowVal = bigParam.OrangeLowVal;
                GlobalVariable.CurrentSystemConfig.YellowHighVal = bigParam.YellowHighVal;
                GlobalVariable.CurrentSystemConfig.YellowLowVal = bigParam.YellowLowVal;
                GlobalVariable.CurrentSystemConfig.BarcodeThreshold = bigParam.BarcodeThreshold;
                GlobalVariable.CurrentSystemConfig.BarcodeWidth = bigParam.BarcodeWidth;
                GlobalVariable.CurrentSystemConfig.AngleExtend = bigParam.AngleExtend;
                GlobalVariable.CurrentSystemConfig.ClosingArea = bigParam.ClosingArea;
                SystemConfig.Save(@"C:\\test.xml", GlobalVariable.CurrentSystemConfig);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            drawingBoard1.DrawRectangle2 = true;
        }

        private void tSSL_Auto_MouseDown(object sender, MouseEventArgs e)
        {
            if(tSSL_Auto.Text == "自动运行中")
            {
                tSSL_Auto.BorderStyle = Border3DStyle.Raised;
                tSSL_Auto.Text = "手动运行中";
                tSSL_Auto.BackColor = Color.Yellow;
            }
            else
            {
                tSSL_Auto.BorderStyle = Border3DStyle.Sunken;
                tSSL_Auto.Text = "自动运行中";
                tSSL_Auto.BackColor = Color.LimeGreen;
            }
        }

        private void btn_LoadCali_Click(object sender, EventArgs e)
        {

        }

        private void cB_Rectangle_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked)
            {
                BigCam.CameraMode = CameraMode.Manual;
                SmallCam.CameraMode = CameraMode.Manual;
            }
            else
            {
                BigCam.CameraMode = CameraMode.Auto;
                SmallCam.CameraMode = CameraMode.Auto;
            }
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabControl1.SelectedTab == tabPage1)
                selectBigCam = true;
            else
                selectBigCam = false;
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            if (cB_Cam1.SelectedIndex == -1)
                return;
            if (cB_Cam2.SelectedIndex == -1)
                return;
            PointF srcPoint = new PointF(Convert.ToSingle(textBox1.Text), Convert.ToSingle(textBox2.Text));
            PointF dstPoint = new PointF();
            string convertFrom = "";
            string convertTo = "";
            if (cB_Cam1.Text == "小视野")
                convertFrom = "Small";
            else if (cB_Cam1.Text == "小视野XY")
                convertFrom = "SmallHeader";
            if (cB_Cam2.Text == "小视野XY")
                convertTo = "SmallHeader";
            else if(cB_Cam2.Text == "贴标头")
                convertTo = "Paste";
            VisionAlgrithom.ConvertCoordinate(convertFrom, convertTo, @"C:\", srcPoint, out dstPoint);
            PointF centerPoint = new PointF(1032f, 1544f);
            PointF centerWorldPoint = new PointF();
            VisionAlgrithom.ConvertCoordinate(convertFrom, convertTo, @"C:\", centerPoint, out centerWorldPoint);
            float dx = centerWorldPoint.X - dstPoint.X Convert.ToSingle(textBox4.Text);
            float dy = centerWorldPoint.Y - dstPoint.Y Convert.ToSingle(textBox3.Text);
            //PointF markPoint = new PointF(dstPoint.X dx, dstPoint.Y dy);
            //PointF finalPoint = new PointF(dstPoint.X )
            MessageBox.Show($"{dx},{dy}");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            serverSmall.Send("hello world");
        }

        private void nUD_BigAngleOffset_ValueChanged(object sender, EventArgs e)
        {
            GlobalVariable.CurrentSystemConfig.BigAngleOffset = (double)nUD_BigAngleOffset.Value;
            SystemConfig.Save(@"C:\\test.xml", GlobalVariable.CurrentSystemConfig);
        }

        private void nUD_SmallAngleOffset_ValueChanged(object sender, EventArgs e)
        {
            GlobalVariable.CurrentSystemConfig.SmallAngleOffset = (double)nUD_SmallAngleOffset.Value;
            SystemConfig.Save(@"C:\\test.xml", GlobalVariable.CurrentSystemConfig);
        }

        #region 显示运行记录
        private void SetRunLog(string mRunTest)
        {
            //pLog.WriteLog(mRunTest, "RunLog");
            SetRichTextFunction(rTB_SysInfo, mRunTest, Color.Green, "RunLog");
            Thread.Sleep(20);
        }


        private void SetRichTextFunction(RichTextBox pButton, string mStr, Color pColor, string iType)
        {
            if (pButton == null)
            {
                throw new ArgumentNullException(nameof(pButton));
            }

            if (pButton.InvokeRequired)
            {
                SetRichTextSN ss = new SetRichTextSN(SetRichTextFunction);
                BeginInvoke(ss, new object[] { pButton, mStr, pColor, iType });
            }
            else
            {
                if (pButton.TextLength >= 65530)
                {
                    pButton.Text = string.Empty;
                }
                pButton.AppendText(DateTime.Now.ToString("HH:mm:ss  ") mStr System.Environment.NewLine);
                if (pButton.Text.LastIndexOf(mStr) >= 0 && mStr.Length > 0)
                {
                    pButton.Select(pButton.Text.LastIndexOf(mStr), mStr.Length);
                    pButton.SelectionColor = pColor;
                    pButton.SelectionLength = mStr.Length;
                }
                pButton.ScrollToCaret();
                pLog.WriteLog(mStr, iType);

            }
        }
        #endregion

    }
}


标签: BASLER C# dev Halcon

实例下载地址

一个视觉定位的贴标机项目实例

不能下载?内容有错? 点击这里报错 + 投诉 + 提问

好例子网口号:伸出你的我的手 — 分享

网友评论

发表评论

(您的评论需要经过审核才能显示)

查看所有0条评论>>

小贴士

感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。

  • 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
  • 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
  • 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
  • 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。

关于好例子网

本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

;
报警