Example #1
0
        /// <summary>
        ///   Classify a related group of characters with an OCR classifier.
        ///   Instance represents: Handle of the OCR classifier.
        /// </summary>
        /// <param name="character">Characters to be recognized.</param>
        /// <param name="image">Gray values of the characters.</param>
        /// <param name="expression">Expression describing the allowed word structure.</param>
        /// <param name="numAlternatives">Number of classes per character considered for the internal word correction. Default: 3</param>
        /// <param name="numCorrections">Maximum number of corrected characters. Default: 2</param>
        /// <param name="confidence">Confidence of the class of the characters.</param>
        /// <param name="word">Word text after classification and correction.</param>
        /// <param name="score">Measure of similarity between corrected word and uncorrected classification results.</param>
        /// <returns>Result of classifying the characters with the k-NN.</returns>
        public string DoOcrWordKnn(
            HRegion character,
            HImage image,
            string expression,
            int numAlternatives,
            int numCorrections,
            out double confidence,
            out string word,
            out double score)
        {
            IntPtr proc = HalconAPI.PreCall(647);

            this.Store(proc, 0);
            HalconAPI.Store(proc, 1, (HObjectBase)character);
            HalconAPI.Store(proc, 2, (HObjectBase)image);
            HalconAPI.StoreS(proc, 1, expression);
            HalconAPI.StoreI(proc, 2, numAlternatives);
            HalconAPI.StoreI(proc, 3, numCorrections);
            HalconAPI.InitOCT(proc, 0);
            HalconAPI.InitOCT(proc, 1);
            HalconAPI.InitOCT(proc, 2);
            HalconAPI.InitOCT(proc, 3);
            int    err1 = HalconAPI.CallProcedure(proc);
            string stringValue;
            int    err2       = HalconAPI.LoadS(proc, 0, err1, out stringValue);
            int    err3       = HalconAPI.LoadD(proc, 1, err2, out confidence);
            int    err4       = HalconAPI.LoadS(proc, 2, err3, out word);
            int    procResult = HalconAPI.LoadD(proc, 3, err4, out score);

            HalconAPI.PostCall(proc, procResult);
            GC.KeepAlive((object)this);
            GC.KeepAlive((object)character);
            GC.KeepAlive((object)image);
            return(stringValue);
        }
Example #2
0
        /// <summary>Gets the HALCON region described by the ROI</summary>
        public override HRegion getRegion()           //生成Region
        {
            HRegion region = new HRegion();

            region.GenRectangle1(row1, col1, row2, col2);
            return(region);
        }
Example #3
0
        /// <summary>
        ///   Classify a single character with an OCR classifier.
        ///   Instance represents: Handle of the k-NN classifier.
        /// </summary>
        /// <param name="character">Character to be recognized.</param>
        /// <param name="image">Gray values of the character.</param>
        /// <param name="numClasses">Number of maximal classes to determine. Default: 1</param>
        /// <param name="numNeighbors">Number of neighbors to consider. Default: 1</param>
        /// <param name="confidence">Confidence(s) of the class(es) of the character.</param>
        /// <returns>Results of classifying the character with the k-NN.</returns>
        public string DoOcrSingleClassKnn(
            HRegion character,
            HImage image,
            HTuple numClasses,
            HTuple numNeighbors,
            out double confidence)
        {
            IntPtr proc = HalconAPI.PreCall(659);

            this.Store(proc, 0);
            HalconAPI.Store(proc, 1, (HObjectBase)character);
            HalconAPI.Store(proc, 2, (HObjectBase)image);
            HalconAPI.Store(proc, 1, numClasses);
            HalconAPI.Store(proc, 2, numNeighbors);
            HalconAPI.InitOCT(proc, 0);
            HalconAPI.InitOCT(proc, 1);
            int err1 = HalconAPI.CallProcedure(proc);

            HalconAPI.UnpinTuple(numClasses);
            HalconAPI.UnpinTuple(numNeighbors);
            string stringValue;
            int    err2       = HalconAPI.LoadS(proc, 0, err1, out stringValue);
            int    procResult = HalconAPI.LoadD(proc, 1, err2, out confidence);

            HalconAPI.PostCall(proc, procResult);
            GC.KeepAlive((object)this);
            GC.KeepAlive((object)character);
            GC.KeepAlive((object)image);
            return(stringValue);
        }
Example #4
0
        private void Act_Engine(HImage image)
        {
            LM_DP_ProcedureCall.SetInputIconicParamObject("R", image);
            LM_DP_ProcedureCall.SetInputIconicParamObject("ROI_LuoMuDiePian_T", LM_DP_Region_Affine);
            LM_DP_ProcedureCall.SetInputCtrlParamTuple("minThreshold", new HTuple(minThreshold));
            LM_DP_ProcedureCall.SetInputCtrlParamTuple("filterRadiu", new HTuple(filterRadiu));
            LM_DP_ProcedureCall.SetInputCtrlParamTuple("minAreaThreshold", new HTuple(minAreaThread));
            LM_DP_ProcedureCall.SetInputCtrlParamTuple("luoMuMaxArea", new HTuple(luoMuMaxArea));
            LM_DP_ProcedureCall.SetInputCtrlParamTuple("luoMuWidth", new HTuple(luoMuWidth));
            LM_DP_ProcedureCall.Execute();
            if (lM_DP_OkNg.Length == 0)
            {
                lM_DP_OkNg = (LM_DP_ProcedureCall.GetOutputCtrlParamTuple("luoMuDiePian_OKNG"));
                lM_DP_Num  = (LM_DP_ProcedureCall.GetOutputCtrlParamTuple("lM_DP_Num"));
                lM_DP_Area = (LM_DP_ProcedureCall.GetOutputCtrlParamTuple("lM_DP_Area"));
            }
            else
            {
                lM_DP_OkNg = lM_DP_OkNg.TupleConcat(LM_DP_ProcedureCall.GetOutputCtrlParamTuple("luoMuDiePian_OKNG"));
                lM_DP_Num  = lM_DP_Num.TupleConcat(LM_DP_ProcedureCall.GetOutputCtrlParamTuple("lM_DP_Num"));
                lM_DP_Area = lM_DP_Area.TupleConcat(LM_DP_ProcedureCall.GetOutputCtrlParamTuple("lM_DP_Area"));
            }
            HRegion temp = new HRegion();

            temp = LM_DP_ProcedureCall.GetOutputIconicParamRegion("Result_Region");
            if (temp != null && temp.IsInitialized())
            {
                ResultRegion = ResultRegion.ConcatObj(temp);
                temp.Dispose();
            }
        }
