コード例 #1
0
        public HXLDCont CreateShapeModel(HImage img, ModelParameter modelParameter, out HShapeModel model)
        {
            model = new HShapeModel(
                img,
                modelParameter.numLevels,
                modelParameter.angleStart,
                modelParameter.angleExtent,
                modelParameter.angleStep,
                modelParameter.scaleMin,
                modelParameter.scaleMax,
                modelParameter.scaleStep,
                modelParameter.optimization,
                modelParameter.metric,
                modelParameter.contrast,
                modelParameter.minContrast);



            var modelContours = Model.GetShapeModelContours(1);

            var homMat2D = new HHomMat2D();


            homMat2D.VectorAngleToRigid(0, 0, 0, ModelRegion.Row, ModelRegion.Column, 0);
            var contoursAffinTrans = modelContours.AffineTransContourXld(homMat2D);

            return(contoursAffinTrans);
        }
コード例 #2
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;
        }
コード例 #3
0
ファイル: ShapeModel.cs プロジェクト: wb2856385025/Simulation
        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 (shapeModel != null)
            {
                shapeModel.Dispose();
                shapeModel = null;
            }
        }
コード例 #4
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());
         }
     }
 }
コード例 #5
0
        private void bCreateModel_Click(object sender, EventArgs e)
        {
            if (Edges != null)
            {
                HTuple startAngle  = new HTuple((double)this.startAngle.Value).TupleRad();
                HTuple extendAngle = new HTuple((double)(this.endAngle.Value - this.startAngle.Value)).TupleRad();

                try
                {
                    this.ShapeModel = new HShapeModel
                                          (this.Edges,
                                          "auto", // 金子塔级别
                                          startAngle,
                                          extendAngle,
                                          "auto", // 角度步长
                                          this.DeParent.YMinScale,
                                          this.DeParent.YMaxScale,
                                          "auto", // X放大步长
                                          this.DeParent.XMinScale,
                                          this.DeParent.XMaxScale,
                                          "auto", // Y放大步长
                                          this.cbOpmizition.Text,
                                          this.cbProtiy.Text,
                                          (int)this.minContrast.Value);

                    MessageBox.Show("学习模板成功!!!");
                }
                catch (HalconException ex)
                {
                    MessageBox.Show($"识别失败原因:{ex.GetErrorMessage()}");
                }
            }
        }
コード例 #6
0
        /// <summary>
        /// Initializes flags, lists, and delegates to have a valid
        /// starting point to start the assistant.
        /// </summary>
        public MatchingAssistant(MatchingParam parSet)
        {
            parameterSet        = parSet;
            NotifyIconObserver  = new MatchingDelegate(dummy);
            NotifyParamObserver = new AutoParamDelegate(dummyS);
            homSc2D             = new HHomMat2D();
            TestImages          = new Hashtable(10);
            tResult             = new MatchingResult();

            contrastLowB    = 0;
            contrastUpB     = 255;
            scaleStepLowB   = 0.0;
            scaleStepUpB    = (double)19.0 / 1000.0;
            angleStepLowB   = 0.0;
            angleStepUpB    = (double)(112.0 / 10.0) * Math.PI / 180.0;
            pyramLevLowB    = 1;
            pyramLevUpB     = 6;
            minContrastLowB = 0;
            minContrastUpB  = 30;

            findAlways        = false;
            createNewModelID  = true;
            ModelID           = new HShapeModel();
            onExternalModelID = false;
        }
コード例 #7
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);
            }
        }
コード例 #8
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;
        }
