Exemple #1
0
        public static HRegion GetRegion(this IRectangle2 rect)
        {
            var processRegion = new HRegion();

            processRegion.GenRectangle2(rect.Y, rect.X, rect.Angle, rect.HalfWidth, rect.HalfHeight);
            return(processRegion);
        }
        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;
        }
        /// <summary>
        ///  在图像中绘制矩形区域
        /// </summary>
        /// <param name="row"></param>
        /// <param name="column"></param>
        /// <param name="phi"></param>
        /// <param name="length1"></param>
        /// <param name="length2"></param>
        public void DrawRectangle2(string color, out double row, out double column, out double phi, out double length1, out double length2)
        {
            try
            {
                Double _row, _column, _phi, _length1, _length2;
                ShieldMouseEvent();
                hWindowControl1.Focus();
                hWindowControl1.HalconWindow.SetColor(color);
                hWindowControl1.HalconWindow.DrawRectangle2(out _row, out _column, out _phi, out _length1, out _length2);
                HRegion rectangle = new HRegion();
                rectangle.GenRectangle2(_row, _column, _phi, _length1, _length2);
                rectangle.GenContourRegionXld("border").DispObj(hWindowControl1.HalconWindow);

                //   rectangle.DispObj(hWindowControl1.HalconWindow);
                rectangle.Dispose();
                ReloadMouseEvent();
                row     = _row;
                column  = _column;
                phi     = _phi;
                length1 = _length1;
                length2 = _length2;
            }
            catch (System.Exception ex)
            {
                row                 = 0.0;
                column              = 0.0;
                phi                 = 0.0;
                length1             = 0.0;
                length2             = 0.0;
                status_message.Text = ex.Message;
            }
        }
        /// <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);
        }
Exemple #5
0
        public static HRegion GenRectangle2Region(double row, double col, double angle, double length1, double length2)
        {
            HRegion Rectangle2 = new HRegion();

            Rectangle2.GenEmptyRegion();
            Rectangle2.GenRectangle2(row, col, angle, length1, length2);
            return(Rectangle2);
        }
        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);
        }
Exemple #7
0
        public HRegion Process(HRegion region)
        {
            HTuple row, col, phi, len1, len2;

            region.SmallestRectangle2(out row, out col, out phi, out len1, out len2);
            var smallestRect2 = new HRegion();

            smallestRect2.GenRectangle2(row, col, phi, len1, len2);
            return(smallestRect2);
        }
Exemple #8
0
 public DrawRectangle2(double row, double column, double phi, double length1, double length2)
 {
     Row     = row;
     Colulmn = column;
     Phi     = phi;
     Length1 = length1;
     Length2 = length2;
     ROIType = ROIType.Rectangle2;
     Region  = new HRegion();
     Region.GenRectangle2(Row, Colulmn, Phi, Length1, Length2);
 }
Exemple #9
0
        public static HRegion GenRegion(this IRectangle2 rectangle2)
        {
            var region = new HRegion();

            region.GenRectangle2(
                rectangle2.Y,
                rectangle2.X,
                rectangle2.Angle,
                rectangle2.HalfWidth,
                rectangle2.HalfHeight);
            return(region);
        }
        /// <summary>
        /// Creates an iconic object depicting the
        /// measuring field.
        /// </summary>
        public void UpdateMeasureRegion()
        {
            mMeasureRegion.Dispose();
            mMeasureRegion.GenEmptyObj();
            switch (mROIType)
            {
            case 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();
                break;

            case ROI.ROI_TYPE_CIRCLE:
                //
                break;

            default:
                mMeasureRegion.GenRectangle2(mMeasROI[0].D, mMeasROI[1].D,
                                             mMeasROI[2].D, mMeasROI[3].D,
                                             mMeasROI[4].D);
                break;
            }
        }
        /// <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();
        }
        /// <summary>
        /// 从DataRow数据获取区域
        /// </summary>
        /// <param name="dr">DataRow</param>
        /// <returns>区域</returns>
        public HRegion GetRegion(DataRow dr)
        {
            var type    = dr["Type"] as string;
            var hRegion = new HRegion();

            switch (type)
            {
            case "Ellipse":
                hRegion.GenEllipse((double)dr["Row"], (double)dr["Column"], (double)dr["Phi"], (double)dr["Ra"], (double)dr["Rb"]);
                break;

            case "Rectangle":
                hRegion.GenRectangle2((double)dr["Row"], (double)dr["Column"], (double)dr["Phi"], (double)dr["Ra"], (double)dr["Rb"]);
                break;
            }

            return(hRegion);
        }