Example #5
0
        HTuple GetGrayHisto(HTuple rectangle1)
        {
            if (HObjList == null || HObjList.Count < 1)
            {
                return(null);
            }
            HImage hv_image = HObjList[0].HObj as HImage;

            if (hv_image != null)
            {
                try
                {
                    HTuple hv_AbsoluteHisto, hv_RelativeHisto;

                    HTuple channel = hv_image.CountChannels();
                    HImage imgTmp  = null;
                    if (channel == 3)
                    {
                        imgTmp = hv_image.Rgb1ToGray();
                    }
                    else
                    {
                        imgTmp = hv_image.Clone();
                    }
                    HRegion region = new HRegion();
                    region.GenRectangle1(rectangle1[0].D, rectangle1[1], rectangle1[2], rectangle1[3]);
                    hv_AbsoluteHisto = imgTmp.GrayHisto(region, out hv_RelativeHisto);
                    return(hv_AbsoluteHisto);
                }
                catch (Exception)
                {
                }
            }
            return(null);
        }
Example #6
0
        /// <summary>
        ///   Return the initial or model components in a certain image.
        ///   Instance represents: Handle of the training result.
        /// </summary>
        /// <param name="components">Type of returned components or index of an initial component. Default: "model_components"</param>
        /// <param name="image">Image for which the components are to be returned. Default: "model_image"</param>
        /// <param name="markOrientation">Mark the orientation of the components. Default: "false"</param>
        /// <param name="row">Row coordinate of the found instances of all initial components or model components.</param>
        /// <param name="column">Column coordinate of the found instances of all initial components or model components.</param>
        /// <param name="angle">Rotation angle of the found instances of all components.</param>
        /// <param name="score">Score of the found instances of all components.</param>
        /// <returns>Contour regions of the initial components or of the model components.</returns>
        public HRegion GetTrainingComponents(
            string components,
            string image,
            string markOrientation,
            out double row,
            out double column,
            out double angle,
            out double score)
        {
            IntPtr proc = HalconAPI.PreCall(1009);

            this.Store(proc, 0);
            HalconAPI.StoreS(proc, 1, components);
            HalconAPI.StoreS(proc, 2, image);
            HalconAPI.StoreS(proc, 3, markOrientation);
            HalconAPI.InitOCT(proc, 1);
            HalconAPI.InitOCT(proc, 0);
            HalconAPI.InitOCT(proc, 1);
            HalconAPI.InitOCT(proc, 2);
            HalconAPI.InitOCT(proc, 3);
            int     err1 = HalconAPI.CallProcedure(proc);
            HRegion hregion;
            int     err2       = HRegion.LoadNew(proc, 1, err1, out hregion);
            int     err3       = HalconAPI.LoadD(proc, 0, err2, out row);
            int     err4       = HalconAPI.LoadD(proc, 1, err3, out column);
            int     err5       = HalconAPI.LoadD(proc, 2, err4, out angle);
            int     procResult = HalconAPI.LoadD(proc, 3, err5, out score);

            HalconAPI.PostCall(proc, procResult);
            GC.KeepAlive((object)this);
            return(hregion);
        }
        private void Act_Engine(HImage R, HImage B)
        {
            LanQuan_ProcedureCall.SetInputIconicParamObject("R", R);
            LanQuan_ProcedureCall.SetInputIconicParamObject("B", B);
            LanQuan_ProcedureCall.SetInputIconicParamObject("ROI_LanQuan_T", LanQuan_Region_Affine);
            LanQuan_ProcedureCall.SetInputCtrlParamTuple("minThreshold", new HTuple(minThreshold));
            LanQuan_ProcedureCall.SetInputCtrlParamTuple("filterRadiu", new HTuple(filterRadiu));
            LanQuan_ProcedureCall.SetInputCtrlParamTuple("minArea", new HTuple(minArea));
            LanQuan_ProcedureCall.Execute();
            if (LanQuan_OkNg.Length == 0)
            {
                LanQuan_OkNg = (LanQuan_ProcedureCall.GetOutputCtrlParamTuple("lanQuan_OKNG"));
                Area         = LanQuan_ProcedureCall.GetOutputCtrlParamTuple("Area");
            }
            else
            {
                LanQuan_OkNg = LanQuan_OkNg.TupleConcat(LanQuan_ProcedureCall.GetOutputCtrlParamTuple("lanQuan_OKNG"));
                Area         = Area.TupleConcat(LanQuan_ProcedureCall.GetOutputCtrlParamTuple("Area"));
            }
            HRegion temp = new HRegion();

            temp = LanQuan_ProcedureCall.GetOutputIconicParamRegion("Result_Region");
            if (temp != null && temp.IsInitialized())
            {
                ResultRegion = ResultRegion.ConcatObj(temp);
                temp.Dispose();
            }
        }
Example #8
0
        /// <summary>
        /// 从DataTable数据获取最终区域
        /// </summary>
        /// <param name="data">DataTable</param>
        /// <returns>最终区域</returns>
        public HRegion GenCompRegion(DataTable data)
        {
            var hRegion = new HRegion();

            hRegion.GenEmptyRegion();
            foreach (DataRow dr in data.Rows)
            {
                HRegion hr, htemp;
                hr = GetRegion(dr);
                if ((bool)dr["ToAdd"])
                {
                    htemp = hRegion | hr;
                }
                else
                {
                    htemp = hRegion / hr;
                }
                hr.Dispose();

                hRegion.Dispose();
                hRegion = htemp.CopyObj(1, -1);
                htemp.Dispose();
            }

            return(hRegion);
        }
        public void Close()
        {
            if (LanQuan_Region_Affine != null && LanQuan_Region_Affine.IsInitialized())
            {
                LanQuan_Region_Affine.Dispose();
            }
            LanQuan_Region_Affine = null;

            if (LanQuan_Region_Affines != null && LanQuan_Region_Affines.IsInitialized())
            {
                LanQuan_Region_Affines.Dispose();
            }
            LanQuan_Region_Affines = null;

            if (ResultRegion != null && ResultRegion.IsInitialized())
            {
                ResultRegion.Dispose();
            }
            ResultRegion = null;

            if (LanQuan_Region != null && !LanQuan_Region.IsInitialized())
            {
                LanQuan_Region = null;
            }

            LanQuan_ROIList.Clear();
            LanQuan_ROIList = null;
        }
        public void SerializeCheck()
        {
            if (LanQuan_Region_Affine != null && LanQuan_Region_Affine.IsInitialized())
            {
                LanQuan_Region_Affine.Dispose();
            }
            LanQuan_Region_Affine = null;

            if (LanQuan_Region_Affines != null && LanQuan_Region_Affines.IsInitialized())
            {
                LanQuan_Region_Affines.Dispose();
            }
            LanQuan_Region_Affines = null;

            if (ResultRegion != null && ResultRegion.IsInitialized())
            {
                ResultRegion.Dispose();
            }
            ResultRegion = null;

            if (LanQuan_Region != null && !LanQuan_Region.IsInitialized())
            {
                LanQuan_Region = null;
            }

            using (Stream objectStream = new MemoryStream())
            {
                System.Runtime.Serialization.IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                formatter.Serialize(objectStream, this);
            }
        }
        /// <summary>Gets the HALCON region described by the ROI</summary>
        public override HRegion getRegion()
        {
            HRegion region = new HRegion();

            region.GenRectangle2(midR, midC, -phi, length1, length2);
            return(region);
        }
