示例#1
0
 private void SaveParaBtn_Click(object sender, EventArgs e)
 {
     if (TeachCirclePara.CenterRows.Count - 1 < CircleNum)
     {
         this.TeachCirclePara.CenterRows.Add(TeachCenterRow);
         this.TeachCirclePara.CenterCols.Add(TeachCenterCol);
         this.TeachCirclePara.CircleRs.Add(TeachCircleR);
         this.TeachCirclePara.DetectHeights.Add(DetectHeight);
         this.TeachCirclePara.Elements.Add(Element);
         this.TeachCirclePara.Thresholds.Add(Threshold);
         this.TeachCirclePara.Directs.Add(Direct.ToString());
         this.TeachCirclePara.StartPhis.Add(TeachStartPhi);
         this.TeachCirclePara.EndPhis.Add(TeachEndPhi);
         this.TeachCirclePara.PointOrders.Add(TeachPointOrderStr);
         this.TeachCirclePara.Directs.Add(Direct.S);
     }
     else if (TeachCirclePara.CenterRows.Count - 1 >= CircleNum)
     {
         this.TeachCirclePara.CenterRows[CircleNum]    = TeachCenterRow;
         this.TeachCirclePara.CenterCols[CircleNum]    = TeachCenterCol;
         this.TeachCirclePara.CircleRs[CircleNum]      = TeachCircleR;
         this.TeachCirclePara.DetectHeights[CircleNum] = DetectHeight;
         this.TeachCirclePara.Elements[CircleNum]      = Element;
         this.TeachCirclePara.Thresholds[CircleNum]    = Threshold;
         this.TeachCirclePara.Directs[CircleNum]       = Direct.ToString();
         this.TeachCirclePara.StartPhis[CircleNum]     = TeachStartPhi;
         this.TeachCirclePara.EndPhis[CircleNum]       = TeachEndPhi;
         this.TeachCirclePara.PointOrders[CircleNum]   = TeachPointOrderStr;
         this.TeachCirclePara.Directs[CircleNum]       = Direct.S;
     }
 }
示例#2
0
        /// <summary>
        /// Action for this instance.
        /// </summary>
        private void Action()
        {
            // Local iconic variables
            HObject ho_ImageGrayRamp, ho_RegionLines, ho_RegionComplement;
            HObject ho_ConnectedRegions;

            // Local control variables
            HTuple hv_Number = null;

            // Initialize local and output iconic variables
            HOperatorSet.GenEmptyObj(out ho_ImageGrayRamp);
            HOperatorSet.GenEmptyObj(out ho_RegionLines);
            HOperatorSet.GenEmptyObj(out ho_RegionComplement);
            HOperatorSet.GenEmptyObj(out ho_ConnectedRegions);
            ho_ImageGrayRamp.Dispose();
            HOperatorSet.GenImageGrayRamp(out ho_ImageGrayRamp, 0, 0, 128, 256, 256, 512, 512);
            HImage ImageGrayRamp = new HImage(ho_ImageGrayRamp);

            // Cast using as operator

            // Traditional cast
            ho_RegionLines.Dispose();
            HOperatorSet.GenRegionLine(out ho_RegionLines, 100, -1, 150, 512);
            HRegion RegionLines = new HRegion(ho_RegionLines);

            ho_RegionComplement.Dispose();
            HOperatorSet.Complement(ho_RegionLines, out ho_RegionComplement);
            HRegion RegionComplement = new HRegion(ho_RegionComplement);

            HOperatorSet.SetSystem("neighborhood", 4);
            ho_ConnectedRegions.Dispose();
            HOperatorSet.Connection(ho_RegionComplement, out ho_ConnectedRegions);
            HRegion ConnectedRegions = new HRegion(ho_ConnectedRegions);

            ImageGrayRamp.DispImage(HalconWindow1);
            ConnectedRegions.DispRegion(HalconWindow1);
            RegionLines.DispRegion(HalconWindow1);

            // Should be two objects
            HOperatorSet.CountObj(ho_ConnectedRegions, out hv_Number);
            label1.Text = "Number of objects 4-connected:" + hv_Number.ToString();

            HOperatorSet.SetSystem("neighborhood", 8);
            ConnectedRegions.Dispose();
            ConnectedRegions = RegionComplement.Connection();

            ImageGrayRamp.DispImage(HalconWindow2);
            ConnectedRegions.DispRegion(HalconWindow2);
            RegionLines.DispRegion(HalconWindow2);

            // Should be a single object
            hv_Number   = ConnectedRegions.CountObj();
            label2.Text = "Number of objects 8-connected:" + hv_Number.ToString();

            ho_ImageGrayRamp.Dispose();
            ho_RegionLines.Dispose();
            ho_RegionComplement.Dispose();
            ho_ConnectedRegions.Dispose();
        }
示例#3
0
        private void ProcessImage(Object ob)
        {
            lock (locker)
            {
                HDevelopExport hd  = new HDevelopExport();
                HTuple         res = hd.RunHalcon((bool)ob);

                String[] date = res.ToString().Remove(0, 1).Remove(res.ToString().Length - 2, 1).Split(',');
                setvalue(date);
            }
        }
示例#4
0
        private void SearchObject(HTuple TempModelID, HObject SearchImage)
        {
            try
            {
                HTuple hv_RefRow = null, hv_RefColumn = null, hv_RefAngle = null, hv_Score = null;
                HOperatorSet.FindShapeModel(SearchImage, TempModelID, (new HTuple(0)).TupleRad(), (new HTuple(360)).TupleRad(), 0.5, 1, 0.5, "least_squares", (new HTuple(6)).TupleConcat(1), 0.75, out hv_RefRow, out hv_RefColumn, out hv_RefAngle, out hv_Score);

                //获取模版中对象轮廓
                HObject ho_ModelContours;
                HOperatorSet.GenEmptyObj(out ho_ModelContours);
                HOperatorSet.GetShapeModelContours(out ho_ModelContours, hv_ModelID, 1);

                //构建一个仿射变换矩阵
                HTuple hv_HomMat2D = null;
                HOperatorSet.VectorAngleToRigid(0, 0, 0, hv_RefRow, hv_RefColumn, 0, out hv_HomMat2D);

                //对图像左上角对象轮廓进行仿射变换,将轮廓平移到产品位置
                HObject ho_TransContours;
                HOperatorSet.GenEmptyObj(out ho_TransContours);
                HOperatorSet.AffineTransContourXld(ho_ModelContours, out ho_TransContours, hv_HomMat2D);


                GraphInteractiveObect.graphic_stackClear();
                VideoWindow_hWindowControl.HalconWindow.ClearWindow();

                HOperatorSet.SetColor(GraphInteractiveObect.halconWindow.HalconWindow, "yellow");
                HOperatorSet.SetDraw(GraphInteractiveObect.halconWindow.HalconWindow, "margin");
                HOperatorSet.DispObj(SearchImage, GraphInteractiveObect.halconWindow.HalconWindow);
                HOperatorSet.DispObj(ho_TransContours, GraphInteractiveObect.halconWindow.HalconWindow);

                HOperatorSet.SetColor(GraphInteractiveObect.halconWindow.HalconWindow, "blue");
                HOperatorSet.SetDraw(GraphInteractiveObect.halconWindow.HalconWindow, "fill");
                HOperatorSet.DispLine(GraphInteractiveObect.halconWindow.HalconWindow, hv_RefRow, hv_RefColumn - 100, hv_RefRow, hv_RefColumn + 100);
                HOperatorSet.DispLine(GraphInteractiveObect.halconWindow.HalconWindow, hv_RefRow - 100, hv_RefColumn, hv_RefRow + 100, hv_RefColumn);

                this.ModelRow_textBox.Text    = hv_RefRow.ToString();
                this.txtRow.Text              = hv_RefRow.ToString();
                this.ModelColumn_textBox.Text = hv_RefColumn.ToString();
                this.txtCol.Text              = hv_RefColumn.ToString();
                this.ModelAngle_textBox.Text  = hv_RefAngle.ToString();
                this.txtAngle.Text            = hv_RefAngle.ToString();

                HOperatorSet.SetColor(GraphInteractiveObect.halconWindow.HalconWindow, "yellow");
                HOperatorSet.SetDraw(GraphInteractiveObect.halconWindow.HalconWindow, "margin");
                saveImage("Pos");
                ho_ModelContours.Dispose();
                ho_TransContours.Dispose();
            }
            catch (HalconException ex)
            {
            }
        }
        /// <summary>
        /// 批量处理并显示图像线程
        /// </summary>
        private void ImagePreprocessThreading()
        {
            //Loop through all images,
            //preprocess and then write them.
            HObject ho_Image = new HObject(); HObject ho_ImagePreprocessed = new HObject();

            for (HTuple hv_ImageIndex = 0; (int)hv_ImageIndex <= (hv_ImageFiles.TupleLength() - 1); hv_ImageIndex = (int)hv_ImageIndex + 1)
            {
                //显示原图像
                using (HDevDisposeHelper dh = new HDevDisposeHelper())
                {
                    ho_Image.Dispose();
                    HOperatorSet.ReadImage(out ho_Image, hv_ImageFiles.TupleSelect(hv_ImageIndex));
                    DispImageAdaptively(ref hv_HWindowControl, ho_Image);
                    HOperatorSet.DispText(hv_HWindowControl.HalconWindow, "ImagesPreprocessing:" + hv_ImageIndex, "window", "top", "left", "red", "box", "true");
                    Console.WriteLine(hv_ImageIndex.ToString());
                }
                ho_ImagePreprocessed.Dispose();

                //预处理图像
                PreprocessImage(this.hv_Pretrained_DlClassifierName, ho_Image, out ho_ImagePreprocessed);

                //保存预处理后图像
                using (HDevDisposeHelper dh = new HDevDisposeHelper())
                {
                    HOperatorSet.WriteObject(ho_ImagePreprocessed, hv_ObjectFilesOut.TupleSelect(hv_ImageIndex));
                }
            }
            HOperatorSet.DispText(this.hv_WindowHandle, "Preprocessing over,Click to continue...", "window", "bottom", "right", "red", "box", "false");
        }