Exemple #13
0
        /// <summary>
        /// Finds the white & black pattern area in the calibration document.
        /// </summary>
        /// <param name="image1">The image1.</param>
        /// <returns></returns>
        /// <remarks></remarks>
        public static HImage FindPatternArea(HImage image1)
        {
            HImage reducedImage = new HImage();

            try
            {
                double row;
                double column;
                double phi;
                double length1;
                double length2;

                HRegion regions = image1.Threshold(Properties.Settings.Default.CalibDocumentThresholdMinimumLimit,
                                                   Properties.Settings.Default.CalibDocumentThresholdMaximumLimit);

                int areaOfWhiteRegion = regions.AreaCenter(out row, out column);
                // If the segmented white region does not have the specified area, return from the function
                if (areaOfWhiteRegion < Properties.Settings.Default.CalibDocumentWhiteRegionMinimumArea)
                {
                    return(null);
                }
                regions.SmallestRectangle2(out row, out column, out phi, out length1, out length2);

                HRegion rectangleRegion = new HRegion();
                rectangleRegion.GenRectangle2(row, column, phi, length1, length2);
                reducedImage = image1.ReduceDomain(rectangleRegion);
            }
            catch (Exception ex)
            {
                string errorMessage = "Exception occurred in FindPatternArea. ";

                errorMessage = errorMessage + " Error Message: " + ex.Message;

                MessageBox.Show(errorMessage, "Camera Setup Tool", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            return(reducedImage);
        }
        private void Action()
        {
            double    S1, S2;
            HTuple    RowCheck, ColumnCheck, AngleCheck, Score;
            HHomMat2D Matrix = new HHomMat2D();
            HRegion   ModelRegionTrans;
            HTuple    Rect1RowCheck, Rect1ColCheck;
            HTuple    Rect2RowCheck, Rect2ColCheck;
            HRegion   Rectangle1 = new HRegion();
            HRegion   Rectangle2 = new HRegion();
            HMeasure  Measure1, Measure2;
            HTuple    RowEdgeFirst1, ColumnEdgeFirst1;
            HTuple    AmplitudeFirst1, RowEdgeSecond1;
            HTuple    ColumnEdgeSecond1, AmplitudeSecond1;
            HTuple    IntraDistance1, InterDistance1;
            HTuple    RowEdgeFirst2, ColumnEdgeFirst2;
            HTuple    AmplitudeFirst2, RowEdgeSecond2;
            HTuple    ColumnEdgeSecond2, AmplitudeSecond2;
            HTuple    IntraDistance2, InterDistance2;
            HTuple    MinDistance;
            int       NumLeads;

            HSystem.SetSystem("flush_graphic", "false");
            Img.GrabImage(Framegrabber);
            Img.DispObj(Window);

            // Find the IC in the current image.
            S1 = HSystem.CountSeconds();
            ShapeModel.FindShapeModel(Img, 0,
                                      new HTuple(360).TupleRad().D,
                                      0.7, 1, 0.5, "least_squares",
                                      4, 0.9, out RowCheck, out ColumnCheck,
                                      out AngleCheck, out Score);
            S2 = HSystem.CountSeconds();
            MatchingTimeLabel.Text = "Time: " +
                                     String.Format("{0,4:F1}", (S2 - S1) * 1000) + "ms";
            MatchingScoreLabel.Text = "Score: ";

            if (RowCheck.Length == 1)
            {
                MatchingScoreLabel.Text = "Score: " +
                                          String.Format("{0:F5}", Score.D);
                // Rotate the model for visualization purposes.
                Matrix.VectorAngleToRigid(new HTuple(Row), new HTuple(Column), new HTuple(0.0),
                                          RowCheck, ColumnCheck, AngleCheck);

                ModelRegionTrans = ModelRegion.AffineTransRegion(Matrix, "false");
                Window.SetColor("green");
                Window.SetDraw("fill");
                ModelRegionTrans.DispObj(Window);
                // Compute the parameters of the measurement rectangles.
                Matrix.AffineTransPixel(Rect1Row, Rect1Col,
                                        out Rect1RowCheck, out Rect1ColCheck);
                Matrix.AffineTransPixel(Rect2Row, Rect2Col,
                                        out Rect2RowCheck, out Rect2ColCheck);

                // For visualization purposes, generate the two rectangles as
                // regions and display them.
                Rectangle1.GenRectangle2(Rect1RowCheck.D, Rect1ColCheck.D,
                                         RectPhi + AngleCheck.D,
                                         RectLength1, RectLength2);
                Rectangle2.GenRectangle2(Rect2RowCheck.D, Rect2ColCheck.D,
                                         RectPhi + AngleCheck.D,
                                         RectLength1, RectLength2);
                Window.SetColor("blue");
                Window.SetDraw("margin");
                Rectangle1.DispObj(Window);
                Rectangle2.DispObj(Window);
                // Do the actual measurements.
                S1       = HSystem.CountSeconds();
                Measure1 = new HMeasure(Rect1RowCheck.D, Rect1ColCheck.D,
                                        RectPhi + AngleCheck.D,
                                        RectLength1, RectLength2,
                                        ImgWidth, ImgHeight, "bilinear");
                Measure2 = new HMeasure(Rect2RowCheck.D, Rect2ColCheck.D,
                                        RectPhi + AngleCheck.D,
                                        RectLength1, RectLength2,
                                        ImgWidth, ImgHeight, "bilinear");
                Measure1.MeasurePairs(Img, 2, 90,
                                      "positive", "all",
                                      out RowEdgeFirst1,
                                      out ColumnEdgeFirst1,
                                      out AmplitudeFirst1,
                                      out RowEdgeSecond1,
                                      out ColumnEdgeSecond1,
                                      out AmplitudeSecond1,
                                      out IntraDistance1,
                                      out InterDistance1);
                Measure2.MeasurePairs(Img, 2, 90,
                                      "positive", "all",
                                      out RowEdgeFirst2,
                                      out ColumnEdgeFirst2,
                                      out AmplitudeFirst2,
                                      out RowEdgeSecond2,
                                      out ColumnEdgeSecond2,
                                      out AmplitudeSecond2,
                                      out IntraDistance2,
                                      out InterDistance2);
                S2 = HSystem.CountSeconds();
                MeasureTimeLabel.Text = "Time: " +
                                        String.Format("{0,5:F1}", (S2 - S1) * 1000) + "ms";
                Window.SetColor("red");
                Window.DispLine(RowEdgeFirst1 - RectLength2 * Math.Cos(AngleCheck),
                                ColumnEdgeFirst1 - RectLength2 * Math.Sin(AngleCheck),
                                RowEdgeFirst1 + RectLength2 * Math.Cos(AngleCheck),
                                ColumnEdgeFirst1 + RectLength2 * Math.Sin(AngleCheck));
                Window.DispLine(RowEdgeSecond1 - RectLength2 * Math.Cos(AngleCheck),
                                ColumnEdgeSecond1 - RectLength2 * Math.Sin(AngleCheck),
                                RowEdgeSecond1 + RectLength2 * Math.Cos(AngleCheck),
                                ColumnEdgeSecond1 + RectLength2 * Math.Sin(AngleCheck));
                Window.DispLine(RowEdgeFirst2 - RectLength2 * Math.Cos(AngleCheck),
                                ColumnEdgeFirst2 - RectLength2 * Math.Sin(AngleCheck),
                                RowEdgeFirst2 + RectLength2 * Math.Cos(AngleCheck),
                                ColumnEdgeFirst2 + RectLength2 * Math.Sin(AngleCheck));
                Window.DispLine(RowEdgeSecond2 - RectLength2 * Math.Cos(AngleCheck),
                                ColumnEdgeSecond2 - RectLength2 * Math.Sin(AngleCheck),
                                RowEdgeSecond2 + RectLength2 * Math.Cos(AngleCheck),
                                ColumnEdgeSecond2 + RectLength2 * Math.Sin(AngleCheck));
                NumLeads             = IntraDistance1.Length + IntraDistance2.Length;
                MeasureNumLabel.Text = "Number of leads: " +
                                       String.Format("{0:D2}", NumLeads);
                MinDistance           = InterDistance1.TupleConcat(InterDistance2).TupleMin();
                MeasureDistLabel.Text = "Minimum lead distance: " +
                                        String.Format("{0:F3}", MinDistance.D);
                HSystem.SetSystem("flush_graphic", "true");
                // Force the graphics window update by displaying an offscreen pixel
                Window.DispLine(-1.0, -1.0, -1.0, -1.0);
            }
        }
 /// <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;
 }
        /// <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();
        }
        /// <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();
        }