Example #12
0
        public void SobelFilter(HDrawingObject dobj, HWindow hwin, string type)
        {
            try
            {
                HObject region = null;

                if (dobj.GetDrawingObjectParams("type") == "line")
                {
                    HTuple a = dobj.GetDrawingObjectParams("row1");
                    HOperatorSet.GenRegionLine(out region, dobj.GetDrawingObjectParams("row1"),
                                               dobj.GetDrawingObjectParams("column1"), dobj.GetDrawingObjectParams("row2"),
                                               dobj.GetDrawingObjectParams("column2"));
                }
                else
                {
                    region = new HRegion(dobj.GetDrawingObjectIconic());
                }

                AddToStack(region);
                DisplayResults();
            }
            catch (HalconException hex)
            {
                MessageBox.Show(hex.GetErrorMessage(), "HALCON error", MessageBoxButtons.OK);
            }
        }
Example #13
0
        /// <summary>Gets the HALCON region described by the ROI</summary>
        public override HRegion getRegion()
        {
            HRegion region = new HRegion();

            region.GenCircle(midR, midC, radius);
            return(region);
        }
Example #14
0
        public void Close()
        {
            if (hShapeModel != null && hShapeModel.IsInitialized())
            {
                hShapeModel.Dispose();
            }
            hShapeModel = null;
            if (modelRegion != null && modelRegion.IsInitialized())
            {
                modelRegion.Dispose();
            }
            modelRegion = null;

            if (modelXLDCont != null && modelXLDCont.IsInitialized())
            {
                modelXLDCont.Dispose();
            }
            modelXLDCont = null;
            if (modelXLDContAffine != null && modelXLDContAffine.IsInitialized())
            {
                modelXLDContAffine.Dispose();
            }
            modelXLDContAffine = null;

            shapeModelROIList = null;
        }
Example #15
0
        /// <summary>Gets the HALCON region described by the ROI.</summary>
        public override HRegion getRegion()
        {
            HRegion region = new HRegion();

            region.GenRegionLine(_StartRow, _StartColumn, _EndRow, _EndCol);
            return(region);
        }
Example #16
0
        /// <summary>Gets the HALCON region described by the ROI</summary>
        public override HRegion  getRegion()
        {
            HRegion region = new HRegion();

            region.GenRegionPolygonFilled(new HTuple(rows), new HTuple(cols));
            return((HRegion )region);
        }
        public HRegion Extract(HImage image)
        {
            if (!(LightDark == LightDark.Light || LightDark == LightDark.Dark))
            {
                throw new InvalidOperationException("BinaryThresholdRegionExtractor.LightDark must be Light or Dark. Now is " + LightDark);
            }

            HObject foundRegionObject;

            HDevelopExport.Singletone.GetRegionByBinaryThresholdRect2(image,
                                                                      out foundRegionObject,
                                                                      MeanMaskWidth,
                                                                      MeanMaskHeight,
                                                                      ScaleAdd,
                                                                      LightDark.ToHalconString(),
                                                                      AreaMin,
                                                                      AreaMax,
                                                                      OpeningWidth,
                                                                      OpeningHeight,
                                                                      ClosingWidth,
                                                                      ClosingHeight,
                                                                      ErosionWidth,
                                                                      ErosionHeight,
                                                                      DilationWidth,
                                                                      DilationHeight);

            var hRegion = new HRegion(foundRegionObject);

            return(hRegion);
        }
Example #18
0
 public void UpdateViewData(int val)
 {
     switch (val)
     {
     case ViewROI.ROIController.EVENT_CHANGED_ROI_SIGN:
     case ViewROI.ROIController.EVENT_DELETED_ACTROI:
     case ViewROI.ROIController.EVENT_UPDATE_ROI:
         bool genROI = view1.roiController.defineModelROI();
         ModelRoi = view1.roiController.getModelRegion();
         if (ModelRoi == null)
         {
             return;
         }
         if (!TemplateParam.CreateShapeModel(CurrentImage, ModelRoi))
         {
             Logger.PopError("模板创建失败!", true);
             return;
         }
         view1.ResetWindow();
         view1.AddViewObject(CurrentImage);
         view1.SetDraw("blue", "margin");
         view1.AddViewObject(ModelRoi);
         HXLD ModelContour = new HXLD();
         TemplateParam.GetShapeModelContour(out ModelContour);
         view1.SetDraw("green", "margin");
         view1.AddViewObject(ModelContour);
         view1.Repaint();
         break;
     }
 }
 /// <summary>
 /// Creates and initializes a measure object based on information the ROI object
 /// about the ROI.
 /// </summary>
 /// <param name="roi">ROI instance</param>
 /// <param name="mAssist">Reference to controller class</param>
 public Measurement(ROI roi, MeasureAssistant mAssist)
 {
     mMeasAssist = mAssist;
     mEdgeXLD = new HXLDCont();
     mMeasureRegion = new HRegion();
     initROI(roi);
 }
Example #20
0
        /// <summary>
        /// 图像处理
        /// </summary>
        /// <returns>返回8个点位数组</returns>
        public double[] Process()
        {
            double[] coorderate = new double[8];
            double   hv_RowBegin1; double hv_ColBegin1; double hv_RowEnd1; double hv_ColEnd1; double hv_Nr1; double hv_Nc1; double hv_Dist1;
            double   hv_RowBegin2; double hv_ColBegin2; double hv_RowEnd2; double hv_ColEnd2; double hv_Nr2; double hv_Nc2; double hv_Dist2;
            //图像阈值化,获得region
            HRegion hRegion = Ho_image.Threshold((double)LowThreshold, (double)HighThreshold);
            //region转化为himage
            HImage hImage = hRegion.RegionToBin(255, 0, 512, 512);
            //减去ROI以外多余部分
            HImage image1 = hImage.ReduceDomain(Region1);
            HImage image2 = hImage.ReduceDomain(Region2);
            //生成边缘轮廓
            HXLDCont edges1 = image1.EdgesSubPix("canny", 1, 5, 5);
            HXLDCont edges2 = image2.EdgesSubPix("canny", 1, 5, 5);
            //分割轮廓
            HXLDCont xldContsplit1 = edges1.SegmentContoursXld("lines_circles", 5, 4, 2);
            HXLDCont xldContsplit2 = edges2.SegmentContoursXld("lines_circles", 5, 4, 2);
            //根据特征筛选轮廓
            HXLDCont xldCont1 = xldContsplit1.SelectContoursXld("contour_length", 100, 99999999, -0.5, 0.5);
            HXLDCont xldCont2 = xldContsplit2.SelectContoursXld("contour_length", 100, 99999999, -0.5, 0.5);

            //拟合直线
            xldCont1.FitLineContourXld("tukey", -1, 0, 5, 2, out hv_RowBegin1, out hv_ColBegin1, out hv_RowEnd1, out hv_ColEnd1, out hv_Nr1, out hv_Nc1, out hv_Dist1);
            xldCont2.FitLineContourXld("tukey", -1, 0, 5, 2, out hv_RowBegin2, out hv_ColBegin2, out hv_RowEnd2, out hv_ColEnd2, out hv_Nr2, out hv_Nc2, out hv_Dist2);
            coorderate[0] = hv_RowBegin1;
            coorderate[1] = hv_ColBegin1;
            coorderate[2] = hv_RowEnd1;
            coorderate[3] = hv_ColEnd1;
            coorderate[4] = hv_RowBegin2;
            coorderate[5] = hv_ColBegin2;
            coorderate[6] = hv_RowEnd2;
            coorderate[7] = hv_ColEnd2;
            return(coorderate);
        }