コード例 #9
0
        public void CreateModel(HImage Img, HWindow window, HWindow window1, double row1, double col1, double row2, double col2, double rowMark, double colMark)
        {
            HRegion rectangle = new HRegion(row1, col1, row2, col2);

            rectangle.AreaCenter(out rowOrg, out colOrg);
            HImage ImgReduced = new HImage();

            //HRegion Rectangle1 = new HRegion();
            //HRegion Rectangle2 = new HRegion();

            //Window.SetColor("red");
            //Window.SetDraw("margin");
            //Window.SetLineWidth(3);
            //Rectangle.GenRectangle1(188.0, 182, 298, 412);
            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, 0,
                                         0, "none", "use_polarity", 30, 10);
            ShapeModel.SetShapeModelOrigin(rowMark - rowOrg, colMark - colOrg);

            //window.SetColor("green");
            //window.SetDraw("margin");
            window.SetPart((int)row1, (int)col1, (int)row2, (int)col2);
            ModelRegion.DispObj(window);
            window1.SetPart((int)row1, (int)col1, (int)row2, (int)col2);
            ImgReduced.DispImage(window1);
            //Window.SetColor("blue");
            //Window.SetDraw("margin");
            //Rectangle1.DispObj(Window);
            //Rectangle2.DispObj(Window);
        }
コード例 #10
0
 public ShapeModelFinder(HShapeModel model, IHActor next)
     : base(next, true)
 {
     if (model == null)
     {
         throw new ArgumentNullException();
     }
     sbm = model;
 }
コード例 #11
0
        public bool CreateShapeModelAct(HImage modelImage)
        {
            if (modelImage == null || !modelImage.IsInitialized())
            {
                return(false);
            }
            this.modelImage = modelImage;

            if (modelRegion == null || !modelRegion.IsInitialized())
            {
                return(false);
            }
            try
            {
                HImage ROIImage = new HImage();
                ROIImage.GenEmptyObj();
                ROIImage = modelImage.ReduceDomain(modelRegion);
                HImage temp = ROIImage.GaussFilter(7);
                ROIImage.Dispose();
                ROIImage    = temp;
                hShapeModel = ROIImage.CreateScaledShapeModel(
                    new HTuple(numLevels),
                    angleStart, angleExtent, new HTuple(angleStep),
                    scaleMin, scaleMax, new HTuple(scaleStep),
                    new HTuple(optimization).TupleConcat("no_pregeneration"),
                    metric,
                    ((new HTuple(contrastLow)).TupleConcat(contrastHigh)).TupleConcat(minLength),
                    new HTuple(minContrast));



                ROIImage.Dispose();
                double row, col;
                modelRegion.AreaCenter(out row, out col);
                refCoordinates   = new HTuple(row, col, 0);
                createNewModelID = false;
                //初始化modelContours
                if (modelXLDCont == null)
                {
                    modelXLDCont = new HXLDCont();
                }
                if (modelXLDCont != null && modelXLDCont.IsInitialized())
                {
                    modelXLDCont.Dispose();
                }
                modelXLDCont = hShapeModel.GetShapeModelContours(1);
            }
            catch
            {
                hShapeModel      = null;
                createNewModelID = true;
                return(false);
            }

            return(true);
        }
コード例 #12
0
        public override HMessage ActorTask(HMessage obj)
        {
            HTuple isempty = msg_queue.GetMessageQueueParam("is_empty");

            if (isempty.I == 0)
            {
                msg_queue.SetMessageQueueParam("flush_queue", 1);
            }
            if (obj != null)
            {
                obj.Dispose();
            }
            HTuple row, column, angle, score;
            HImage img;

            img = imggrabber.GrabImageAsync(-1);
            HRegion roi = new HRegion(ActiveObject);

            HMessage msg = new HMessage();

            msg.SetMessageObj(img, "image");
            Monitor.Enter(lockobj);
            try
            {
                if (sbm != null)
                {
                    sbm.Dispose();
                }
                sbm = new HShapeModel(img.ReduceDomain(roi), "auto", -Math.PI,
                                      2 * Math.PI, "auto", "auto", "use_polarity", "auto", "auto");

                sbm.FindShapeModel(img, 0.0, 0.0, 0.5, 1, 0.5, "least_squares", 0, 0.9,
                                   out row, out column, out angle, out score);
                if (row.Length > 0)
                {
                    HXLDCont  contours = sbm.GetShapeModelContours(1);
                    HHomMat2D homMat2D = new HHomMat2D();
                    homMat2D.VectorAngleToRigid(0.0, 0.0, 0.0, row.D, column.D, angle.D);
                    HXLDCont projcont = homMat2D.AffineTransContourXld(contours);
                    msg.SetMessageObj(projcont, "contour");
                }
                else
                {
                    sbm.Dispose();
                    sbm = null;
                }
            }
            finally
            {
                Monitor.Exit(lockobj);
            }
            return(msg);
        }