示例#6
0
        private void load_parm()
        {
            if (FL_data.in_row != null)
            {
                Hrow = FL_data.in_row;
                Hcol = FL_data.in_col;
                Hphi = FL_data.in_phi;
                L1   = FL_data.L1;
                L2   = FL_data.L2;
            }
            Hnum        = FL_data.Hnum;
            Hwid        = FL_data.Hwid;
            Hamp        = FL_data.Hamp;
            Hsomth      = FL_data.Hsomth;
            Htransition = FL_data.Htransition;
            Hselect     = FL_data.Hselect;
            data_row    = FL_data.data_row;
            data_col    = FL_data.data_col;
            data_phi    = FL_data.data_phi;

            NUM_UpDown.Value = (decimal)Hnum[0].I;
            trackBar1.Value  = (int)NUM_UpDown.Value;
            Wid_UpDown.Value = (decimal)Hwid[0].I;
            trackBar2.Value  = (int)Wid_UpDown.Value;
            Amp_UpDown.Value = (decimal)Hamp[0].I;
            trackBar3.Value  = (int)Amp_UpDown.Value;
            Som_UpDown.Value = (decimal)Hsomth[0].D;
            trackBar4.Value  = (int)(Som_UpDown.Value * 10);
            comboBox1.Text   = Htransition;
            comboBox2.Text   = Hselect;
            textBox1.Text    = data_row.ToString();
            textBox2.Text    = data_col.ToString();
            textBox3.Text    = data_phi.ToString();
        }
示例#7
0
        private void HwindowShow_HMouseDown(object sender, HMouseEventArgsWPF e)
        {
            if (e.Button == MouseButton.Right)
            {
                ContextMenu cm = this.FindResource("cmButton") as ContextMenu;
                cm.PlacementTarget = sender as Button;
                cm.IsOpen          = true;
            }
            if (e.Button == MouseButton.Middle)
            {
                HTuple  X = new HTuple();
                HTuple  Y = new HTuple();
                HObject image;
                HTuple  row     = new HTuple();
                HTuple  col     = new HTuple();
                HTuple  grayval = new HTuple();

                row = (int)e.X;
                col = (int)e.Y;
                try
                {
                    HOperatorSet.GetGrayval(background_image, col, row, out grayval);
                }
                catch (Exception ex)
                {
                    ;
                }
                MessageBox.Show("当前坐标:  X:" + row.ToString() + "  Y: " + col.ToString() + "  灰度值  " + grayval.ToString());
            }
        }
示例#8
0
        public bool WriteParams(String xmlNode, string regionName)
        {
            try
            {
                string shv_MinGray = "Parameters/" + xmlNode + "/hv_MinGray";
                string shv_MaxGray = "Parameters/" + xmlNode + "/hv_MaxGray";
                string shv_Min     = "Parameters/" + xmlNode + "/hv_Min";
                string shv_Max     = "Parameters/" + xmlNode + "/hv_Max";
                string shv_Number  = "Parameters/" + xmlNode + "/hv_Number";

                xmlRW.Update(shv_MinGray, hv_MinGray.ToString());
                xmlRW.Update(shv_MaxGray, hv_MaxGray.ToString());
                xmlRW.Update(shv_Min, hv_Min.ToString());
                xmlRW.Update(shv_Max, hv_Max.ToString());
                xmlRW.Update(shv_Number, hv_Number.ToString());

                string regionPath = AppDomain.CurrentDomain.BaseDirectory + @".//Parameters//" + regionName;
                HOperatorSet.WriteRegion(ho_Region, regionPath);

                errorFlag = false;
                return(true);
            }
            catch (Exception exc)
            {
                errorFlag = true;
                return(false);
            }
        }
示例#9
0
        private void ModelSearch(HTuple hv_ModelID, int i, out HTuple hv_Row, out HTuple hv_Column)
        {
            // Local iconic variables

            HTuple hv_num = new HTuple(), hv_a = new HTuple();
            HTuple hv_Seconds1 = new HTuple();
            HTuple hv_Angle = new HTuple(), hv_Score = new HTuple();
            HTuple hv_Seconds2 = new HTuple(), hv_Time = new HTuple();
            HTuple hv_HeightWin = null, hv_WidthWin = null, hv_n = 1;

            HOperatorSet.GenEmptyObj(out ho_GrayImage);
            HOperatorSet.GenEmptyObj(out ho_Circle);
            HOperatorSet.GenEmptyObj(out ho_Image);

            hv_Row    = null;
            hv_Column = null;

            // stop(); only in hdevelop
            //**********************************************
            //**********************************************
            //设置模板完成开始匹配

            ho_Image.Dispose();
            HOperatorSet.ReadImage(out ho_Image, ("acA2500-14gc0" + i) + ".bmp");
            ho_GrayImage.Dispose();
            HOperatorSet.Rgb1ToGray(ho_Image, out ho_GrayImage);
            HOperatorSet.CountSeconds(out hv_Seconds1);
            HOperatorSet.FindShapeModel(ho_Image, hv_ModelID, (new HTuple(0)).TupleRad()
                                        , (new HTuple(360)).TupleRad(), 0.8, 15, 0.2, "none", 0, 0.9, out hv_Row,
                                        out hv_Column, out hv_Angle, out hv_Score);
            HOperatorSet.CountSeconds(out hv_Seconds2);
            hv_Time = 1000.0 * (hv_Seconds2 - hv_Seconds1);
            HOperatorSet.GetImageSize(ho_Image, out hv_HeightWin, out hv_WidthWin);              // 获取输入图像的尺寸
            HOperatorSet.SetPart(hWindowControl1.HalconWindow, 0, 0, hv_WidthWin, hv_HeightWin); //将获得的图像铺满整个窗口
            HOperatorSet.DispObj(ho_Image, hWindowControl1.HalconWindow);
            HOperatorSet.SetColor(hWindowControl1.HalconWindow, "yellow");
            HOperatorSet.SetLineWidth(hWindowControl1.HalconWindow, 1);
            HOperatorSet.SetLineWidth(hWindowControl1.HalconWindow, 3);
            HOperatorSet.SetColor(hWindowControl1.HalconWindow, "green");
            HOperatorSet.SetDraw(hWindowControl1.HalconWindow, "margin");

            hv_num = new HTuple(hv_Row.TupleLength());
            HTuple end_val35  = hv_num - 1;
            HTuple step_val35 = 1;

            for (hv_a = 0; hv_a.Continue(end_val35, step_val35); hv_a = hv_a.TupleAdd(step_val35))
            {
                ho_Circle.Dispose();
                HOperatorSet.GenCircle(out ho_Circle, hv_Row.TupleSelect(hv_a), hv_Column.TupleSelect(
                                           hv_a), 220);
                HOperatorSet.DispObj(ho_Circle, hWindowControl1.HalconWindow);
            }
            double d = hv_Time[0];

            txtNumber.Text = hv_num.ToString();
            txtTime.Text   = d.ToString("0.##");
            ho_GrayImage.Dispose();
            ho_Image.Dispose();
            ho_Circle.Dispose();
        }