Exemple #18
0
        private double FindPositionBottle(HImage Image, DataType.AlgoritmoControlloLivelloParam param, bool useIconic, ref ArrayList iconicList)
        {
            double columnCenter = 0;

            HMeasure MeasureHandle = null;
            HImage   ImgEmfatize   = null;

            try
            {
                double Rowstart, Rowend, Colstart, Colend;
                int    Width, Height;
                Image.GetImageSize(out Width, out Height);

                Rowstart = 0.0;
                Rowend   = Height;
                Colstart = Width / 2;
                Colend   = Width / 2;

                if (useIconic)
                {
                    iconicList.Add(new Utilities.ObjectToDisplay("Line", new HTuple(Rowstart, Colstart, Rowend, Colend), "red", 1));
                }

                param.RectCentraggio.Column = Width / 2;

                if (useIconic)
                {
                    // genero i due rettangoli per la misura dell'inclinazione bottiglia
                    // solo per visualizzazione
                    HRegion rectangleCentraggio = new HRegion();
                    rectangleCentraggio.GenRectangle2(param.RectCentraggio.Row, Width / 2, 0, param.RectCentraggio.Length1, param.RectCentraggio.Length2);
                    iconicList.Add(new Utilities.ObjectToDisplay(rectangleCentraggio, "red", 1));
                }

                // Determine all edge pairs that have a negative transition, i.e., edge pairs that enclose dark regions.
                const string Interpolation = "nearest_neighbor";
                HTuple       RowEdge_first, ColumnEdge_first, Amplitude_first, Distance_first;
                HTuple       RowEdge_last, ColumnEdge_last, Amplitude_last, Distance_last;

                ImgEmfatize = Image.Emphasize(7, 7, param.EmphasizeFactorx10 / 10.0);

                // Misura degli edge sul primo rettangolo
                MeasureHandle = new HMeasure(param.RectCentraggio.Row, Width / 2, 0, param.RectCentraggio.Length1, param.RectCentraggio.Length2, Width, Height, Interpolation);
                MeasureHandle.MeasurePos(ImgEmfatize, param.Sigmax10 / 10.0, param.Thresholdx10 / 10.0, "all", "first", out RowEdge_first, out ColumnEdge_first, out Amplitude_first, out Distance_first);
                MeasureHandle.Dispose();        // Libera lo spazio associato a 'MeasureHandle'

                MeasureHandle = new HMeasure(param.RectCentraggio.Row, Width / 2, Math.PI, param.RectCentraggio.Length1, param.RectCentraggio.Length2, Width, Height, Interpolation);
                MeasureHandle.MeasurePos(ImgEmfatize, param.Sigmax10 / 10.0, param.Thresholdx10 / 10.0, "all", "first", out RowEdge_last, out ColumnEdge_last, out Amplitude_last, out Distance_last);
                MeasureHandle.Dispose();        // Libera lo spazio associato a 'MeasureHandle'

                if (RowEdge_first.Length == 1 && RowEdge_last.Length == 1 && ColumnEdge_first.Length == 1 && ColumnEdge_last.Length == 1)
                {
                    columnCenter = (ColumnEdge_last.D + ColumnEdge_first.D) / 2;

                    if (useIconic)
                    {
                        iconicList.Add(new Utilities.ObjectToDisplay("Cross", new HTuple(RowEdge_first.D, ColumnEdge_first.D, 15, Math.PI / 4), "magenta", 1));
                        iconicList.Add(new Utilities.ObjectToDisplay("Cross", new HTuple(RowEdge_last.D, ColumnEdge_last.D, 15, Math.PI / 4), "magenta", 1));
                        iconicList.Add(new Utilities.ObjectToDisplay("Cross", new HTuple(RowEdge_last.D, columnCenter, 15, Math.PI / 4), "green", 1));
                    }
                }
                else
                {
                    columnCenter = Width / 2;
                }
            }
            catch (Exception)
            {
                columnCenter = 0;
            }
            finally
            {
                if (MeasureHandle != null)
                {
                    MeasureHandle.Dispose();
                }
                if (ImgEmfatize != null)
                {
                    ImgEmfatize.Dispose();
                }
            }

            return(columnCenter);
        }