コード例 #13
0
ファイル: ShapeModel.cs プロジェクト: wb2856385025/Simulation
        public bool CreateModel()
        {
            try
            {
                if (ModelRegion == null || ModelRegion.IsInitialized() == false)
                {
                    return(false);
                }

                HImage modelImage = ModelImg.ReduceDomain(ModelRegion);

                HTuple contrast = "auto";
                if (!shapeParam.IsAuto(ShapeParam.AUTO_CONTRAST))
                {
                    contrast = shapeParam.mContrast;
                }

                HShapeModel model = new HShapeModel(modelImage,
                                                    (HTuple)shapeParam.mNumLevel,
                                                    (HTuple)shapeParam.mStartingAngle,
                                                    (HTuple)shapeParam.mAngleExtent,
                                                    (HTuple)shapeParam.mAngleStep,
                                                    (HTuple)shapeParam.mMinScale,
                                                    (HTuple)shapeParam.mMaxScale,
                                                    (HTuple)shapeParam.mScaleStep,
                                                    (HTuple)shapeParam.mOptimization,
                                                    (HTuple)shapeParam.mMetric,
                                                    (HTuple)contrast,
                                                    (HTuple)shapeParam.mMinContrast);
                modelImage.Dispose();

                if (shapeModel != null)
                {
                    shapeModel.Dispose();
                    shapeModel = null;
                }
                shapeModel = model;
                SetModelOrigin(ModelImgRow, ModelImgCol);

                if (TimeOutEnable)
                {
                    shapeModel.SetShapeModelParam("timeout", OutTime);
                }

                createNewModelID = false;
                return(true);
            }
            catch
            {
                return(false);
            }
        }
コード例 #14
0
ファイル: ShapeModel.cs プロジェクト: wb2856385025/Simulation
        public void ReadHalconObj(string fileName)
        {
            if (File.Exists(fileName + ".ncm"))
            {
                if (shapeModel != null)
                {
                    shapeModel.Dispose();
                }

                shapeModel = new HShapeModel(fileName + ".shm");
            }

            if (File.Exists(fileName + "se.tif"))
            {
                if (SearchRegion != null)
                {
                    SearchRegion.Dispose();
                }
                SearchRegion = new HRegion();
                SearchRegion.ReadRegion(fileName + "se.tif");
            }

            if (File.Exists(fileName + "md.tif"))
            {
                if (ModelRegion != null)
                {
                    ModelRegion.Dispose();
                }
                ModelRegion = new HRegion();
                ModelRegion.ReadRegion(fileName + "md.tif");
            }

            if (File.Exists(fileName + ".bmp"))
            {
                if (ModelImg != null)
                {
                    ModelImg.Dispose();
                }
                ModelImg = new HImage(fileName + ".bmp");
            }

            ModelImgRow   = Convert.ToSingle(IniFileOperate.INIGetStringValue(fileName, "参数", "ModelImgRow", ModelImgRow.ToString()));
            ModelImgCol   = Convert.ToSingle(IniFileOperate.INIGetStringValue(fileName, "参数", "ModelImgCol", ModelImgCol.ToString()));
            ModelimgAng   = Convert.ToSingle(IniFileOperate.INIGetStringValue(fileName, "参数", "ModelimgAng", ModelimgAng.ToString()));
            TimeOutEnable = Convert.ToBoolean(IniFileOperate.INIGetStringValue(fileName, "参数", "TimeOutEnable", TimeOutEnable.ToString()));
            OutTime       = Convert.ToInt32(IniFileOperate.INIGetStringValue(fileName, "参数", "OutTime", OutTime.ToString()));
            shapeParam.ReadParam(fileName + "par.dat");


            SetOutTime(TimeOutEnable ? 0 : OutTime);
        }