示例#10
0
    // Main procedure
    private void action(HTuple UID)
    {
        // HTuple hv_exception = new HTuple();
        // Initialize local and output iconic variables
        //HOperatorSet.GenEmptyObj(out ho_Image);
#if DEBUG
        Console.WriteLine("ÕýÔÚ³õʼ»¯" + UID.ToString());
#endif
        try
        {
            HOperatorSet.OpenFramegrabber("MVision", 0, 0, 0, 0, 0, 0, "default", -1,

//            HOperatorSet.OpenFramegrabber("GigEVision", 0, 0, 0, 0, 0, 0, "default", -1,
                                          "default", -1, "false", "default", UID, 0, -1, out hv_AcqHandle);
            HOperatorSet.SetFramegrabberParam(hv_AcqHandle, "ExposureTime", 5000);
            HOperatorSet.SetFramegrabberParam(hv_AcqHandle, "Gain", 0);
            HOperatorSet.SetFramegrabberParam(hv_AcqHandle, "TriggerMode", "On");
            HOperatorSet.SetFramegrabberParam(hv_AcqHandle, "TriggerSource", "Software");
            HOperatorSet.GrabImageStart(hv_AcqHandle, -1);
        }
        catch (HalconException HDevExpDefaultException)
        {
            throw HDevExpDefaultException;
        }
    }
        /// <summary>
        /// 相机参数Thread
        /// </summary>
        private void Camerarfs()
        {
            HObject ho_Image = null;
            int     i        = 1;

            try
            {
                while (i != 0)
                {
                    HOperatorSet.GrabImage(out ho_Image, hv_AcqHandle);
                    if (ho_Image != null)
                    {
                        HOperatorSet.Intensity(ho_Image, ho_Image, out hv_Mean, out hv_Deviation); // 求图片平均值和方差
                        tssl_Mean.Text      = "图片平均值:" + hv_Mean.ToString();
                        tssl_Deviation.Text = "图片方差:" + hv_Deviation.ToString();
                        //显示玩之后释放图片
                        ho_Image.Dispose();
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("相机参数获取失败!");
                tssl_Mean.Text      = "相机参数获取失败!";
                tssl_Deviation.Text = "无法自动捕捉图像";
            }
        }
示例#12
0
 private void ClassifierParamsSetForm_Load(object sender, EventArgs e)
 {
     numericUpDownBatchSize.Value         = _BatchSize;
     numericUpDownNumEpochs.Value         = _NumEpochs;
     numericUpDownLearningRateSENE.Value  = _LearningRateStepEveryNthEpoch;
     textBoxLearningRateStepRatio.Text    = _LearningRateStepRatio.ToString();
     textBoxInitialLearningRate.Text      = _InitialLearningRate.ToString();
     numericUpDownTrainingPercent.Value   = _TrainingPercent;
     numericUpDownValidationPercent.Value = _ValidationPercent;
 }
示例#13
0
        List <HObject> ho_Regions;   //模板区域集合

        private void Show2HWindow(HObject ho_HObject)
        {
            //缩放显示图像,并且计算缩放比例和窗口起始位置
            HOperatorSet.ClearWindow(hv_ImageWindow);
            HTuple hv_Width  = new HTuple();
            HTuple hv_Height = new HTuple();

            HOperatorSet.GetImageSize(ho_HObject, out hv_Width, out hv_Height);
            int    imgWidth       = int.Parse(hv_Width.ToString());
            int    imgHeight      = int.Parse(hv_Height.ToString());
            double imgAspectRatio = (double)imgWidth / (double)imgHeight;
            int    winWidth       = this.hWindowControl1.WindowSize.Width;
            int    winHeight      = this.hWindowControl1.WindowSize.Height;
            double winAspectRatio = (double)winWidth / (double)winHeight;

            HOperatorSet.SetSystem("int_zooming", "false");//图像缩放之前最好将此参数设置为false.

            HTuple  hv_Para = new HTuple("constant");
            HObject ho_ZoomImage;

            HOperatorSet.GenEmptyObj(out ho_ZoomImage);

            if (winWidth < imgWidth && imgAspectRatio > winAspectRatio)
            {
                //超宽图像
                HOperatorSet.ZoomImageSize(ho_HObject, out ho_ZoomImage, winWidth, winWidth / imgAspectRatio, hv_Para);
                hv_StartX     = 0 - (winHeight - winWidth / imgAspectRatio) / 2;
                hv_StartY     = 0;
                hv_ZoomFactor = (double)winWidth / (double)imgWidth;
            }
            else if (winHeight < imgHeight && imgAspectRatio < winAspectRatio)
            {
                //超高图像
                HOperatorSet.ZoomImageSize(ho_HObject, out ho_ZoomImage, winHeight * imgAspectRatio, winHeight, hv_Para);
                hv_StartX     = 0;
                hv_StartY     = 0 - (winWidth - winHeight * imgAspectRatio) / 2;
                hv_ZoomFactor = (double)winHeight / (double)imgHeight;
            }

            try
            {
                HOperatorSet.SetPart(hv_ImageWindow, hv_StartX, hv_StartY, winHeight - 1 + hv_StartX, winWidth - 1 + hv_StartY);//设置居中显示
                HOperatorSet.DispObj(ho_ZoomImage, hv_ImageWindow);

                HOperatorSet.HomMat2dIdentity(out hv_XldHomMat2D);
                HOperatorSet.HomMat2dScale(hv_XldHomMat2D, hv_ZoomFactor, hv_ZoomFactor, 0, 0, out hv_XldHomMat2D);
            }
            catch (Exception exc)
            {
                MessageBox.Show("图像显示错误!" + exc.ToString());
            }
        }
示例#14
0
        public bool WriteParams(String xmlNode, string regionName)
        {
            try
            {
                string shv_MeasureLength1   = "Parameters/" + xmlNode + "/hv_MeasureLength1";
                string shv_MeasureLength2   = "Parameters/" + xmlNode + "/hv_MeasureLength2";
                string shv_MeasureSigma     = "Parameters/" + xmlNode + "/hv_MeasureSigma";
                string shv_MeasureThreshold = "Parameters/" + xmlNode + "/hv_MeasureThreshold";
                string shv_GenParamName     = "Parameters/" + xmlNode + "/hv_GenParamName";
                string shv_GenParamValue    = "Parameters/" + xmlNode + "/hv_GenParamValue";
                string shv_Number           = "Parameters/" + xmlNode + "/hv_Number";

                string shv_Row1_Horizon    = "Parameters/" + xmlNode + "/hv_Row1_Horizon";
                string shv_Column1_Horizon = "Parameters/" + xmlNode + "/hv_Column1_Horizon";
                string shv_Row2_Horizon    = "Parameters/" + xmlNode + "/hv_Row2_Horizon";
                string shv_Column2_Horizon = "Parameters/" + xmlNode + "/hv_Column2_Horizon";

                string shv_Row1_Vertical    = "Parameters/" + xmlNode + "/hv_Row1_Vertical";
                string shv_Column1_Vertical = "Parameters/" + xmlNode + "/hv_Column1_Vertical";
                string shv_Row2_Vertical    = "Parameters/" + xmlNode + "/hv_Row2_Vertical";
                string shv_Column2_Vertical = "Parameters/" + xmlNode + "/hv_Column2_Vertical";


                xmlRW.Update(shv_MeasureLength1, hv_MeasureLength1.ToString());
                xmlRW.Update(shv_MeasureLength2, hv_MeasureLength2.ToString());
                xmlRW.Update(shv_MeasureSigma, hv_MeasureSigma.ToString());
                xmlRW.Update(shv_MeasureThreshold, hv_MeasureThreshold.ToString());
                xmlRW.Update(shv_GenParamName, hv_GenParamName);
                xmlRW.Update(shv_GenParamValue, hv_GenParamValue);
                xmlRW.Update(shv_Number, hv_Number.ToString());

                xmlRW.Update(shv_Row1_Horizon, hv_Row1_Horizon.ToString());
                xmlRW.Update(shv_Column1_Horizon, hv_Column1_Horizon.ToString());
                xmlRW.Update(shv_Row2_Horizon, hv_Row2_Horizon.ToString());
                xmlRW.Update(shv_Column2_Horizon, hv_Column2_Horizon.ToString());

                xmlRW.Update(shv_Row1_Vertical, hv_Row1_Vertical.ToString());
                xmlRW.Update(shv_Column1_Vertical, hv_Column1_Vertical.ToString());
                xmlRW.Update(shv_Row2_Vertical, hv_Row2_Vertical.ToString());
                xmlRW.Update(shv_Column2_Vertical, hv_Column2_Vertical.ToString());

                errorFlag = false;
                return(true);
            }
            catch (Exception exc)
            {
                errorFlag = true;
                return(false);
            }
        }
示例#15
0
        public bool FindTab()
        {
            if (tabParams.ho_Image == null)
            {
                MessageBox.Show("图像为空!");
                return(false);
            }
            Show2HWindow(tabParams.ho_Image);
            if (tabParams.ho_Region == null)
            {
                MessageBox.Show("区域为空!");
                return(false);
            }
            try
            {
                HObject ho_ImageReduced = null;
                HOperatorSet.ReduceDomain(tabParams.ho_Image, tabParams.ho_Region, out ho_ImageReduced);

                HObject ho_Regions = null;
                HOperatorSet.Threshold(ho_ImageReduced, out ho_Regions, tabParams.hv_MinGray, tabParams.hv_MaxGray);

                HObject ho_ConnectedRegions = null;
                HOperatorSet.Connection(ho_Regions, out ho_ConnectedRegions);

                HObject ho_SelectedRegions = null;
                HOperatorSet.SelectShape(ho_ConnectedRegions, out ho_SelectedRegions, "area", "and", tabParams.hv_Min, tabParams.hv_Max);

                HTuple hv_Number = new HTuple();
                HOperatorSet.CountObj(ho_SelectedRegions, out hv_Number);
                if (hv_Number < tabParams.hv_Number)
                {
                    MessageBox.Show("匹配数量过少");
                    return(false);
                }
                HOperatorSet.AffineTransRegion(ho_SelectedRegions, out ho_SelectedRegions, hv_XldHomMat2D, hv_Interpolate);

                HOperatorSet.SetColor(hv_ImageWindow, "red");
                HOperatorSet.DispObj(ho_SelectedRegions, hv_ImageWindow);
                MessageBox.Show("检测成功,检测匹配个数:" + hv_Number.ToString() + "!");
                return(true);
            }
            catch (Exception exc)
            {
                MessageBox.Show("检测失败!" + exc.ToString());
                return(false);
            }
        }
示例#16
0
        private void get_calibarate_data(HTuple cameraWindow, TextBox x, TextBox y)
        {
            try
            {
                HTuple hv_Row1    = null;
                HTuple hv_Column1 = null;
                HTuple hv_Row2    = null;
                HTuple hv_Column2 = null;
                HOperatorSet.SetColor(cameraWindow, "red");
                HOperatorSet.DrawRectangle1(cameraWindow, out hv_Row1, out hv_Column1, out hv_Row2, out hv_Column2);

                HTuple roi_hv_Row1    = null;
                HTuple roi_hv_Column1 = null;
                HTuple roi_hv_Row2    = null;
                HTuple roi_hv_Column2 = null;

                roi_hv_Row1    = hv_Row1 / hv_ZoomFactor;
                roi_hv_Column1 = hv_Column1 / hv_ZoomFactor;
                roi_hv_Row2    = hv_Row2 / hv_ZoomFactor;
                roi_hv_Column2 = hv_Column2 / hv_ZoomFactor;

                HObject ho_ROI = new HObject();
                HOperatorSet.GenRectangle1(out ho_ROI, roi_hv_Row1, roi_hv_Column1, roi_hv_Row2, roi_hv_Column2);

                HTuple hv_Row_camera    = null;
                HTuple hv_Column_camera = null;

                if (!findCircle(ho_Image, ho_ROI, ref hv_Row_camera, ref hv_Column_camera))
                {
                    MessageBox.Show("查找圆心失败!");
                    return;
                }
                HObject ho_MeasuredPoint;
                HOperatorSet.GenCrossContourXld(out ho_MeasuredPoint, hv_Row_camera, hv_Column_camera, 40, (new HTuple(45)).TupleRad());

                x.Text = hv_Row_camera.ToString();
                y.Text = hv_Column_camera.ToString();

                HOperatorSet.AffineTransContourXld(ho_MeasuredPoint, out ho_MeasuredPoint, hv_XldHomMat2D);

                HOperatorSet.DispObj(ho_MeasuredPoint, cameraWindow);
            }
            catch (Exception)
            {
                MessageBox.Show("框取区域失败!");
            }
        }
示例#17
0
        async void getDataLive()
        {
            while (true)
            {
                try
                {
                    string a;
                    HTuple b = 1000;

                    // get data from PLC
                    if (btnConnection.Text == "Connected")
                    {
                        dataWord = clsPlc.RecDataFromPLC(dataType, device_getWord, 10, _plcSocket);
                        databit  = clsPlc.GetBitFromPLC(device_getBit, 1, _plcSocket);
                        //getdataBarcode = clsPlc.RecDataFromPLC("String", 3000, 10, _plcSocket);
                        this.Invoke((MethodInvoker) delegate
                        {
                            txtRecdataBit.Text  = databit.ToString();
                            txtRecdataWord.Text = dataWord.ToString();
                        });
                        b = Lib.ToDouble(nbrDataSend.Value);
                    }

                    HTuple bb = Lib.ToDouble(nbrDataSend.Value);
                    // rec data to PLC
                    if (btnConnection.Text == "Connected")
                    {
                        clsPlc.SendDataFromPLC("Word", bb, 4000, _plcSocket);
                    }
                    if (databit == 1)
                    {
                        Img.Dispose();
                        Img = Framgraber.GrabImage();
                        Img.DispObj(window);
                    }
                    if (static_senddata == true)
                    {
                        clsPlc.SetBitFromPLC(3000, 1, 1, _plcSocket);
                        clsPlc.SetBitFromPLC(3000, 0, 1, _plcSocket);
                    }
                }
                catch (Exception ex)
                {
                }
            }
        }
示例#18
0
        private void findCode(HObject hObj, HTuple codeType, out string result)
        {
            // Local iconic variables
            HObject ho_Image, ho_SymbolXLDs;
            //HObject ho_ImageZoomed = null;
            // Local control variables
            HTuple hv_DataCodeHandle = null, hv_ResultHandles = null;
            HTuple hv_DecodedDataStrings = null;
            HTuple hv_Width = null, hv_Height = null;

            // Initialize local and output iconic variables
            HOperatorSet.GenEmptyObj(out ho_Image);
            //HOperatorSet.GenEmptyObj(out ho_ImageZoomed);
            HOperatorSet.GenEmptyObj(out ho_SymbolXLDs);

            HOperatorSet.CreateDataCode2dModel(codeType, "default_parameters", "maximum_recognition", out hv_DataCodeHandle);
            ho_Image.Dispose();

            ho_Image = hObj.Clone();
            //HOperatorSet.GetImageSize(ho_Image, out hv_Width, out hv_Height);
            ////int width = hv_Width;
            //int height = hv_Height;
            //if (hv_Width>2000 || height>2000)
            //{
            //    ho_ImageZoomed.Dispose();
            //    HOperatorSet.ZoomImageFactor(ho_Image, out ho_ImageZoomed, 0.5, 0.5, "bilinear");
            //}
            //else
            //{
            //    ho_ImageZoomed.Dispose();
            //    HOperatorSet.ZoomImageFactor(ho_Image, out ho_ImageZoomed, 1, 1, "bilinear");
            //}
            //Read the symbol in the image
            ho_SymbolXLDs.Dispose();
            HOperatorSet.FindDataCode2d(ho_Image, out ho_SymbolXLDs, hv_DataCodeHandle, new HTuple(),
                                        new HTuple(), out hv_ResultHandles, out hv_DecodedDataStrings);
            //Clear the model
            HOperatorSet.ClearDataCode2dModel(hv_DataCodeHandle);
            ho_Image.Dispose();
            //ho_ImageZoomed.Dispose();
            ho_SymbolXLDs.Dispose();

            result = hv_DecodedDataStrings.ToString();
        }
示例#19
0
文件: FrmAutoFocus.cs 项目: Gz1d/Gz
        public void GetFocusValueProcess()
        {
            HTuple  Value = new HTuple();
            HObject Rect = new HObject();
            HObject ReduceImg = new HObject();
            HObject CropImg = new HObject();
            HObject RectContour = new HObject();
            HTuple  Width, Hei;

            while (IsContinue)
            {
                try
                {
                    #region
                    if (Img != null && Img.IsInitialized())
                    {
                        Img.Dispose();
                    }
                    //if (RectContour != null && RectContour.IsInitialized()) RectContour.Dispose();
                    Camera.Instance.GrabImg(CcdName, out Img);
                    HOperatorSet.GenRectangle1(out Rect, row1, col1, row2, col2);
                    HOperatorSet.GenContourRegionXld(Rect, out RectContour, "border");
                    HOperatorSet.ReduceDomain(Img, Rect, out ReduceImg);
                    Rect.Dispose();
                    HOperatorSet.CropDomain(ReduceImg, out CropImg);
                    ReduceImg.Dispose();
                    MyVisionBase.evaluate_definition(CropImg, out Value);
                    CropImg.Dispose();
                    view.ResetView();
                    view.AddViewImage(Img);
                    view.AddViewObject(RectContour);
                    HOperatorSet.GetImageSize(Img, out Width, out Hei);

                    view.Repaint();
                    view.SetString(Width.D / 2, Hei.D / 2, "red", Value.ToString());
                    System.Threading.Thread.Sleep(100);
                    //Img.Dispose();
                    //RectContour.Dispose();
                    #endregion
                }
                catch  {     }
            }
        }
示例#20
0
    // Main procedure
    private void action()
    {
        // Local iconic variables

        HObject ho_Image1, ho_Image, ho_Rectangle;

        // Local control variables

        HTuple hv_Row1 = null, hv_Column1 = null, hv_Row2 = null;
        HTuple hv_Column2 = null, hv_Mean = null, hv_Deviation = null;

        // Initialize local and output iconic variables
        HOperatorSet.GenEmptyObj(out ho_Image1);
        HOperatorSet.GenEmptyObj(out ho_Image);
        HOperatorSet.GenEmptyObj(out ho_Rectangle);
        //¶ÁȡͼƬ£¬×ª»»³É»Ò¶ÈͼƬ

        ho_Image1.Dispose();
        HOperatorSet.ReadImage(out ho_Image1, "C:/Users/Public/Documents/MVTec/HALCON-17.12-Progress/examples/images/cable1.png");
        ho_Image.Dispose();
        HOperatorSet.Rgb1ToGray(ho_Image1, out ho_Image);
        HOperatorSet.DispObj(ho_Image, hv_ExpDefaultWinHandle);
        //Ñ¡Ôñ²âÁ¿µÄÇøÓò

        HOperatorSet.DrawRectangle1(hv_ExpDefaultWinHandle, out hv_Row1, out hv_Column1,
                                    out hv_Row2, out hv_Column2);
        ho_Rectangle.Dispose();
        HOperatorSet.GenRectangle1(out ho_Rectangle, hv_Row1, hv_Column1, hv_Row2, hv_Column2);

        //¼ì²â»Ò¶È
        HOperatorSet.Intensity(ho_Rectangle, ho_Image, out hv_Mean, out hv_Deviation);
        HOperatorSet.DispObj(ho_Image, hv_ExpDefaultWinHandle);
        MessageBox.Show(hv_Mean.ToString());

        ho_Image1.Dispose();
        ho_Image.Dispose();
        ho_Rectangle.Dispose();
    }
示例#21
0
 private void hv_Window_HMouseMove(object sender, HMouseEventArgs e)
 {
     if (MyCurCom.ho_Image == null)
     {
         BeginInvoke(new MethodInvoker(delegate
         {
             PixelLabel.Text = "[-1,-1]->[-1]";
         }));
     }
     else
     {
         double current_beginX, current_beginY, current_width, current_heigth;
         string mes      = ((int)e.X).ToString() + "," + ((int)e.Y).ToString();
         string ShowMes  = "[" + mes + "]->";
         HTuple row      = new HTuple();
         HTuple col      = new HTuple();
         HTuple grayval  = new HTuple();
         string PixelMes = "";
         lock (locker1)
         {
             try
             {
                 HOperatorSet.GetGrayval(MyCurCom.ho_Image, (int)e.Y, (int)e.X, out grayval);
                 PixelMes = grayval.ToString();
             }
             catch
             {
                 PixelMes = "[-1]";
             }
         }
         ShowMes = ShowMes + PixelMes;
         BeginInvoke(new MethodInvoker(delegate
         {
             PixelLabel.Text = ShowMes;
         }));
     }
 }
示例#22
0
        public bool WriteParams(String xmlNode)
        {
            try
            {
                string shv_MeasureLength1   = "Parameters/" + xmlNode + "/hv_MeasureLength1";
                string shv_MeasureLength2   = "Parameters/" + xmlNode + "/hv_MeasureLength2";
                string shv_MeasureSigma     = "Parameters/" + xmlNode + "/hv_MeasureSigma";
                string shv_MeasureThreshold = "Parameters/" + xmlNode + "/hv_MeasureThreshold";
                string shv_GenParamName     = "Parameters/" + xmlNode + "/hv_GenParamName";
                string shv_GenParamValue    = "Parameters/" + xmlNode + "/hv_GenParamValue";

                string shv_Row1    = "Parameters/" + xmlNode + "/hv_Row1";
                string shv_Column1 = "Parameters/" + xmlNode + "/hv_Column1";
                string shv_Row2    = "Parameters/" + xmlNode + "/hv_Row2";
                string shv_Column2 = "Parameters/" + xmlNode + "/hv_Column2";

                xmlRW.Update(shv_MeasureLength1, hv_MeasureLength1.ToString());
                xmlRW.Update(shv_MeasureLength2, hv_MeasureLength2.ToString());
                xmlRW.Update(shv_MeasureSigma, hv_MeasureSigma.ToString());
                xmlRW.Update(shv_MeasureThreshold, hv_MeasureThreshold.ToString());
                xmlRW.Update(shv_GenParamName, hv_GenParamName);
                xmlRW.Update(shv_GenParamValue, hv_GenParamValue);

                xmlRW.Update(shv_Row1, hv_Row1.ToString());
                xmlRW.Update(shv_Column1, hv_Column1.ToString());
                xmlRW.Update(shv_Row2, hv_Row2.ToString());
                xmlRW.Update(shv_Column2, hv_Column2.ToString());

                errorFlag = false;
                return(true);
            }
            catch (Exception exc)
            {
                errorFlag = true;
                return(false);
            }
        }
示例#23
0
        private void load_parm()
        {
            if (FC_data.in_row != null)
            {
                Hrow    = FC_data.in_row;
                Hcol    = FC_data.in_col;
                Hradius = FC_data.in_radius;
            }
            Hnum        = FC_data.Hnum;
            Hwid        = FC_data.Hwid;
            Hamp        = FC_data.Hamp;
            Hsomth      = FC_data.Hsomth;
            HLengh      = FC_data.HLengh;
            Htransition = FC_data.Htransition;
            Hselect     = FC_data.Hselect;
            Hdirection  = FC_data.Hdirection;
            data_row    = FC_data.data_row;
            data_col    = FC_data.data_col;


            NUM_UpDown.Value = (decimal)Hnum[0].I;
            trackBar1.Value  = (int)NUM_UpDown.Value;
            Wid_UpDown.Value = (decimal)Hwid[0].I;
            trackBar2.Value  = (int)Wid_UpDown.Value;
            Amp_UpDown.Value = (decimal)Hamp[0].I;
            trackBar3.Value  = (int)Amp_UpDown.Value;
            Som_UpDown.Value = (decimal)Hsomth[0].D;
            trackBar4.Value  = (int)(Som_UpDown.Value * 10);
            L1_UpDown.Value  = (decimal)HLengh[0].I;
            trackBar5.Value  = (int)L1_UpDown.Value;

            comboBox1.Text = Htransition;
            comboBox2.Text = Hselect;
            comboBox3.Text = Hdirection;
            textBox1.Text  = data_row.ToString();
            textBox2.Text  = data_col.ToString();
        }
示例#24
0
 private void UpdateHalconControl(double ControlScale)
 {
     hWindowControl1.Size = new Size((int)(int.Parse(hv_Width.ToString()) * (ControlScale)), (int)(int.Parse(hv_Height.ToString()) * (ControlScale)));
 }
示例#25
0
        private void Calib_button_Click(object sender, EventArgs e)
        {
            HTuple hv_x = new HTuple(), hv_y = new HTuple(), hv_x_mm = new HTuple();
            HTuple hv_y_mm = new HTuple(), hv_HomMat2D = new HTuple();

            //count valid pairs  validPairs

            int validPairs1 = 0, validPairs2 = 0, validPairs = 0;
            int min = 9;

            foreach (TextBox tb in this.Cali_tabPage.Controls.OfType <TextBox>())
            {
                if (tb is TextBox && tb.Text == string.Empty && tb.TabIndex < min)
                {
                    min = tb.TabIndex;
                }
            }
            foreach (TextBox tb in this.Cali_tabPage.Controls.OfType <TextBox>())
            {
                if (tb is TextBox && tb.TabIndex == min)
                {
                    if (tb.Text == string.Empty)
                    {
                        validPairs1 = min - 1;
                        break;
                    }
                    else
                    {
                        validPairs1 = min;
                        break;
                    }
                }
            }

            int min2 = 19;

            foreach (TextBox tb in this.Cali_tabPage.Controls.OfType <TextBox>())
            {
                if (tb is TextBox && tb.Text == string.Empty && tb.TabIndex < min2 && tb.TabIndex > 10)
                {
                    min2 = tb.TabIndex;
                }
            }
            foreach (TextBox tb in this.Cali_tabPage.Controls.OfType <TextBox>())
            {
                if (tb is TextBox && tb.TabIndex == min2)
                {
                    if (tb.Text == string.Empty)
                    {
                        validPairs2 = min2 - 1;
                        break;
                    }
                    else
                    {
                        validPairs2 = min2;
                        break;
                    }
                }
            }
            if (validPairs1 - (validPairs2 - 10) > 0)
            {
                validPairs = validPairs2 - 10;
            }
            else
            {
                validPairs = validPairs1;
            }


            foreach (TextBox tb in this.Cali_tabPage.Controls.OfType <TextBox>())
            {
                for (int i = 0; i < validPairs; i++)
                {
                    if (tb.TabIndex == i + 1)
                    {
                        hv_x[i] = string2point(tb.Text)[0];
                        hv_y[i] = string2point(tb.Text)[1];

                        tb.BackColor = Color.Green;
                    }


                    if (tb.TabIndex == i + 1 + 10)
                    {
                        hv_x_mm[i]   = string2point(tb.Text)[0];
                        hv_y_mm[i]   = string2point(tb.Text)[1];
                        tb.BackColor = Color.Green;
                    }
                }
            }


            HOperatorSet.VectorToSimilarity(hv_x, hv_y, hv_x_mm, hv_y_mm, out hv_HomMat2D);

            MessageBox.Show(hv_HomMat2D.ToString());
        }
示例#26
0
        async void runcode()
        {
            if (Framgraber == null)
            {
                MessageBox.Show("  CAMERA DISCONNECTION !!");
                return;
            }
            if (socketPLC == null)
            {
                MessageBox.Show("  PLC DISCONNECTION  !!");
                return;
            }
            double Z      = 100;
            int    _break = 0;

            while (true)
            {
                try
                {
                    int countPointHE = 0;

                    DataBit            = clsPlc.GetBitFromPLC(3000, 1, socketPLC); // Snap
                    DataBitTrigerHE    = clsPlc.GetBitFromPLC(4000, 1, socketPLC); // HEB
                    DataBitTrigerCaLib = clsPlc.GetBitFromPLC(5000, 1, socketPLC);

                    Task task1;
                    task1 = Task.Factory.StartNew(() =>
                    {
                        try
                        {
                            //HOperatorSet.GrabImage(out HObject image1, _frameGrabber);
                        }
                        catch (Exception ex)
                        {
                        }
                    });
                    //CALIB
                    // if (DataBitTrigerCaLib == 1)
                    if (DataBitTrigerCaLib == 1)
                    {
                        this.Invoke((MethodInvoker) delegate
                        {
                            btnCalibBit.BackColor = Color.Green;
                        });

                        // Khoi tao Model Calibration cua Halcon
                        HTuple CalibDataID     = clsCalib.InitCalib("area_scan_division", "calibration_object", 0.008, 0, 1.85 / 1000000, 1.85 / 1000000, 4024 / 2, 3036 / 2, 4024, 3036, Application.StartupPath + "/calib/" + "caltab_30mm.descr");
                        int    countpointCalib = 0;
                        while (true)
                        {
                            DataBit = clsPlc.GetBitFromPLC(3000, 1, socketPLC);

                            if (DataBit == 1)
                            {
                                snap();
                                HOperatorSet.WriteImage(Img, "bmp", 0, Application.StartupPath + "/hand_eye/" + "image_calib_" + countpointCalib);
                                clsPlc.SendDataFromPLC("Word", 2, 4005, socketPLC);
                                Thread.Sleep(100);
                                clsPlc.SendDataFromPLC("Word", 2, 4002, socketPLC); // Send Data OK
                                countpointCalib += 1;
                            }
                            if (countpointCalib == 11)
                            {
                                HTuple Error = clsCalib.Finally();
                                this.Invoke((MethodInvoker) delegate
                                {
                                    string Errorshow   = Error.ToString();
                                    txtErrorCalib.Text = Errorshow;
                                }
                                            );
                                clsPlc.SetBitFromPLC(4003, 2, 1, socketPLC);
                                // Send Finish
                                MessageBox.Show("  Calib Complete <3");
                                break;
                            }
                            Thread.Sleep(100);
                        }
                    }
                    else
                    {
                        this.Invoke((MethodInvoker) delegate
                        {
                            btnCalibBit.BackColor = Color.Red;
                        });
                    }
                    //HE
                    if (DataBitTrigerHE == 1) /////////-----HEB------
                    {
                        HTuple lst_row_vs = new HTuple();
                        HTuple lst_col_vs = new HTuple();
                        HTuple lst_agl_vs = new HTuple();

                        HTuple lst_x_rb = new HTuple();
                        HTuple lst_y_rb = new HTuple();
                        HTuple lst_a_rb = new HTuple();

                        int countpointHE = 0;

                        while (true)
                        {
                            _break = 0;
                            try
                            {
                                /// Recieve signal riger Camera
                                DataBit = clsPlc.GetBitFromPLC(3000, 1, socketPLC);

                                if (DataBit == 1)
                                {
                                    this.Invoke((MethodInvoker) delegate
                                    {
                                        btnHandeyeBit.BackColor = Color.Green;
                                    });
                                    window.ClearWindow();
                                    // Call result Shape Model
                                    result rsl = new result();
                                    snap();
                                    HObject newimg = new HObject(Img);
                                    rsl = clsCalib.findshapemodle(newimg, ModelID, window);

                                    ////**** Use Origin
                                    HTuple row_input = rsl.RowProj;
                                    HTuple col_input = rsl.ColProj;
                                    HTuple agl_input = rsl.Angle_;
                                    if (_useOrigin == 1)
                                    {
                                        HTuple x0 = 0.0, y0 = 0.0, agl0 = 0.0;
                                        HTuple hommat2D_findregion = new HTuple();
                                        HOperatorSet.VectorAngleToRigid(x0, y0, agl0, rsl.lst_cordinate_shapemodel[0], rsl.lst_cordinate_shapemodel[1], rsl.lst_cordinate_shapemodel[2], out hommat2D_findregion);
                                        clsCalib.create_origin(newimg, rg_binary, rg_first, rg_second, hommat2D_findregion);
                                        row_input = rsl.RowProj;
                                        col_input = rsl.ColProj;
                                        agl_input = rsl.Angle_;
                                    }
                                    else
                                    {
                                        row_input = rsl.lst_cordinate_shapemodel[0];
                                        col_input = rsl.lst_cordinate_shapemodel[1];
                                        agl_input = rsl.lst_cordinate_shapemodel[2];
                                    }
                                    //Add list vision coordinate
                                    HOperatorSet.TupleConcat(lst_row_vs, row_input, out lst_row_vs);
                                    HOperatorSet.TupleConcat(lst_col_vs, col_input, out lst_col_vs);
                                    HOperatorSet.TupleConcat(lst_agl_vs, agl_input, out lst_agl_vs);

                                    // set window
                                    window.SetColor("green");
                                    window.SetDraw("margin");
                                    window.SetLineWidth(3);
                                    rsl.shapemodel_affined.DispObj(window);
                                    window.SetColor("yellow");

                                    //window.DispObj(cross);
                                    //HOperatorSet.WriteImage(Img, "bmp", 0, Application.StartupPath + "/hand_eye/" + "image_calib_" + countpointHE);
                                    clsPlc.SendDataFromPLC("Word", 2, 4005, socketPLC);

                                    // Get coordinate of Robot
                                    HTuple _x       = clsPlc.RecDataFromPLC("DWord", 3100, 2, socketPLC);
                                    HTuple _y       = clsPlc.RecDataFromPLC("DWord", 3102, 2, socketPLC);
                                    HTuple _angle   = clsPlc.RecDataFromPLC("DWord", 3104, 2, socketPLC);
                                    HTuple division = 1000.0;
                                    HTuple _xx      = _x / division;
                                    HTuple _xy      = _y / division / 10;
                                    HTuple _thee    = _angle / 10000.0;

                                    // Add list coordinate robot
                                    HOperatorSet.TupleConcat(lst_x_rb, _xx, out lst_x_rb);
                                    HOperatorSet.TupleConcat(lst_y_rb, _xy, out lst_y_rb);
                                    HOperatorSet.TupleConcat(lst_a_rb, _thee, out lst_a_rb);

                                    countpointHE += 1;
                                    HOperatorSet.WriteImage(Img, "bmp", 0, Application.StartupPath + "/hand_eye/" + "image_calib_" + countpointHE);
                                    this.Invoke((MethodInvoker) delegate
                                    {
                                        //timer1.Enabled = true;
                                        //MessageBox.Show($"Next count {countpointHE}...");
                                        //timer1.Enabled = false;
                                        lbCountNumber.Text     = countpointHE.ToString();
                                        txtXRobot.Text         = _x.ToString();
                                        txtYRobot.Text         = _y.ToString();
                                        txtThetaRobot.Text     = _angle.ToString();
                                        btnTrigerBit.BackColor = Color.Green;
                                    });
                                    Thread.Sleep(100);

                                    clsPlc.SendDataFromPLC("Word", 2, 4002, socketPLC);
                                }
                                if (DataBit == 0)
                                {
                                    this.Invoke((MethodInvoker) delegate
                                    {
                                        btnTrigerBit.BackColor = Color.Red;
                                    });
                                }
                                if (countpointHE == 11)
                                {
                                    string pathsave = Application.StartupPath + "/Handeye_Hommat";
                                    result rsl      = new result();
                                    rsl = clsCalib.handeye11point(lst_row_vs, lst_col_vs, lst_agl_vs, lst_x_rb, lst_y_rb);
                                    // Write list data point
                                    HOperatorSet.WriteTuple(lst_row_vs, pathsave + "/lst_row_vs.tup");
                                    HOperatorSet.WriteTuple(lst_col_vs, pathsave + "/lst_col_vs.tup");
                                    HOperatorSet.WriteTuple(lst_agl_vs, pathsave + "/lst_agl_vs.tup");
                                    HOperatorSet.WriteTuple(lst_x_rb, pathsave + "/lst_x_rb.tup");
                                    HOperatorSet.WriteTuple(lst_y_rb, pathsave + "/lst_y_rb.tup");
                                    // Save Data Handeye
                                    HOperatorSet.WriteTuple(rsl.HomMat_ImgtoWorld, pathsave + "/HomMat_ImgtoWorld.tup");
                                    HOperatorSet.WriteTuple(rsl.HomMat_WorldtoImg, pathsave + "/HomMat_WorldtoImg.tup");
                                    HOperatorSet.WriteTuple(rsl.TCP_to_Tool, pathsave + "/TCP_to_Tool.tup");
                                    HOperatorSet.WriteTuple(rsl.Tool_to_TCP, pathsave + "/Tool_to_TCP.tup");

                                    clsPlc.SendDataFromPLC("Word", 4, 4003, socketPLC);           // Send complete handeye to PLC.
                                    Thread.Sleep(100);
                                    MessageBox.Show($"Complete!!");
                                    countpointHE = 0;
                                    this.Invoke((MethodInvoker) delegate
                                    {
                                        btnTrigerBit.BackColor = Color.Red;
                                    });
                                    break;
                                }
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.ToString());
                                _break = 1;
                                break;
                            }
                            Thread.Sleep(100);
                        }
                    }
                    else
                    {
                        this.Invoke((MethodInvoker) delegate
                        {
                            btnHandeyeBit.BackColor = Color.Red;
                        });
                    }

                    await Task.WhenAll(task1);
                }
                catch (Exception ex)
                {
                }
                if (_break == 1)
                {
                    break;
                }
            }
        }
示例#27
0
        public void ProcessStep(HImage imageGrabbed)
        {
            currentFMCData = new FocusMagnificationCheckData();
            lock (this.ImageToBeSaved)
            {
                this.ImageToBeSaved = imageGrabbed.CopyImage();
            }

            bool calibrationTargetContrastOK = true;

            // Feed the image to the script
            imageGrabbed         = imageGrabbed.CropDomain();
            currentFMCData.Image = imageGrabbed;

            int imageChannels = imageGrabbed.CountChannels();

            HImage rImg = null, gImg = null, bImg = null, rgbImg = null, irImg = null;

            if (imageChannels == Properties.Settings.Default.NumberOfChannelsInIRAndRGBImage)
            {
                rImg   = imageGrabbed.Decompose4(out gImg, out bImg, out irImg);
                rgbImg = rImg.Compose3(gImg, bImg);
            }

            HImage grayImage = new HImage();

            if (rgbImg == null)
            {
                return;
            }

            imageGrabbed = rgbImg.CopyImage();

            #region IntensityCheckForCheckingCalibrationTarget
            // Check the minimum and maximum light intensity to determine whether correct calibration target
            // has been placed
            grayImage = imageGrabbed.Rgb1ToGray();

            HImage ho_R;
            HImage ho_G;
            HImage ho_B;

            ho_R = imageGrabbed.Decompose3(out ho_G, out ho_B);

            HTuple RAOIGrayVals  = Globals.GetGrayValuesOfLine(ho_R);
            HTuple GAOIGrayVals  = Globals.GetGrayValuesOfLine(ho_G);
            HTuple BAOIGrayVals  = Globals.GetGrayValuesOfLine(ho_B);
            HTuple IRAOIGrayVals = Globals.GetGrayValuesOfLine(irImg);

            currentFMCData.GrayValues.RPlaneVals = RAOIGrayVals.ToDArr();
            currentFMCData.GrayValues.GPlaneVals = GAOIGrayVals.ToDArr();
            currentFMCData.GrayValues.BPlaneVals = BAOIGrayVals.ToDArr();
            currentFMCData.GrayValues.MPlaneVals = IRAOIGrayVals.ToDArr();

            int RPlaneMinValue;
            int RPlaneMaxValue;

            RAOIGrayVals = RAOIGrayVals.TupleSelectRange(this.CameraAcquisition.CurrentCameraProperties.NumberOfPixelsToBeClippedAtLeft,
                                                         this.CameraAcquisition.CurrentImageWidth - this.CameraAcquisition.CurrentCameraProperties.NumberOfPixelsToBeClippedAtRight);

            calibrationTargetContrastOK = this.CameraAcquisition.IsLightIntensityLevelOptimum(GAOIGrayVals.ToDArr(), out RPlaneMinValue, out RPlaneMaxValue);
            calibrationTargetContrastOK = (RPlaneMaxValue - RPlaneMinValue) > Properties.Settings.Default.FocusPatternCheckReferenceGrayValue;

            #endregion

            #region FindPatternArea
            //Finds the pattern area
            HImage reducedImage = Globals.FindPatternArea(grayImage);
            if (reducedImage == null)
            {
                SetFocusStatusMessage("Image is too dark or Incorrect Pattern", Color.Red);
                currentFMCData.FocusPercentage         = "";
                currentFMCData.MagnificationPercentage = "";
                currentFMCData.PixelResolution         = "";
                //this.BeginInvoke(new Action<FocusMagnificationCheckData>(UpdateFocusMagnificationStepUI), currentFMCData);
                return;
            }
            #endregion

            #region Focus Learning

            hv_focus = new HTuple();
            HTuple hv_currentSharpness = new HTuple();
            HImage imageCropped        = new HImage();

            //Indicates that execution has entered the focus learning stage
            //(For both successful and failed learning)
            bool focusLearningDone = false;

            if (this.focusLearningStarted)
            {
                #region FocusLearningStage
                focusLearningDone = true;
                if (!this.focusLearningOver)
                {
                    HTuple hv_Scale;
                    HTuple hv_Subsampling = 1;
                    hv_Scale = 1.0 / hv_Subsampling;

                    int grabbedImageWidth, grabbedImageHeight;

                    imageGrabbed.GetImageSize(out grabbedImageWidth, out grabbedImageHeight);

                    // Crop the image before learning
                    imageCropped = imageGrabbed.CropPart((this.CameraAcquisition.CurrentImageHeight / 2) - Properties.Settings.Default.FocusROIRectangleHeight,
                                                         (this.CameraAcquisition.CurrentImageWidth / 2) - Properties.Settings.Default.FocusROIRectangleWidth,
                                                         Properties.Settings.Default.FocusROIRectangleWidth * 2,
                                                         (this.CameraAcquisition.CurrentImageHeight / 2));

                    int croppedImageWidth, croppedImageHeight;

                    imageCropped.GetImageSize(out croppedImageWidth, out croppedImageHeight);

                    int noOfSamples = croppedImageHeight / Properties.Settings.Default.NoOfSamplesUsedInFocusStep;

                    for (int i = 0; i < Properties.Settings.Default.NoOfSamplesUsedInFocusStep; i++)
                    {
                        try
                        {
                            int    row             = i * noOfSamples;
                            HImage newCroppedImage = imageCropped.CopyImage().CropPart(row, 0, croppedImageWidth, noOfSamples);
                            //newCroppedImage.WriteImage("bmp", 0, "D:\\imageCropped" + i.ToString());

                            // Function Call for sharpness Measurement
                            hv_currentSharpness     = MeasureSharpness(newCroppedImage, hv_Scale);
                            hv_AutoCorrelationTuple = hv_AutoCorrelationTuple.TupleConcat(hv_currentSharpness);
                        }
                        catch (Exception ex)
                        {
                        }
                    }

                    currentFMCData.FocusPercentage = "";
                    SetFocusStatusMessage("Learning...", Color.Yellow);
                    UpdateLabelMessage(currentFMCData.FocusPercentage);
                }
                else
                {
                    hv_MaxAutoCorrelation = new HTuple();
                    HTuple hv_Change = new HTuple();
                    if (hv_AutoCorrelationTuple.TupleLength() > 0)
                    {
                        hv_MaxAutoCorrelation = hv_AutoCorrelationTuple.TupleMax();
                        hv_Change             = ((hv_AutoCorrelationTuple.TupleMax() - hv_AutoCorrelationTuple.TupleMin()) / hv_AutoCorrelationTuple.TupleMax()) * 100;

                        if (hv_MaxAutoCorrelation.D <= 0.0 || hv_Change.D < Properties.Settings.Default.MinimumFocusLearningRangeRequired)
                        {
                            currentFMCData.FocusPercentage = "";
                            SetFocusStatusMessage("Focus Learning not done properly. Range of focus learning is not enough.", Color.Orange);
                            this.focusLearningOver = false;
                            UpdateLabelMessage(currentFMCData.FocusPercentage);
                        }
                        else
                        {
                            this.CameraAcquisition.CurrentCameraSetupProperties.FocusMaxAutoCorrelationValue = hv_MaxAutoCorrelation.D;
                        }
                    }
                    else
                    {
                        currentFMCData.FocusPercentage = "";
                        SetFocusStatusMessage("Focus Learning not done properly. Sharpness measurement failed", Color.Orange);
                        this.focusLearningOver = false;
                        UpdateLabelMessage(currentFMCData.FocusPercentage);
                    }
                    this.focusLearningStarted = false;
                }
                #endregion
            }
            else if (this.focusLearningOver)
            {
                #region FocusTestingPhase
                if (!calibrationTargetContrastOK)
                {
                    currentFMCData.FocusPercentage         = "";
                    currentFMCData.MagnificationPercentage = "";
                    currentFMCData.PixelResolution         = "";
                    SetFocusStatusMessage("Incorrect Pattern. Not enough contrast", Color.Red);
                    UpdateLabelMessage(currentFMCData.FocusPercentage);
                    return;
                }

                HTuple hv_Scale;
                HTuple hv_Subsampling = 1;

                hv_Scale = 1.0 / hv_Subsampling;
                // Crop the image before learning
                imageCropped = imageGrabbed.CropPart((this.CameraAcquisition.CurrentImageHeight / 2) - Properties.Settings.Default.FocusROIRectangleHeight,
                                                     (this.CameraAcquisition.CurrentImageWidth / 2) - Properties.Settings.Default.FocusROIRectangleWidth,
                                                     Properties.Settings.Default.FocusROIRectangleWidth * 2,
                                                     (this.CameraAcquisition.CurrentImageHeight / 2));

                // Function Call for sharpness Measurement
                hv_currentSharpness = MeasureSharpness(imageCropped, hv_Scale);
                if (hv_currentSharpness > hv_MaxAutoCorrelation + 2)
                {
                    SetFocusStatusMessage("Current sharpness is more than learnt sharpness. Insert valid calibration doc or Re-do focus learning !!", Color.Orange);
                    currentFMCData.PixelResolution         = "";
                    currentFMCData.MagnificationPercentage = "";
                    currentFMCData.FocusPercentage         = "";
                    UpdateLabelMessage(currentFMCData.FocusPercentage);
                    return;
                }
                else if (hv_currentSharpness > hv_MaxAutoCorrelation)
                {
                    hv_MaxAutoCorrelation   = hv_currentSharpness;
                    hv_AutoCorrelationTuple = hv_AutoCorrelationTuple.TupleConcat(hv_currentSharpness);
                }
                hv_focus = 100 - (((hv_MaxAutoCorrelation - hv_currentSharpness) / hv_MaxAutoCorrelation) * 100);
                hv_focus = hv_focus.TupleRound();
                currentFMCData.FocusPercentage = hv_focus.ToString();
                if (hv_focus > 100)
                {
                    // Not Focused
                    currentFMCData.FocusPercentage = "";
                    SetFocusStatusMessage("Focus learning not done properly", Color.Red);
                    UpdateLabelMessage(currentFMCData.FocusPercentage);
                }
                if (hv_focus >= 95 && hv_focus <= 100)
                {
                    // Focused
                    SetFocusStatusMessage("Focused", Color.LimeGreen);
                }
                else if (hv_focus > 70 && hv_focus < 95)
                {
                    //// Fine Tuning is required
                    SetFocusStatusMessage("Fine Tuning is required", Color.Yellow);
                }
                else
                {
                    // Not Focused
                    SetFocusStatusMessage("Not focused", Color.Red);
                }
                #endregion
            }
            else if (!focusLearningOver && !focusLearningDone)
            {
                if (hv_MaxAutoCorrelation == null)
                {
                    SetFocusStatusMessage("Focus learning not done", Color.Yellow);
                }
            }

            UpdateLabelMessage(currentFMCData.FocusPercentage);
            #endregion
        }
示例#28
0
        private void hWindowControl2_HMouseMove(object sender, HMouseEventArgs e)
        {
            HTuple x = 0, y = 0, z = 0;

            x = e.X;
            y = e.Y;

            if (mainForm.ho_MainImagePositiveB != null && mainForm.ImageHeightPositiveB != null)
            {
                try
                {
                    HOperatorSet.GetGrayval(mainForm.ho_MainImagePositiveB, y, x, out z);
                }
                catch
                {
                    if (x > 4096)
                    {
                        x = 4096;
                    }
                    if (y > mainForm.ImageHeightPositiveB)
                    {
                        y = mainForm.ImageHeightPositiveB;
                    }
                }

                lblPointInfoRowB.Text       = y.TupleInt().ToString();
                lblPointInfoColumnB.Text    = x.TupleInt().ToString();
                lblPointInfoGrayValueB.Text = z.ToString();
            }


            if (!bl_IsMoveB)
            {
                return;
            }
            try
            {
                HTuple row, col;
                GetPosB(out row, out col);

                dbl_PositionB[2] = col;
                dbl_PositionB[3] = row;

                double[] vecB = { dbl_PositionB[2] - dbl_PositionB[0], dbl_PositionB[3] - dbl_PositionB[1] };
                hv_c1B = hv_c1B - vecB[0];
                hv_c2B = hv_c2B - vecB[0];
                hv_r1B = hv_r1B - vecB[1];
                hv_r2B = hv_r2B - vecB[1];
                HOperatorSet.SetPart(hWindowIDTwo, hv_r1B, hv_c1B, hv_r2B, hv_c2B);

                //清除halconWindow窗口 ,避免闪屏
                HSystem.SetSystem("flush_graphic", "false");
                HOperatorSet.ClearWindow(hWindowIDTwo);
                HSystem.SetSystem("flush_graphic", "true");

#if CPlusPlus
                ShowImage(DE.htup_WindowHandle, DE.bl_showdefect);
#else
                HOperatorSet.DispObj(mainForm.ho_MainImagePositiveB, hWindowIDTwo);
#endif
            }
            catch { }
        }
        private void Button_Click_Height_Measure(object sender, RoutedEventArgs e)
        {
            int       Cam_idx = global.GetIns().CamSel;
            Info_Ctrl Infc    = new Info_Ctrl();

            if (false == ImageOperate.FindTrackPos(Obj[Cam_idx], this.CamSetting.HalconID, out Infc, ImageOperate.Track_Model, false))
            {
                return;
            }

            HObject Ho_Image;
            HTuple  hv_c = null, hv_r = null;

            HOperatorSet.GenEmptyObj(out Ho_Image);
            try
            {
                double Angle = CameraADisp.Disp_Adjust_Line(Obj[Cam_idx], INI.axis_roi[Cam_idx].adjust_r1, INI.axis_roi[Cam_idx].adjust_c1, INI.axis_roi[Cam_idx].adjust_phi, INI.axis_roi[Cam_idx].adjust_r2,
                                                            INI.axis_roi[Cam_idx].adjust_c2, this.CamSetting.HalconID, false);
                //HOperatorSet.RotateImage(Obj[Cam_idx], out Ho_Image, Angle, "constant");
                HOperatorSet.DispObj(Obj[Cam_idx], this.CamSetting.HalconID);

                //恢复信息
                double r1 = INI.axis_roi[Cam_idx].axis_d1_r1 + Infc.pos_y;
                double c1 = INI.axis_roi[Cam_idx].axis_d1_c1 + Infc.pos_x;
                CameraADisp.Measure_Diameter(Obj[Cam_idx], r1, c1, new HTuple(-Angle).TupleRad(), INI.axis_roi[Cam_idx].axis_d1_r2, INI.axis_roi[Cam_idx].axis_d1_c2, out hv_c, out hv_r, this.CamSetting.HalconID, false);

                //找到垂直线和找到图像的高度和宽度,来找到在哪儿画横线和纵线
                HTuple hv_Width, hv_Height, hv_HalfHeight, hv_HalfWidth;
                HOperatorSet.GetImageSize(Obj[Cam_idx], out hv_Width, out hv_Height);
                hv_HalfHeight = hv_Height / 2;
                hv_HalfWidth  = hv_c;
                CameraADisp.draw_line(hv_HalfHeight, 0, hv_HalfHeight, hv_Width, this.CamSetting.HalconID, "blue");


                //操作系统,操作系统本身自带选择功能,qt做映射
                //win api


                double x = 0;
                double y = 0;
                CameraADisp.GetPoint(hv_c, hv_r, Angle, out x, out y);
                Console.WriteLine("hv_c:" + hv_c.ToString() + " hv_r:" + hv_r.ToString() + " end x:" + x.ToString() + " end y;" + y.ToString());
                CameraADisp.draw_line(hv_r, hv_c, y, x, this.CamSetting.HalconID, "green");
                CameraADisp.GetPoint(hv_c, hv_r, Angle + 180, out x, out y);
                CameraADisp.draw_line(hv_r, hv_c, y, x, this.CamSetting.HalconID, "green");

                //INI.axis_roi[Cam_idx].d3_min = hv_c;
                INI.axis_roi[Cam_idx].axis_d3_r1           = hv_r;
                INI.axis_roi[Cam_idx].axis_d3_c1           = hv_c;
                INI.axis_roi[Cam_idx].axis_d3_relative_phi = Angle;


                //this.D3_Min.Text = INI.axis_roi[Cam_idx].d3_min.ToString();
                INI.writting();
            }
            catch (HalconException ex)
            {
                Console.WriteLine(ex.ToString());
            }

            Ho_Image.Dispose();
        }
        /// <summary>
        ///显示当前位置和灰度值
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        public override void ShowPosandGray(double x, double y)
        {
            try
            {
                HTuple gray = 0;
                if (y > HeightImage ||
                    x > WidthImage ||
                    x < 0 ||
                    y < 0)
                {
                    return;
                }
                HOperatorSet.GetGrayval(Ho_Image, y, x, out gray);
                if (ParCameraWork.P_I.ParCameraWork_L[NoCamera - 1].TypeImageCoord_e != TypeImageCoord_enum.LeftTop)
                {
                    y = HeightImage - y;
                }

                this.Dispatcher.Invoke(
                    new Dbl2Action((a, b) =>
                {
                    lblPosGray.Content = string.Format("X{0},Y{1}*({2})", a.ToString("f0"), b.ToString("f0"), gray.ToString());
                }),
                    x, y);
            }
            catch (Exception ex)
            {
                Log.L_I.WriteError(NameClass, ex);
            }
        }