Example #21
0
        public void SetModelImage()
        {
            if (ModelImg != null)
            {
                ModelImg.Dispose();
            }
            ModelImg = new HImage(InputImg);

            if (SearchRegion != null)
            {
                SearchRegion.Dispose();
                SearchRegion = null;
            }

            if (ModelRegion != null)
            {
                ModelRegion.Dispose();
                ModelRegion = null;
            }

            if (nCCModel != null)
            {
                nCCModel.Dispose();
                nCCModel = null;
            }
        }
Example #22
0
 private void AffineTransModelContour(HShapeModel model, HRegion modelRegion)
 {
     if (model != null && modelRegion != null)
     {
         try
         {
             //获取金字塔第一层轮廓
             HXLDCont modelContour = model.GetShapeModelContours(1);
             double   num3, num4;
             modelRegion.AreaCenter(out num3, out num4);
             HHomMat2D matd = new HHomMat2D();
             matd.VectorAngleToRigid(0.0, 0.0, 0.0, num3, num4, 0.0);
             HXLD affterAffineModelXLD = matd.AffineTransContourXld(modelContour);
             if (info.IsShowModelXLD)
             {
                 Window.SetColor("green");
                 affterAffineModelXLD.DispXld(Window.Window);
             }
         }
         catch (Exception e)
         {
             WriteErrorLog("VisionTool", e.ToString());
         }
     }
 }
Example #23
0
        private void CreateBtn_Click(object sender, System.EventArgs e)
        {
            HImage  ImgReduced;
            HRegion Rectangle1 = new HRegion();
            HRegion Rectangle2 = new HRegion();

            CreateBtn.Enabled = false;
            Window.SetColor("red");
            Window.SetDraw("margin");
            Window.SetLineWidth(3);

            ImgReduced = Img.ReduceDomain(Rectangle);
            ImgReduced.InspectShapeModel(out ModelRegion, 1, 30);
            Rectangle1.GenRectangle2(Rect1Row, Rect1Col, RectPhi, RectLength1, RectLength2);
            Rectangle2.GenRectangle2(Rect2Row, Rect2Col, RectPhi, RectLength1, RectLength2);
            ShapeModel = new HShapeModel(ImgReduced, 4, 0, new HTuple(360.0).TupleRad().D,
                                         new HTuple(1.0).TupleRad().D, "none", "use_polarity", 30, 10);

            Window.SetColor("green");
            Window.SetDraw("fill");
            ModelRegion.DispObj(Window);
            Window.SetColor("blue");
            Window.SetDraw("margin");
            Rectangle1.DispObj(Window);
            Rectangle2.DispObj(Window);

            StopBtn.Enabled  = false;
            StartBtn.Enabled = true;
        }
Example #24
0
        /// <summary>
        ///   Classify a single character with an OCR classifier.
        ///   Instance represents: Handle of the k-NN classifier.
        /// </summary>
        /// <param name="character">Character to be recognized.</param>
        /// <param name="image">Gray values of the character.</param>
        /// <param name="numClasses">Number of maximal classes to determine. Default: 1</param>
        /// <param name="numNeighbors">Number of neighbors to consider. Default: 1</param>
        /// <param name="confidence">Confidence(s) of the class(es) of the character.</param>
        /// <returns>Results of classifying the character with the k-NN.</returns>
        public HTuple DoOcrSingleClassKnn(
            HRegion character,
            HImage image,
            HTuple numClasses,
            HTuple numNeighbors,
            out HTuple confidence)
        {
            IntPtr proc = HalconAPI.PreCall(659);

            this.Store(proc, 0);
            HalconAPI.Store(proc, 1, (HObjectBase)character);
            HalconAPI.Store(proc, 2, (HObjectBase)image);
            HalconAPI.Store(proc, 1, numClasses);
            HalconAPI.Store(proc, 2, numNeighbors);
            HalconAPI.InitOCT(proc, 0);
            HalconAPI.InitOCT(proc, 1);
            int err1 = HalconAPI.CallProcedure(proc);

            HalconAPI.UnpinTuple(numClasses);
            HalconAPI.UnpinTuple(numNeighbors);
            HTuple tuple;
            int    err2       = HTuple.LoadNew(proc, 0, err1, out tuple);
            int    procResult = HTuple.LoadNew(proc, 1, HTupleType.DOUBLE, err2, out confidence);

            HalconAPI.PostCall(proc, procResult);
            GC.KeepAlive((object)this);
            GC.KeepAlive((object)character);
            GC.KeepAlive((object)image);
            return(tuple);
        }
Example #25
0
        private void WindowControl_Load(object sender, EventArgs e)
        {
            string ImgType;

            Window       = WindowControl.HalconWindow;
            Framegrabber = new HFramegrabber("File", 1, 1, 0, 0, 0, 0, "default",
                                             -1, "default", -1, "default",
                                             "board/board.seq", "default", 1, -1);
            Img = Framegrabber.GrabImage();
            Img.GetImagePointer1(out ImgType, out ImgWidth, out ImgHeight);
            Window.SetPart(0, 0, ImgHeight - 1, ImgWidth - 1);
            Img.DispObj(Window);
            Window.SetDraw("margin");
            Window.SetLineWidth(3);
            Rectangle = new HRegion(188.0, 182, 298, 412);
            Rectangle.AreaCenter(out Row, out Column);
            Rect1Row         = Row - 102;
            Rect1Col         = Column + 5;
            Rect2Row         = Row + 107;
            Rect2Col         = Column + 5;
            RectPhi          = 0;
            RectLength1      = 170;
            RectLength2      = 5;
            this.MouseWheel += my_MouseWheel;
        }
Example #26
0
        public HImage SegmentImage()
        {
            HRegion region, connectedRegions, selectedRegions, SortedRegions;
            HRegion regionDilated, tmpRegion;
            HImage  imgReduced;
            HTuple  row1, row2;
            HTuple  col1, col2;

            region = image.Threshold(minGray, maxGray);

            regionDilated    = region.Connection().DilationRectangle1(dilationH, dilationW);
            selectedRegions  = regionDilated.SelectShape(new HTuple("area", "row"), "and", new HTuple(2000, 400), new HTuple(60000, 2200));
            connectedRegions = selectedRegions.Union1().Connection();
            connectedRegions.SmallestRectangle1(out row1, out col1, out row2, out col2);
            tmpRegion = new HRegion();
            tmpRegion.GenRectangle1(row1, col1, row2, col2);
            imgReduced = image.ReduceDomain(tmpRegion.Union1());

            region          = imgReduced.Threshold(12.0, 255.0);
            selectedRegions = region.Connection().SelectShape("area", "and", 1000, 6000);
            imgReduced.GetImageSize(out imgH, out imgW);
            segImage = selectedRegions.ClosingRectangle1(8, 3).Union1().RegionToBin(255, 0, imgH, imgW);

            //SortedRegions = selectedRegions.SortRegion("character", "true", "row");
            return(segImage);
        }// HImage SegmentImage()