Exemple #19
0
        private bool AnalisiLivello(HImage Img, DataType.AlgoritmoControlloLivelloParam param, double centerColumn, bool regolazioni, out bool errorLevelMin, out bool errorLevelMax, out bool errorEmpty, ref ArrayList iconicList)
        {
            bool ret = false;


            errorLevelMin = false;
            errorLevelMax = false;
            errorEmpty    = false;


            int Width, Height;

            Img.GetImageSize(out Width, out Height);

            const string Interpolation = "nearest_neighbor";
            string       Transition    = param.LiquidoChiaro ? "negative" : "positive";
            const string Select        = "first";
            const double delta         = 30.0;

            // Disegna la regione per il calcolo del Livello
            HRegion Rectangle = new HRegion();

            Rectangle.GenRectangle2(param.RectLivello.Row, centerColumn, param.RectLivello.Angle, param.RectLivello.Length1, param.RectLivello.Length2);

            HMeasure MeasureHandle = new HMeasure(param.RectLivello.Row, centerColumn, param.RectLivello.Angle, param.RectLivello.Length1, param.RectLivello.Length2, Width, Height, Interpolation);

            HTuple RowEdge, ColumnEdge, Amplitude, Distance;

            Img.MeasurePos(MeasureHandle, param.SigmaLivellox10 / 10.0, param.ThresholdLivellox10 / 10.0, Transition, Select, out RowEdge, out ColumnEdge, out Amplitude, out Distance);

            MeasureHandle.Dispose();

            if (RowEdge.Length > 0)
            {
                double altezzaSchiuma = RowEdge.D;

                if (altezzaSchiuma >= param.RowMaxLivello && altezzaSchiuma <= param.RowMinLivello)
                {
                    if (param.LiquidoChiaro)
                    {
                        ret = true;
                    }
                    else
                    {
                        HRegion rectangleThreshold = new HRegion();
                        //double row = altezzaSchiuma + (paramLevel.rowMin - altezzaSchiuma) / 2;
                        double row    = altezzaSchiuma + (param.RectLivello.Row + param.RectLivello.Length1 - altezzaSchiuma) / 2;
                        double column = centerColumn;
                        //double length1 = (paramLevel.rowMin - altezzaSchiuma) / 2;
                        double length1 = (param.RectLivello.Row + param.RectLivello.Length1 - altezzaSchiuma) / 2;
                        double length2 = param.RectLivello.Length2;

                        rectangleThreshold.GenRectangle2(row, column, param.RectLivello.Angle, length1, length2);

                        HImage  imgReduced      = Img.ReduceDomain(rectangleThreshold);
                        HRegion regionThreshold = imgReduced.Threshold((double)param.ThresholdMin, (double)param.ThresholdMax);
                        imgReduced.Dispose();

                        double r, c;
                        int    area = rectangleThreshold.AreaCenter(out r, out c);
                        rectangleThreshold.Dispose();

                        HRegion regionSelect = regionThreshold.SelectShape("area", "and", area * 0.7, double.MaxValue);
                        regionThreshold.Dispose();

                        ret = regionSelect.CountObj() == 1;
                        iconicList.Add(new Utilities.ObjectToDisplay(regionSelect, "blue", 3)
                        {
                            DrawMode = "fill"
                        });
                    }
                }
                else if (altezzaSchiuma < param.RowMaxLivello)
                {
                    errorLevelMax = true;
                }
                else if (altezzaSchiuma > param.RowMinLivello)
                {
                    errorLevelMin = true;
                }

                iconicList.Add(new Utilities.ObjectToDisplay("Line", new HTuple(altezzaSchiuma, centerColumn - delta, altezzaSchiuma, centerColumn + delta), ret ? "green" : "red", 3));
            }
            else
            {
                if (param.UseThreshold)
                {
                    if (param.LiquidoChiaro)
                    {
                        HRegion rectangleThreshold = new HRegion();
                        rectangleThreshold.GenRectangle2(param.QuotaControlloVuoto, centerColumn, 0.0, param.LarghezzaControlloVuoto, 20);

                        HImage imgReduced = Img.ReduceDomain(rectangleThreshold);
                        rectangleThreshold.Dispose();

                        HRegion regionThreshold = imgReduced.Threshold((double)param.ThresholdMin, (double)param.ThresholdMax);
                        imgReduced.Dispose();

                        HRegion connectedRegions = regionThreshold.Connection();
                        regionThreshold.Dispose();

                        HRegion filledCandidates = connectedRegions.FillUp();
                        connectedRegions.Dispose();

                        HRegion regionMax = filledCandidates.SelectShapeStd("max_area", 0);

                        double row, col;
                        int    area = regionMax.AreaCenter(out row, out col);
                        regionMax.Dispose();

                        if (area > param.SogliaAreaControlloVuoto)
                        {
                            iconicList.Add(new Utilities.ObjectToDisplay(filledCandidates, "green", 1)
                            {
                                DrawMode = "fill"
                            });
                            ret = true;
                        }
                        else
                        {
                            iconicList.Add(new Utilities.ObjectToDisplay(filledCandidates, "red", 1)
                            {
                                DrawMode = "fill"
                            });
                            ret = false;
                        }

                        iconicList.Add(new Utilities.ObjectToDisplay(area.ToString(), "blue", (int)(row - 50), (int)(col - param.LarghezzaControlloVuoto)));
                    }
                    else
                    {
                        HRegion rectangleThreshold = new HRegion();
                        rectangleThreshold.GenRectangle2(param.RowMaxLivello + (param.RowMinLivello - param.RowMaxLivello) / 2
                                                         , centerColumn
                                                         , param.RectLivello.Angle
                                                         , (param.RowMinLivello - param.RowMaxLivello) / 2
                                                         , param.RectLivello.Length2);

                        HImage  imgReduced      = Img.ReduceDomain(rectangleThreshold);
                        HRegion regionThreshold = imgReduced.Threshold((double)param.ThresholdMin, (double)param.ThresholdMax);
                        imgReduced.Dispose();

                        double r, c;
                        int    area = rectangleThreshold.AreaCenter(out r, out c);

                        HRegion regionSelect = regionThreshold.SelectShape("area", "and", area * 0.7, double.MaxValue);

                        ret = regionSelect.CountObj() == 1;
                        regionSelect.Dispose();

                        iconicList.Add(new Utilities.ObjectToDisplay(rectangleThreshold, "red", 1));
                        iconicList.Add(new Utilities.ObjectToDisplay(regionThreshold, "red", 1)
                        {
                            DrawMode = "fill"
                        });
                    }

                    if (ret == false)
                    {
                        errorEmpty = true;
                    }
                }
            }

            iconicList.Add(new Utilities.ObjectToDisplay(Rectangle, "red", 2));

            iconicList.Add(new Utilities.ObjectToDisplay("Line", new HTuple(param.RowMaxLivello, centerColumn - delta, param.RowMaxLivello, centerColumn + delta), "cyan", 3));
            iconicList.Add(new Utilities.ObjectToDisplay("Max", "cyan", (int)(param.RowMaxLivello - delta), (int)(centerColumn + 2 * delta)));

            iconicList.Add(new Utilities.ObjectToDisplay("Line", new HTuple(param.RowMinLivello, centerColumn - delta, param.RowMinLivello, centerColumn + delta), "cyan", 3));
            iconicList.Add(new Utilities.ObjectToDisplay("Min", "cyan", (int)(param.RowMinLivello), (int)(centerColumn + 2 * delta)));

            return(ret);
        }
        private void DefineMat2Ds()
        {
            if (mat2Ds == null)
            {
                mat2Ds = new List <HHomMat2D>();
            }
            else
            {
                mat2Ds.Clear();
            }
            for (int i = 0; i < row_temp.Length; i++)
            {
                HHomMat2D homMat2D = new HHomMat2D();
                homMat2D.VectorAngleToRigid(
                    createShapeModel.refCoordinates[0].D, createShapeModel.refCoordinates[1].D, createShapeModel.refCoordinates[2].D,
                    row_temp[i].D, column_temp[i].D, angle_temp[i].D);
                HRegion boundary_region;
                if (SearchRegion == null | !SearchRegion.IsInitialized())
                {
                    boundary_region = refImage.GetDomain().Boundary("inner");
                }
                else
                {
                    boundary_region = SearchRegion.Boundary("inner");
                }

                HTuple row_rect2, col_rect2, phi_rect2, lenght1_rect2, lenght2_rect2;
                if (this.createShapeModel.modelRegion == null || !this.createShapeModel.modelRegion.IsInitialized())
                {
                    return;
                }
                this.createShapeModel.modelRegion.SmallestRectangle2(out row_rect2, out col_rect2, out phi_rect2, out lenght1_rect2, out lenght2_rect2);

                HRegion small_rect2_region = new HRegion();
                small_rect2_region.GenRectangle2(row_rect2, col_rect2, phi_rect2, lenght1_rect2, lenght2_rect2);

                HRegion small_rect2_region_affine = homMat2D.AffineTransRegion(small_rect2_region, "nearest_neighbor");

                HObject Area_temp;
                HOperatorSet.Intersection(boundary_region, small_rect2_region_affine, out Area_temp);
                HTuple area, row_tt, col_tt;
                HOperatorSet.AreaCenter(Area_temp, out area, out row_tt, out col_tt);
                if (area.D == 0)
                {
                    mat2Ds.Add(homMat2D);
                    row    = row.TupleConcat(row_temp[i]);
                    column = column.TupleConcat(column_temp[i]);
                    angle  = angle.TupleConcat(angle_temp[i]);
                    scale  = scale.TupleConcat(scale_temp[i]);
                    score  = score.TupleConcat(score_temp[i]);
                }
                if (boundary_region != null && boundary_region.IsInitialized())
                {
                    boundary_region.Dispose();
                }
                if (small_rect2_region_affine != null && small_rect2_region_affine.IsInitialized())
                {
                    small_rect2_region_affine.Dispose();
                }
                if (small_rect2_region != null && small_rect2_region.IsInitialized())
                {
                    small_rect2_region.Dispose();
                }
                if (Area_temp != null && Area_temp.IsInitialized())
                {
                    Area_temp.Dispose();
                }
            }
        }
        /// <summary>
        /// Creates an iconic object depicting the 
        /// measuring field.
        /// </summary>
        public void UpdateMeasureRegion()
        {
            mMeasureRegion.Dispose();
            mMeasureRegion.GenEmptyObj();
            switch (mROIType)
            {
                case 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();
                    break;
                case ROI.ROI_TYPE_CIRCLE:
                    //
                    break;
                default:
                    mMeasureRegion.GenRectangle2(mMeasROI[0].D, mMeasROI[1].D,
                                             mMeasROI[2].D, mMeasROI[3].D,
                                             mMeasROI[4].D);
                    break;
            }
        }
 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>
        /// 更新量測結果.
        /// 量測演算法放這裡
        /// </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();
        }