コード例 #15
0
 public ShapeMatchTool(IToolInfo info, DisplayControl window)
 {
     this.Info     = info;
     this.Window   = window;
     this.ToolName = info.ToolName;
     try
     {
         ShapeModel = new HShapeModel();
         ShapeModel = ReadModelFromFile(info.ToolName);
         ModelXLD   = ShapeModel.GetShapeModelContours(1);
     }
     catch (Exception e)
     {
         ShapeModel = null;
         WriteErrorLog("VisionTool", e.ToString());
     }
 }
コード例 #16
0
 private void bOK_Click(object sender, EventArgs e)
 {
     if (this.ShapeModel != null)
     {
         try
         {
             this.DeParent.ModelAngle = double.Parse(this.lAngle.Text.Split(':')[1]);
             this.DeParent.ShapeModel = this.ShapeModel.Clone();
             this.DialogResult        = DialogResult.Yes;
         }
         catch { }
     }
     else
     {
         this.DialogResult = DialogResult.No;
     }
 }
コード例 #17
0
        public void Reset()
        {
            shapeModelROIList = new List <ROI>();

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

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

            refCoordinates = new HTuple();
        }
コード例 #18
0
ファイル: Form1.cs プロジェクト: Askerer/HalconExamples
        private void buttonRun_Click(object sender, EventArgs e)
        {
            createsbm.Stop();
            HShapeModel sbm = createsbm.GetShapeModel;

            if (sbm == null)
            {
                MessageBox.Show("You need to define a valid shape model first",
                                "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                createsbm.Start();
                return;
            }
            findsbm.ShapeModel = sbm;
            halconWindow.HalconWindow.DetachDrawingObjectFromWindow(roi_object);
            buttonStop.Enabled = true;
            buttonRun.Enabled  = false;
            findsbm.Start();
            imggrabber.Start();
        }
コード例 #19
0
        private HShapeModel ReadModelFromFile(string toolName)
        {
            HShapeModel model = new HShapeModel();;

            try
            {
                if (File.Exists(@".//ModelMatchFile/" + toolName + ".shm"))
                {
                    model.ReadShapeModel(@".//ModelMatchFile/" + info.ToolName + ".shm");
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception)
            {
                WriteErrorLog("VisionTool", "模板读取失败");
            }
            return(model);
        }
コード例 #20
0
        /// <summary>
        /// Creates the shape-based model. If the region of interest
        /// <c>mROIModel</c> is missing or not well defined using the
        /// interactive ROIs, then an error message is returned.
        /// </summary>
        public bool createShapeModel()
        {
            if (mImage == null)
            {
                if (!onTimer)
                {
                    NotifyIconObserver(MatchingAssistant.ERR_NO_MODEL_DEFINED);
                }
                return(false);
            }

            try
            {
                ModelID = mImage.CreateScaledShapeModel(parameterSet.mNumLevel,
                                                        parameterSet.mStartingAngle,
                                                        parameterSet.mAngleExtent,
                                                        parameterSet.mAngleStep,
                                                        parameterSet.mMinScale,
                                                        parameterSet.mMaxScale,
                                                        parameterSet.mScaleStep,
                                                        parameterSet.mOptimization,
                                                        parameterSet.mMetric,
                                                        parameterSet.mContrast,
                                                        parameterSet.mMinContrast);
            }
            catch (HOperatorException e)
            {
                if (!onTimer)
                {
                    exceptionText = e.Message;
                    NotifyParamObserver(MatchingParam.H_ERR_MESSAGE);
                }
                return(false);
            }

            tResult.mContour = ModelID.GetShapeModelContours(1);

            createNewModelID = false;
            return(true);
        }
コード例 #21
0
        // Training of the shape model and write the serialized item to a file
        // stream
        private void CreateBtn_Click(object sender, System.EventArgs e)
        {
            HTuple      Names;
            HRegion     Coin;
            HShapeModel Model;

            TrainBtn.Enabled = false;
            Window.SetColor("red");
            Window.SetDraw("margin");
            Window.SetLineWidth(1);

            Names = "german";
            Names.Append("italian");
            Names.Append("greek");
            Names.Append("spanish");

            //Write a serialized item of type tuple to a file
            Stream s = File.OpenWrite("serialized_shape_model");

            Names.Serialize(s);

            // Note: The binary layout of serialized HALCON objects is determined by
            // the native HALCON libary. You could also package this blob together with
            // other .NET objects into a formatted stream, e.g. by using
            //
            // BinaryFormatter f = new BinaryFormatter();
            // f.Serialize(s, Names);
            //
            // When using only HALCON objects without extra formatting, the streamed
            // data is interchangable with HDevelop or HALCON/C++.

            //Train shape models
            for (int i = 0; i < 4; i++)
            {
                MatchingLabel.Text = "Train coin " + (i + 1) + "/4 (" + Names[i] +
                                     ") and serialize resulting shape model to a" +
                                     " file...";
                MatchingLabel.Refresh();
                Img = new HImage("coins/20cent_" + Names[i]);

                Window.DispObj(Img);

                HRegion Region           = Img.Threshold(70.0, 255.0);
                HRegion ConnectedRegions = Region.Connection();
                HRegion SelectedRegions  = ConnectedRegions.SelectShapeStd("max_area", 0);
                HRegion RegionTrans      = SelectedRegions.ShapeTrans("convex");
                Coin = new HRegion(RegionTrans.Row, RegionTrans.Column, 120);
                int    Contrast = 20;
                HTuple HysteresisContrast;
                HysteresisContrast = (Contrast / 2.0);
                HysteresisContrast.Append(Contrast + 6.0);
                HysteresisContrast.Append(10.0);
                HImage ImgReduced = Img.ReduceDomain(Coin);
                //Called during the test phase to see if contrast is selected correctly
                Model = new HShapeModel(ImgReduced, new HTuple(0), 0.0,
                                        new HTuple(360.0).TupleRad(), new HTuple(0),
                                        new HTuple("no_pregeneration"), "ignore_local_polarity",
                                        HysteresisContrast, new HTuple(5));

                //Write a serialized item of type shape based model to a file
                Model.Serialize(s);

                // Destroy shape based model and objects
                Coin.Dispose();
                Model.Dispose();
                Img.Dispose();
                ImgReduced.Dispose();
                Region.Dispose();
                SelectedRegions.Dispose();
                RegionTrans.Dispose();
                ImgReduced.Dispose();

                HSystem.WaitSeconds(0.4);
            }

            s.Close();

            MatchingLabel.Text = "Ready to find coins";

            StopBtn.Enabled  = false;
            StartBtn.Enabled = true;
        }
コード例 #22
0
 public ShapeModelFinder(IHActor next) : base(next, true)
 {
     sbm = null;
 }
コード例 #23
0
        /// <summary>
        /// Creates the shape-based model. If the region of interest
        /// <c>mROIModel</c> is missing or not well defined using the
        /// interactive ROIs, then an error message is returned.
        /// </summary>
        public bool createShapeModel(string filePath)
        {
            bool isSuccess = false;

            if (mReducedImage == null)
            {
                if (!onTimer)
                {
                    NotifyIconObserver(MatchingAssistant.ERR_NO_MODEL_DEFINED);
                }
                return(false);
            }

            try
            {
                parameterSet.mMetric = "ignore_local_polarity";
                //parameterSet.mOptimization = "auto";
                //parameterSet.mAngleStep = "auto";
                mReducedImage.WriteImage("bmp", 0, filePath + "template.bmp");
                if (ModelID != null)
                {
                    ModelID.Dispose();
                }
                ModelID = mReducedImage.CreateShapeModel(
                    parameterSet.mNumLevel,
                    parameterSet.mStartingAngle,
                    parameterSet.mAngleExtent,
                    0.0175 / 10,
                    "auto",//parameterSet.mOptimization,
                    parameterSet.mMetric,
                    "auto_contrast",
                    "auto"
                    );

                if (GrayTemplate != null)
                {
                    GrayTemplate.Dispose();
                }
                GrayTemplate = mReducedImage.CreateTemplate(255, parameterSet.mNumLevel, "none", "original");
                isSuccess    = true;
            }
            catch (HOperatorException e)
            {
                isSuccess = false;
                if (!onTimer)
                {
                    exceptionText = e.Message;
                    NotifyParamObserver(MatchingParam.H_ERR_MESSAGE);
                }
                return(false);
            }

            if (tResult.mContour != null)
            {
                tResult.mContour.Dispose();
            }
            tResult.mContour = ModelID.GetShapeModelContours(1);

            createNewModelID = false;
            return(isSuccess);
        }
コード例 #24
0
 public HXLDCont CreateShapeModel(HRegion modelRegion, HImage img, ModelParameter modelParameter, out HShapeModel model)
 {
     return(CreateShapeModel(img.ReduceDomain(modelRegion), modelParameter, out model));
 }
コード例 #25
0
        public HXLDCont FindShapeModel(HImage img,
                                       HShapeModel model,
                                       FindModelParameter findModelParameter,
                                       out HTuple row,
                                       out HTuple column,
                                       out HTuple angle,
                                       out HTuple scale,
                                       out HTuple score)
        {
            var t1 = HSystem.CountSeconds();

            model.SetShapeModelParam("timeout", 10000);
            try
            {
                img.FindScaledShapeModel(
                    model,
                    findModelParameter.angleStart,
                    findModelParameter.angleExtent,
                    findModelParameter.scaleMin,
                    findModelParameter.scaleMax,
                    findModelParameter.minScore,
                    findModelParameter.numMatches,
                    findModelParameter.maxOverlap,
                    findModelParameter.subPixel,
                    findModelParameter.numLevels,
                    findModelParameter.greediness,
                    out row,
                    out column,
                    out angle,
                    out scale,
                    out score);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                row                   =
                    column            =
                        angle         =
                            scale     =
                                score = new HTuple();
            }

            var t2    = HSystem.CountSeconds();
            var mTime = 1000.0 * (t2 - t1);

            System.Diagnostics.Debug.WriteLine(mTime.ToString());

            var modelContours = Model.GetShapeModelContours(1);
            var homMat2D      = new HHomMat2D();

            //HTuple Width, Height;
            //Img.GetImageSize(out Width, out Height);

            if (score.Length <= 0)
            {
                return(null);
            }
            homMat2D.VectorAngleToRigid(0, 0, 0, row, column, angle);

            var contoursAffinTrans = modelContours.AffineTransContourXld(homMat2D);

            return(contoursAffinTrans);
        }
コード例 #26
0
        /// <summary>
        /// Initializes flags, lists, and delegates to have a valid
        /// starting point to start the assistant.
        /// </summary>
        public MatchingAssistant(MatchingParam  parSet)
        {
            parameterSet	= parSet;
            NotifyIconObserver  = new MatchingDelegate(dummy);
            NotifyParamObserver = new AutoParamDelegate(dummyS);
            homSc2D    = new HHomMat2D();
            TestImages = new Hashtable(10);
            tResult	   = new MatchingResult();

            contrastLowB	= 0;
            contrastUpB		= 255;
            scaleStepLowB	= 0.0;
            scaleStepUpB	= (double)19.0/1000.0;
            angleStepLowB	= 0.0;
            angleStepUpB	= (double)(112.0/10.0)*Math.PI/180.0;
            pyramLevLowB	= 1;
            pyramLevUpB		= 6;
            minContrastLowB = 0;
            minContrastUpB	= 30;

            findAlways		 = false;
            createNewModelID = true;
            ModelID			  = new HShapeModel();
            onExternalModelID = false;
        }
コード例 #27
0
        /// <summary>
        /// Creates the shape-based model. If the region of interest 
        /// <c>mROIModel</c> is missing or not well defined using the 
        /// interactive ROIs, then an error message is returned.
        /// </summary>
        public bool createShapeModel()
        {
            if(mImage==null)
            {
                if(!onTimer)
                    NotifyIconObserver(MatchingAssistant.ERR_NO_MODEL_DEFINED);
                return false;
            }

            try
            {
                ModelID = mImage.CreateScaledShapeModel(parameterSet.mNumLevel,
                                                        parameterSet.mStartingAngle,
                                                        parameterSet.mAngleExtent,
                                                        parameterSet.mAngleStep,
                                                        parameterSet.mMinScale,
                                                        parameterSet.mMaxScale,
                                                        parameterSet.mScaleStep,
                                                        parameterSet.mOptimization,
                                                        parameterSet.mMetric,
                                                        parameterSet.mContrast,
                                                        parameterSet.mMinContrast);
            }
            catch(HOperatorException e)
            {

                if(!onTimer)
                {
                    exceptionText = e.Message;
                    NotifyParamObserver(MatchingParam.H_ERR_MESSAGE);
                }
                return false;
            }

            tResult.mContour = ModelID.GetShapeModelContours(1);

            createNewModelID = false;
            return true;
        }
コード例 #28
0
        // Procedure to find the coins and to read the serialized item from a
        // file stream
        private void Action()
        {
            HRegion Coin, Circle;
            HTuple  Row, Column, Angle, Score, ResultModel;

            if (ImgNum == 0)
            {
                MatchingLabel.Text = "Deserialize shape models...";
                MatchingLabel.Refresh();
                //Reading names
                Stream s = File.OpenRead("serialized_shape_model");
                Names = HTuple.Deserialize(s);
                //Reading shape models
                for (int i = 0; i < 4; i++)
                {
                    Models[i] = HShapeModel.Deserialize(s);
                }
                s.Close();
                MatchingLabel.Text = "Deserialize shape models... OK";
                MatchingLabel.Refresh();
            }

            if (ImgNum == 13)
            {
                ImgNum = 0;
            }
            HTuple Zero;

            if (ImgNum + 1 < 10)
            {
                Zero = "0";
            }
            else
            {
                Zero = "";
            }

            //Find shape based model using the read models
            Img.ReadImage("coins/20cent_" + Zero + (ImgNum + 1).ToString() + ".png");
            ImgNum++;

            HRegion Region           = Img.Threshold(70.0, 255.0);
            HRegion ConnectedRegions = Region.Connection();
            HRegion SelectedRegions  = ConnectedRegions.SelectShapeStd("max_area", 0);
            HRegion RegionTrans      = SelectedRegions.ShapeTrans("convex");

            Coin   = new HRegion(RegionTrans.Row, RegionTrans.Column, 120);
            Circle = new HRegion(Coin.Row, Coin.Column, 35);
            HImage ImgReduced = Img.ReduceDomain(Circle);

            ImgReduced.FindShapeModels(Models, 0.0, new HTuple(360.0).TupleRad(),
                                       0.6, 1, 0, "interpolation", 0, 0.9,
                                       out Row, out Column, out Angle, out Score,
                                       out ResultModel);

            HXLDCont  ModelContours = Models[ResultModel.I].GetShapeModelContours(1);
            HHomMat2D HomMat2D      = new HHomMat2D();

            Window.SetColor("green");

            HomMat2D.VectorAngleToRigid(0, 0, 0, Row, Column, Angle);
            HXLDCont ContoursAffineTrans = ModelContours.AffineTransContourXld(HomMat2D);

            HSystem.SetSystem("flush_graphic", "false");
            Window.DispObj(Img);
            HSystem.SetSystem("flush_graphic", "true");
            Window.DispObj(ContoursAffineTrans);

            MatchingLabel.Text = "#" + (ImgNum + 1) + ": Found: " +
                                 Names[ResultModel.I] + " coin";
        }
コード例 #29
0
        public bool CreateMatchTool()
        {
            HImage  modelImage  = null;
            HRegion modelRegion = null;

            if (info.ModelROIParam.GetType() == typeof(CircleParam))
            {
                CircleParam circle = info.ModelROIParam as CircleParam;
                if (circle != null)
                {
                    modelImage = GetModelImageByCircle(Image.CopyImage(), circle.CircleRow, circle.CircleColumn, circle.Radius, out modelRegion);
                }
            }
            else if (info.ModelROIParam.GetType() == typeof(Rectangle1Param))
            {
                Rectangle1Param rectangle1 = info.ModelROIParam as Rectangle1Param;
                if (rectangle1 != null)
                {
                    modelImage = GetModelImageByRectangle1(Image.CopyImage(), rectangle1.RectangleStartRow, rectangle1.RectangleStartColumn, rectangle1.RectangleEndRow, rectangle1.RectangleEndColumn, out modelRegion);
                }
            }
            else if (info.ModelROIParam.GetType() == typeof(Rectangle2Param))
            {
                Rectangle2Param rectangle2 = info.ModelROIParam as Rectangle2Param;
                if (rectangle2 != null)
                {
                    modelImage = GetModelImageByRectangle2(Image.CopyImage(), rectangle2.Rectangle2CenterRow, rectangle2.Retangle2CenterColumn, rectangle2.Retangle2Angle, rectangle2.Rectangle2Length1, rectangle2.Rectangle2Length2, out modelRegion);
                }
            }
            else if (info.ModelROIParam.GetType() == typeof(EllipseParam))
            {
                EllipseParam ellipse = info.ModelROIParam as EllipseParam;
                if (ellipse != null)
                {
                    modelImage = GetModelImageByEllipse(Image.CopyImage(), ellipse.EllipseCenterRow, ellipse.EllipseCenterColumn, ellipse.EllipseAngle, ellipse.EllipseRadius1, ellipse.EllipseRadius2, out modelRegion);
                }
            }
            else
            {
                WriteErrorLog("VisionTool", info.ToolName + "模板创建失败");
                return(false);
            }
            HShapeModel shapeScaleModel = new HShapeModel();
            double      modelRow, modelCol;

            if (modelImage != null)
            {
                try
                {
                    shapeScaleModel.CreateScaledShapeModel(modelImage, new HTuple(info.NumLevels), TransAngle.AngleToHu(info.AngleStart), TransAngle.AngleToHu(info.AngleExtent), new HTuple(info.AngleStep), info.ScaleMin, info.ScaleMax, new HTuple(info.ScaleStep), new HTuple(info._Optimization.ToString()), info._Metric.ToString(), new HTuple(info.Contrast), new HTuple(info.MinContrast));
                    AffineTransModelContour(shapeScaleModel, modelRegion);
                    //record the model coordinate to the setting info.
                    modelRegion.AreaCenter(out modelRow, out modelCol);
                    info.ModelRegionRow   = modelRow;
                    info.ModelRegionCol   = modelCol;
                    info.ModelRegionAngle = 0.0;

                    this.ShapeModel = shapeScaleModel;
                    this.ModelXLD   = shapeScaleModel.GetShapeModelContours(1);
                    SaveModelFile(info.ToolName);
                }
                catch
                {
                    WriteErrorLog("VisionTool", info.ToolName + "模板创建失败");
                    return(false);
                }
            }
            else
            {
                WriteErrorLog("VisionTool", info.ToolName + "模板创建失败");
                return(false);
            }
            return(true);
        }