Example #27
0
        private void HWindowControl1_HMouseDown(object sender, HMouseEventArgs e)
        {
            if (drawFrame == DrawFrame.Brush)
            {
                HRegion region = new HRegion(e.Y, e.X, (int)brushSize);
                if (e.Button == MouseButtons.Left)
                {
                    ChangeMaskHRegion(region);
                }
                DisplayMaskRegion();
                hWindowControl1.HalconWindow.SetColor("blue");
                hWindowControl1.HalconWindow.DispObj(region);
                region.Dispose();
            }


            if (ctrller.ActiveROIIndex < 0 && rOI == null && drawFrame != DrawFrame.Brush)
            {
                if (e.Button == MouseButtons.Left)
                {
                    hWndCtrller.SetViewMode(HWndCtrller.MODE_VIEW_MOVE);
                }
            }
            rOI = null;
        }
Example #28
0
        /// <summary>
        ///   Asynchronous grab of images and preprocessed image data from the specified image acquisition device.
        ///   Instance represents: Handle of the acquisition device to be used.
        /// </summary>
        /// <param name="region">Pre-processed image regions.</param>
        /// <param name="contours">Pre-processed XLD contours.</param>
        /// <param name="maxDelay">Maximum tolerated delay between the start of the asynchronous grab and the delivery of the image [ms]. Default: -1.0</param>
        /// <param name="data">Pre-processed control data.</param>
        /// <returns>Grabbed image data.</returns>
        public HImage GrabDataAsync(
            out HRegion region,
            out HXLDCont contours,
            double maxDelay,
            out string data)
        {
            IntPtr proc = HalconAPI.PreCall(2029);

            this.Store(proc, 0);
            HalconAPI.StoreD(proc, 1, maxDelay);
            HalconAPI.InitOCT(proc, 1);
            HalconAPI.InitOCT(proc, 2);
            HalconAPI.InitOCT(proc, 3);
            HalconAPI.InitOCT(proc, 0);
            int    err1 = HalconAPI.CallProcedure(proc);
            HImage himage;
            int    err2       = HImage.LoadNew(proc, 1, err1, out himage);
            int    err3       = HRegion.LoadNew(proc, 2, err2, out region);
            int    err4       = HXLDCont.LoadNew(proc, 3, err3, out contours);
            int    procResult = HalconAPI.LoadS(proc, 0, err4, out data);

            HalconAPI.PostCall(proc, procResult);
            GC.KeepAlive((object)this);
            return(himage);
        }
Example #29
0
        public HRegion Extract(HImage image)
        {
            var domain        = image.GetDomain();
            var offsetRow1    = domain.GetRow1();
            var offsetColumn1 = domain.GetColumn1();
            var croppedImage  = image.CropDomain();

            var    swThresholdImageFilter = new NotifyStopwatch("DynThresholdCroppedRegionExtractor.ThresholdImageFilter");
            HImage thresholdImage         = ThresholdImageFilter.Process(croppedImage);

            swThresholdImageFilter.Dispose();

            var     swDynThreshold = new NotifyStopwatch("DynThresholdCroppedRegionExtractor.DynThreshold");
            HRegion region         = croppedImage.DynThreshold(
                thresholdImage,
                Offset,
                LightDark.ToHalconString());

            swDynThreshold.Dispose();

            var movedRegion = region.MoveRegion(offsetRow1, offsetColumn1);

            croppedImage.Dispose();
            thresholdImage.Dispose();
            region.Dispose();

            return(movedRegion);
        }
Example #30
0
        public void SerializeCheck()
        {
            if (modelXLDCont != null && modelXLDCont.IsInitialized())
            {
                modelXLDCont.Dispose();
            }
            if (modelXLDContAffine != null && modelXLDContAffine.IsInitialized())
            {
                modelXLDContAffine.Dispose();
            }

            modelXLDCont       = null;
            modelXLDContAffine = null;

            if (hShapeModel != null && !hShapeModel.IsInitialized())
            {
                hShapeModel = null;
            }
            if (modelRegion != null && !modelRegion.IsInitialized())
            {
                modelRegion = null;
            }

            using (Stream objectStream = new MemoryStream())
            {
                System.Runtime.Serialization.IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                formatter.Serialize(objectStream, this);
            }
        }
Example #31
0
        /// <summary>Gets the HALCON region described by the ROI.</summary>
        public override HRegion getRegion()
        {
            HRegion region = new HRegion();

            region.GenRegionLine(row1, col1, row2, col2);
            return(region);
        }
        /// <summary>
        /// Creates and initializes a measure object based on information the ROI object
        /// about the ROI.
        /// </summary>
        /// <param name="roi">ROI instance</param>
        /// <param name="mAssist">Reference to controller class</param>
        public Measurement(ROI roi, MeasureAssistant mAssist)
        {
            mRoi = roi;
            mMeasAssist = mAssist;
            mROICoord = mRoi.getModelData();
            mEdgeXLD = new HXLDCont();
            mMeasureRegion = new HRegion();

            if (mRoi is ROICircularArc)
                mROIType = ROI.ROI_TYPE_CIRCLEARC;
            else
                mROIType = ROI.ROI_TYPE_LINE;
        }
 /// <summary>Gets the HALCON region described by the ROI.</summary>
 public override HRegion getRegion()
 {
     HRegion region = new HRegion();
     region.GenRegionLine(_StartRow, _StartColumn, _EndRow, _EndCol);
     return region;
 }
        /**********************************************************************/
        /**********************************************************************/
        /*                     Delegate Routines                              */
        /**********************************************************************/
        /**********************************************************************/
        /// <summary>
        /// This method is invoked if changes occur in the HWndCtrl instance
        /// or the ROIController. In either case, the HALCON 
        /// window needs to be updated/repainted.
        /// </summary>
        public void UpdateViewData(int val)
        {
            switch(val)
            {
                case ROIController.EVENT_CHANGED_ROI_SIGN:
                case ROIController.EVENT_DELETED_ACTROI:
                case ROIController.EVENT_DELETED_ALL_ROIS:
                case ROIController.EVENT_UPDATE_ROI:
                    ModelContour = null;
                    DetectionContour = null;
                    bool genROI = roiController.defineModelROI();
                    ModelRegion = roiController.getModelRegion();
                    mAssistant.setModelROI(ModelRegion);
                    CreateModelGraphics();
                    if(!genROI)
                        mView.repaint();

                    break;
                case HWndCtrl.ERR_READING_IMG:
                    MessageBox.Show("Problem occured while reading file! \n" + mView.exceptionText,
                        "Matching assistant",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Information);
                    break;
                default:
                    break;
            }
        }
Example #35
0
 /// <summary>Gets the HALCON region described by the ROI.</summary>
 public override HRegion getRegion()
 {
     HRegion region = new HRegion();
     region.GenRegionLine(row1, col1, row2, col2);
     return region;
 }
        /// <summary>
        /// Creates an iconic object depicting the 
        /// measuring field.
        /// </summary>
        public void UpdateMeasureRegion()
        {
            mMeasureRegion.Dispose();
            mMeasureRegion.GenEmptyObj();

            if (mROIType == ROI.ROI_TYPE_CIRCLEARC)
            {
                double sPhi, extent, innerRad, outerRad;
                HTuple innerR, outerR, innerC, outerC;
                HXLDCont outCont, innerCont, contour;

                outCont = new HXLDCont();
                innerCont = new HXLDCont();

                sPhi = mMeasROI[2].D;
                extent = mMeasROI[3].D;
                outerRad = mMeasROI[4].D;
                innerRad = mMeasROI[5].D;

                innerCont.GenCircleContourXld(mMeasROI[0].D, mMeasROI[1].D, innerRad, sPhi, (sPhi + extent), (extent > 0) ? "positive" : "negative", 1.0);
                outCont.GenCircleContourXld(mMeasROI[0].D, mMeasROI[1].D, outerRad, (sPhi + extent), sPhi, (extent > 0) ? "negative" : "positive", 1.0);

                innerCont.GetContourXld(out innerR, out innerC);
                outCont.GetContourXld(out outerR, out outerC);
                innerR = innerR.TupleConcat(outerR);
                innerC = innerC.TupleConcat(outerC);

                contour = new HXLDCont(innerR, innerC);
                contour = contour.CloseContoursXld();

                mMeasureRegion = contour.GenRegionContourXld("margin");

                contour.Dispose();
                innerCont.Dispose();
                outCont.Dispose();
            }
            else
            {
                mMeasureRegion.GenRectangle2(mMeasROI[0].D, mMeasROI[1].D,
                                             mMeasROI[2].D, mMeasROI[3].D,
                                             mMeasROI[4].D);
            }
        }
        /// <summary>
        /// Compute the model image and the model contour for the applied ROI.
        /// </summary>
        public void setModelROI(HRegion roi)
        {
            mROIModel	= roi;
            PyramidROIs = null;
            createNewModelID = true;

            if(mROIModel==null)
            {
                mImage = null;
                return;
            }

            mImage = oImage.ReduceDomain(mROIModel);

            determineStepRanges();

            if(parameterSet.isOnAuto())
                determineShapeParameter();

            inspectShapeModel();
        }
 /// <summary>Gets the HALCON region described by the ROI</summary>
 public override HRegion getRegion()
 {
     HRegion region = new HRegion();
     region.GenCircle(midR, midC, radius);
     return region;
 }
        /// <summary>
        /// 更新量測結果.
        /// 量測演算法放這裡
        /// </summary>
        public override void UpdateResults()
        {
            if (mMeasAssist.mImage == null) return;

            #region 初始化數值
            if (!String.IsNullOrEmpty(mMeasAssist.FitCircleAlgo))
                _Algorithm = new HTuple(mMeasAssist.FitCircleAlgo);

            //init result
            mResult = new CircleResult();

            // Local iconic variables
            HObject ho_MeasureROI, ho_ImageReduced;
            HObject ho_Border, tmp_Border;

            // Initialize local and output iconic variables
            HOperatorSet.GenEmptyObj(out ho_MeasureROI);
            HOperatorSet.GenEmptyObj(out ho_ImageReduced);
            HOperatorSet.GenEmptyObj(out ho_Border);
            HOperatorSet.GenEmptyObj(out tmp_Border);
            #endregion

            try
            {
                //******* Create ROI ********
                ho_MeasureROI.Dispose();
                HOperatorSet.GenCircle(out ho_MeasureROI, mROICoord[0], mROICoord[1], mROICoord[2]);
                HRegion region = new HRegion();
                region.GenCircle(mROICoord[0].D, mROICoord[1].D, mROICoord[2].D);

                //****** Area Center, 取得目標區域的 pixels 數 ***********
                HTuple area, areaRow, areaColumn;
                double areaPixels = 0.0;
                HOperatorSet.AreaCenter(region, out area, out areaRow, out areaColumn);
                areaPixels = area.D;

                //****** 取得影像 ******
                var himage = mMeasAssist.getImage();

                //******* Extract ROI Image *****
                ho_ImageReduced.Dispose();
                HOperatorSet.ReduceDomain(himage, ho_MeasureROI, out ho_ImageReduced);

                //******* Filter ****************
                var subpixThreadhold = mMeasAssist.SubpixThreadhold;
                HOperatorSet.GenEmptyObj(out ho_Border);
                HOperatorSet.ThresholdSubPix(ho_ImageReduced, out ho_Border, subpixThreadhold);

                if (mMeasAssist.ApplyCalibration && mMeasAssist.IsCalibrationValid)
                {
                    if (_cameraOut.TupleLength() == 0)
                    {
                        _cameraOut = HMisc.ChangeRadialDistortionCamPar("adaptive", mMeasAssist.CameraIn, 0.0);
                    }
                    //var rectifyImage = himage.ChangeRadialDistortionImage(region, mMeasAssist.CameraIn, cameraOut);
                    HObject calibrationBorder;
                    HOperatorSet.GenEmptyObj(out calibrationBorder);
                    HOperatorSet.ChangeRadialDistortionContoursXld(ho_Border, out calibrationBorder, mMeasAssist.CameraIn, _cameraOut);
                    mResult = fitCircle(calibrationBorder, areaPixels);
                }
                else
                {
                    mResult = fitCircle(ho_Border, areaPixels);
                }

            }
            catch (HOperatorException ex)
            {
                Hanbo.Log.LogManager.Error(ex);
                mResultWorld = new CircleResult();
                mResult = new CircleResult();
            }
            finally
            {
                ho_MeasureROI.Dispose();
                ho_ImageReduced.Dispose();
                ho_Border.Dispose();
            }
            UpdateXLD();
        }
 /// <summary>Gets the HALCON region described by the ROI</summary>
 public override HRegion getRegion()
 {
     HRegion region;
     contour.Dispose();
     contour.GenCircleContourXld(midR, midC, radius, startPhi, (startPhi + extentPhi), circDir, 1.0);
     region = new HRegion(contour);
     return region;
 }
 /// <summary>
 /// Clears all variables managing ROI objects
 /// </summary>
 public void reset()
 {
     ROIList.Clear();
     activeROIidx = -1;
     ModelROI = null;
     roiMode = null;
     NotifyRCObserver(EVENT_DELETED_ALL_ROIS);
 }
 private HRegion getRectangle2(HTuple row, HTuple column, double degree, HTuple length1, HTuple length2)
 {
     var theta = new HTuple(degree.ToHalconPhi());
     HRegion region = new HRegion();
     region.GenRectangle2(row, column, theta, length1, length2);
     return region;
 }
 /// <summary>Gets the HALCON region described by the ROI</summary>
 public override HRegion getRegion()
 {
     HRegion region = new HRegion();
     region.GenRectangle2(midR, midC, -phi, length1, length2);
     return region;
 }
 private HImage getRegionImage(HRegion region)
 {
     HImage regionImage = null;
     if (mMeasAssist.ApplyCalibration && mMeasAssist.IsCalibrationValid)
     {
         regionImage = mMeasAssist.mImage.ChangeRadialDistortionImage(region, mMeasAssist.CameraIn, _cameraOut);
     }
     else
     {
         HObject imageReduced;
         HOperatorSet.GenEmptyObj(out imageReduced);
         HOperatorSet.ReduceDomain(mMeasAssist.mImage, region, out imageReduced);
         regionImage = new HImage(imageReduced);
     }
     return regionImage;
 }
 /// <summary>
 /// 
 /// </summary>
 private void viewPort_HInitWindow(object sender, EventArgs e)
 {
     hImage = null;
     regionOfInterest = new HRegion();
 }
 /// <summary>
 /// Update the current ROI (region of interest) according to 
 /// the changes that were performed through user interaction.
 /// </summary>
 private void CalcCurrentROI()
 {
     bool genROI = false;
     try
     {
         genROI = roiController.defineModelROI();
     }
     catch (HOperatorException exception)
     {
         MessageBox.Show("Error occured during calculating" +
                         " the region of interest:\n" +
                         exception.Message);
         hWndControl.repaint();
     }
     regionOfInterest = roiController.getModelRegion();
     if (!genROI)
         hWndControl.repaint();
 }
        /// <summary>
        /// Determine s(or updates) the basic information for this 
        /// calibration image, which are the values for the region 
        /// plate, the center marks, and the estimated pose. 
        /// The flag <c>mPlateStatus</c> describes the evaluation 
        /// of the computation process.
        /// If desired the quality assessment can be recalculated 
        /// as well.
        /// </summary>
        /// <param name="updateQuality">
        /// Triggers the recalculation of the quality assessment for
        /// this calibration image 
        /// </param>
        public void UpdateCaltab(bool updateQuality)
        {
            HTuple worldX, worldY;
            HTuple unit = new HTuple("m");

            bool failed = false;
            QualityProcedures proc = new QualityProcedures();
            string descrFile;
            HTuple startCamp;
            mErrorMessage = "";

            mCaltabRegion.Dispose();
            mMarkCenter.Dispose();
            mEstimatedWCS.Dispose();

            //reset this variable
            mMarkCenterRows = new HTuple();

            mPlateStatus =  CalibrationAssistant.PS_NOT_FOUND ;

            descrFile = mAssistant.getDesrcFile();

            try
            {
                mCaltabRegion = mImage.FindCaltab(descrFile,
                                                 (int)mAssistant.mFilterSize,
                                                 (int)mAssistant.mMarkThresh,
                                                 (int)mAssistant.mMinMarkDiam);

                mPlateStatus = CalibrationAssistant.PS_MARKS_FAILED;

                //-- Quality issue measurements --
                if(updateQuality)
                {
                    mQualityIssuesList.Clear();
                    failed = mAssistant.testQualityIssues(this);
                }

                startCamp = mAssistant.getCameraParams(this);
                mMarkCenterRows = mImage.FindMarksAndPose(mCaltabRegion,
                                                          descrFile,
                                                          startCamp,
                                                          (int)mAssistant.mInitThresh,
                                                          (int)mAssistant.mThreshDecr,
                                                          (int)mAssistant.mMinThresh,
                                                          mAssistant.mSmoothing,
                                                          mAssistant.mMinContLength,
                                                          mAssistant.mMaxMarkDiam,
                                                          out mMarkCenterCols,
                                                          out mEstimatedPose);

                mMarkCenter.GenCrossContourXld(mMarkCenterRows,
                                               mMarkCenterCols,
                                               new HTuple(6.0),
                                               0.785398);

                if(failed)
                    mAssistant.addQualityIssue(this, CalibrationAssistant.QUALITY_ISSUE_FAILURE, 0.0);

               HOperatorSet.ImagePointsToWorldPlane(startCamp, mEstimatedPose,
                                                    mMarkCenterRows, mMarkCenterCols,
                                                    unit, out worldX, out worldY);
               mEstimatedPlateSize = HMisc.DistancePp(worldY[0].D, worldX[0].D,
                                                      worldY[1].D, worldX[1].D);
               mEstimatedPlateSize *=10.0;
               proc.get_3d_coord_system(mImage, out mEstimatedWCS,
                                        startCamp, mEstimatedPose,
                                        new HTuple(mEstimatedPlateSize/2.0));

               mPlateStatus = mQualityIssuesList.Count>0 ? CalibrationAssistant.PS_QUALITY_ISSUES:CalibrationAssistant.PS_OK; // "Quality Issues found": "OK";
               mCanCalib   = 0;
            }
            catch(HOperatorException e)
            {
                this.mErrorMessage = e.Message;
                mCanCalib = 1;

                /* if exception was raised due to lack of memory,
                 * forward the error to the calling method */
                if(e.Message.IndexOf("not enough")!=-1)
                    throw(e);
            }
        }
        /// <summary>
        /// Calculates the ModelROI region for all objects contained 
        /// in ROIList, by adding and subtracting the positive and 
        /// negative ROI objects.
        /// </summary>
        public bool defineModelROI()
        {
            HRegion tmpAdd, tmpDiff, tmp;
            double row, col;

            if (stateROI == MODE_ROI_NONE)
                return true;

            tmpAdd = new HRegion();
            tmpDiff = new HRegion();
            tmpAdd.GenEmptyRegion();
            tmpDiff.GenEmptyRegion();

            for (int i = 0; i < ROIList.Count; i++)
            {
                switch (((ROI)ROIList[i]).getOperatorFlag())
                {
                    case ROI.POSITIVE_FLAG:
                        tmp = ((ROI)ROIList[i]).getRegion();
                        tmpAdd = tmp.Union2(tmpAdd);
                        break;
                    case ROI.NEGATIVE_FLAG:
                        tmp = ((ROI)ROIList[i]).getRegion();
                        tmpDiff = tmp.Union2(tmpDiff);
                        break;
                    default:
                        break;
                }//end of switch
            }//end of for

            ModelROI = null;

            if (tmpAdd.AreaCenter(out row, out col) > 0)
            {
                tmp = tmpAdd.Difference(tmpDiff);
                if (tmp.AreaCenter(out row, out col) > 0)
                    ModelROI = tmp;
            }

            //in case the set of positiv and negative ROIs dissolve
            if (ModelROI == null || ROIList.Count == 0)
                return false;

            return true;
        }
        /// <summary>
        /// Initializes all status flags and objects to set up 
        /// this image for the calibration process
        /// </summary>
        /// <param name="img">Calibration image</param>
        /// <param name="assist">Reference to the Calibration Assistant</param>
        public CalibImage(HImage img, CalibrationAssistant assist)
        {
            string tmp;
            mImage     = img;

            mAssistant = assist;
            mCanCalib  = 1;  //labeled as 'for not having been evaluated'
            mPlateStatus = CalibrationAssistant.PS_NOT_FOUND;// "No Plate found" yet
            mImage.GetImagePointer1(out tmp, out mWidth, out mHeight);
            mEstimatedPlateSize = 0;
            mErrorMessage       = "";

            // initialize all instances
            mCaltabRegion      = new HRegion();
            mMarkCenter        = new HXLDCont();
            mEstimatedWCS      = new HObject();
            mQualityIssuesList = new ArrayList(15);

            mMarkCenterRows = new HTuple();
            mMarkCenterCols = new HTuple();
            mEstimatedPose  = new HPose ();
        }
 /// <summary>Constructor</summary>
 public ROIController()
 {
     stateROI = MODE_ROI_NONE;
     ROIList = new ArrayList();
     activeROIidx = -1;
     ModelROI = new HRegion();
     NotifyRCObserver = new IconicDelegate(dummyI);
     deletedIdx = -1;
     currX = currY = -1;
 }
        /// <summary>
        /// Compute the model image and the model contour for the applied ROI.
        /// </summary>
        public void setModelROI(HRegion roi)
        {
            mROIModel = roi;
            PyramidROIs = null;
            createNewModelID = true;

            if (mROIModel == null)
            {
                mImage = null;
                return;
            }

            mImage = oImage.ReduceDomain(mROIModel);

            deterimineParamsAndInspectShapeModel();
        }
        /// <summary>
        /// Clears all model creation and detection results 
        /// and resets flags to their initial values.
        /// </summary>
        public void reset()
        {
            mROIModel	= null;
            currentImgLevel = 1;
            PyramidROIs = null;
            PyramidImages = null;
            mImage = null;
            scaleH = 1;
            scaleW = 1;
            createNewModelID = true;

            tResult.reset();
            NotifyIconObserver(MatchingAssistant.UPDATE_XLD);
        }
        /// <summary>
        /// Triggers an update of the measure results because of  
        /// changes in the parameter setup or a recreation of the measure 
        /// object caused by an update in the ROI model.
        /// </summary>               
        public override void UpdateResults()
        {
            if (mHandle == null)
                return;

            mMeasAssist.exceptionText = "";

            try
            {
                HObject imageReduced;
                HOperatorSet.GenEmptyObj(out imageReduced);
                //«Ø ROI
                var roiModel = mRoi.getModelData();
                var row = roiModel[0];
                var column = roiModel[1];
                var phi = roiModel[2];
                var length1 = roiModel[3];
                var length2 = roiModel[4];
                HRegion region = new HRegion();
                region.GenRectangle2(row.D, column.D, phi.D, length1.D, length2.D);

                if (mMeasAssist.ApplyCalibration && mMeasAssist.IsCalibrationValid)
                {
                    HTuple cameraOut = HMisc.ChangeRadialDistortionCamPar("adaptive", mMeasAssist.CameraIn, 0.0);
                    var rectifyImage = mMeasAssist.mImage.ChangeRadialDistortionImage(region, mMeasAssist.CameraIn, cameraOut);
                    measurePos(rectifyImage);
                }
                else
                {
                    HOperatorSet.ReduceDomain(mMeasAssist.mImage, region, out imageReduced);
                    measurePos(new HImage(imageReduced));
                }
                mResultWorld = new EdgeResult(mResult);
            }
            catch (HOperatorException e)
            {
                mEdgeXLD.Dispose();
                mMeasAssist.exceptionText = e.Message;
                mResultWorld = new EdgeResult();
                return;
            }
            UpdateXLD();
        }
        private void init()
        {
            //default value
            CanCalibFlag = 1;  //labeled as 'for not having been evaluated'
            PlateStatus = CalibrationAssistant.PS_NOT_FOUND;// "No Plate found" yet
            _mEstimatedPlateSize = 0;
            ErrorMessage = "";

            //Image width and height
            string tmp;
            _mImage.GetImagePointer1(out tmp, out Width, out Height);

            // initialize all instances
            _mCaltabRegion = new HRegion();
            _mMarkCenter = new HXLDCont();
            _mEstimatedWCS = new HObject();
            _mQualityIssuesList = new ArrayList(15);

            _mMarkCenterRows = new HTuple();
            _mMarkCenterCols = new HTuple();
            _mEstimatedPose = new HPose();
        }
        /// <summary>
        /// 更新量測結果.
        /// 量測演算法放這裡
        /// </summary>
        public override void UpdateResults()
        {
            if (mMeasAssist.mImage == null) return;
            //init result
            mResult = new FitLineResult()
            {
                Col1 = new HTuple(),
                Row1 = new HTuple(),
                Col2 = new HTuple(),
                Row2 = new HTuple(),
            };
            var image = mMeasAssist.getImage();

            HObject imageReduced;
            HOperatorSet.GenEmptyObj(out imageReduced);

            //建 ROI
            var roiModel = mRoi.getModelData();
            var row = roiModel[0];
            var column = roiModel[1];
            var phi = roiModel[2].D * -1;//修正為 Retangle 2 的方向
            var length1 = roiModel[3];
            var length2 = roiModel[4];

            HRegion region = new HRegion();
            region.GenRectangle2(row.D, column.D, phi, length1.D, length2.D);
            HOperatorSet.ReduceDomain(image, region, out imageReduced);
            try
            {
                HOperatorSet.WriteImage(imageReduced, "tiff", 0, @"D:\ttt.tif");
            }
            catch (Exception)
            {

            }
            var contoursSplit = extractEdges(imageReduced);

            try
            {
                if (mMeasAssist.ApplyCalibration && mMeasAssist.IsCalibrationValid)
                {
                    if (_cameraOut.TupleLength() == 0)
                        HOperatorSet.ChangeRadialDistortionCamPar("adaptive", mMeasAssist.CameraIn, 0, out _cameraOut);

                    HObject calibrationContoursSplits;
                    HOperatorSet.GenEmptyObj(out calibrationContoursSplits);

                    //var imageRect = image.ChangeRadialDistortionImage(region, mMeasAssist.CameraIn, _cameraOut);
                    //mResult = fitline(imageRect, true);
                    HOperatorSet.ChangeRadialDistortionContoursXld(contoursSplit, out calibrationContoursSplits, mMeasAssist.CameraIn, _cameraOut);
                    mResult = fitline(calibrationContoursSplits);
                }
                else
                {
                    mResult = fitline(contoursSplit);
                }
                mResultWorld = new FitLineResult(mResult);
            }
            catch (HOperatorException ex)
            {
                Hanbo.Log.LogManager.Error(ex);
            }
            UpdateXLD();
        }
Example #56
0
 /// <summary>Gets the HALCON region described by the ROI</summary>
 public override HRegion getRegion()
 {
     HRegion region;
     contour.Dispose();
     contour.GenCircleContourXld(midR, midC, radius, _startPhi, (_startPhi + _extentPhi), _pointOrder, 1.0);
     region = new HRegion(contour);
     return region;
 }