//-------------------------------------------------------

        private void action()
        {
            HOperatorSet.SetColor(hv_ExpDefaultWinHandle, "yellow");                                    //設定畫線的顏色及粗細
            HOperatorSet.SetDraw(hv_ExpDefaultWinHandle, "margin");
            HOperatorSet.SetLineWidth(hv_ExpDefaultWinHandle, 2);

            HOperatorSet.GenEmptyObj(out ho_Rectangle);                                                 //清空ho_Rectangle

            HOperatorSet.DrawLine(hv_ExpDefaultWinHandle, out hv_line_Row1, out hv_line_Column1,        //畫線
                out hv_line_Row2,out hv_line_Column2);

           hv_Rectangle_Row = (hv_line_Row1 + hv_line_Row2) / 2;                                        //線段轉換成矩形(Row、colum)
            hv_Rectangle_Column = (hv_line_Column1 + hv_line_Column2) / 2;

            HOperatorSet.AngleLx(hv_line_Row1, hv_line_Column1, hv_line_Row2, hv_line_Column2,          //線段與垂直線的夾角為何  此角度也是矩形參數理的角度
                out hv_Rectangle_Angle);

            HOperatorSet.DistancePp(hv_line_Row1, hv_line_Column1, hv_line_Row2, hv_line_Column2,       //兩點之間的距離運算
                out hv_line_Distance);
            
            hv_Rectangle_length1 = hv_line_Distance / 2;                                                //線段轉換成矩形(length1)

            HOperatorSet.GenRectangle2(out ho_Rectangle, hv_Rectangle_Row, hv_Rectangle_Column,         //產生一個矩形ROI區域(ho_Rectangle)
                hv_Rectangle_Angle, hv_Rectangle_length1, hv_Rectangle_length2);

            HOperatorSet.GenRegionLine(out ho_line, hv_line_Row1, hv_line_Column1, hv_line_Row2,        //產生線段
                hv_line_Column2);

            HOperatorSet.DispObj(ho_line, hv_ExpDefaultWinHandle);                                      //顯示矩形ROI(ho_Rectangle)
        }
        public void DrawROIline(HTuple hwindows)//方形
        {
            emptyallparameter();
            HOperatorSet.GenEmptyObj(out ROI);
            SetLine(hwindows, "yellow", "margin", 2);

            HOperatorSet.DrawLine(hwindows, out line_Row1, out line_Column1,                //畫線
                out line_Row2, out line_Column2);

            Row = (line_Row1 + line_Row2) / 2;                                              //線段轉換成矩形(Row、colum)
            Column = (line_Column1 + line_Column2) / 2;

            HOperatorSet.AngleLx(line_Row1, line_Column1, line_Row2, line_Column2,          //線段與垂直線的夾角為何  此角度也是矩形參數理的角度
                out Phi);

            HOperatorSet.DistancePp(line_Row1, line_Column1, line_Row2, line_Column2,       //兩點之間的距離運算
                out line_Distance);

            Length1Rectangle = line_Distance / 2;                                           //線段轉換成矩形(length1)

            HOperatorSet.GenRectangle2(out ROI, Row, Column,                                //產生一個矩形ROI區域(ho_Rectangle)
                Phi, Length1Rectangle, 0);

            HOperatorSet.DispObj(ROI, hwindows);
        }
 public static void AffineTransImage(ImageBase srcImage, ImageBase dstImage, HTuple row, HTuple col , HTuple ang)
 {
     HTuple hv_HomMat2D=null;
     HObject tempImage = null;
     HOperatorSet.VectorAngleToRigid(srcImage.GetWidth / 2, srcImage.GetHeight / 2, 0 ,row ,col, ang , out hv_HomMat2D);
     HOperatorSet.AffineTransImage(srcImage.GetImage, out tempImage, hv_HomMat2D,"constant", "'false");
     dstImage.CopyImagetoThis(tempImage);
     tempImage.Dispose();
 }
 /*CoherenceEnhancingDiff
 Sigma (input_control)  real → (real)
 Smoothing for derivative operator.
     Default value: 0.5
     Suggested values: 0.0, 0.1, 0.5, 1.0
     Restriction: Sigma >= 0
 Rho (input_control)  real → (real)
 Smoothing for diffusion coefficients.
     Default value: 3.0
     Suggested values: 0.0, 1.0, 3.0, 5.0, 10.0, 30.0
     Restriction: Rho >= 0
 Theta (input_control)  real → (real)
 Time step.
     Default value: 0.5
     Suggested values: 0.1, 0.2, 0.3, 0.4, 0.5
     Restriction: (0 < Theta) <= 0.5
 Iterations (input_control)  integer → (integer)
 Number of iterations.
     Default value: 10
     Suggested values: 1, 5, 10, 20, 50, 100, 500
     Restriction: Iterations >= 1
 */
 public  void CoherenceEnhancingDiff(ImageBase src_Image, ImageBase dst_Image, HTuple sigma, HTuple rho, HTuple theta, HTuple iterations)
 {
     HObject dst;
     HOperatorSet.CoherenceEnhancingDiff(src_Image.GetImage, out dst, sigma, rho, theta, iterations);
     dst_Image.CopyImagetoThis(dst);
     dst.Dispose();
 }
 public MeasurementFitLine(ROI roi, MeasureAssistant mAssist)
     : base(roi, mAssist)
 {
     mResult = new FitLineResult();
     _cameraOut = new HTuple();
     UpdateMeasure();
 }
 /// <summary>
 /// 線段的顯示 viewModel
 /// </summary>
 /// <returns></returns>
 public override ResultDisplayViewModel CreateDisplayViewModel()
 {
     HXLDCont edge = new HXLDCont();
     HTuple rows, cols;
     double centerRow = 0.0, centerCol = 0.0;
     double f_ArrowX = 0.0, f_ArrowY = 0.0, s_ArrowX = 0.0, s_ArrowY = 0.0;
     if (Row1.TupleLength() > 0 && Row2.TupleLength() > 0)
     {
         rows = new HTuple(new double[] { Row1, Row2 });
         cols = new HTuple(new double[] { Col1, Col2 });
         centerRow = (Row1.D + Row2.D) / 2.0;
         centerCol = (Col1.D + Col2.D) / 2.0;
         f_ArrowX = Col1;
         f_ArrowY = Row1;
         s_ArrowX = Col2;
         s_ArrowY = Row2;
         edge.GenContourPolygonXld(rows, cols);
     }
     return new ResultDisplayViewModel()
     {
         PositionX = centerCol,
         PositionY = centerRow,
         ImageXLD = edge,
         FirstArrowX = f_ArrowX,
         FirstArrowY = f_ArrowY,
         SecArrowX = s_ArrowX,
         SecArrowY = s_ArrowY,
     };
 }
 public void Initialize(HImage image, HTuple modelRow, HTuple modelColumn, HTuple modelAngle)
 {
     ho_Image = image;
     hv_AllModelRow = new HTuple(modelRow);
     hv_AllModelColumn = new HTuple(modelColumn);
     hv_AllModelAngle = new HTuple(modelAngle);
 }
 /*Emphasize
 MaskWidth (input_control)  extent.x → (integer)
 Width of low pass MaskBase.
     Default value: 7
     Suggested values: 3, 5, 7, 9, 11, 15, 21, 25, 31, 39
     Typical range of values: 3 ≤ MaskWidth ≤ 201
     Minimum increment: 2
     Recommended increment: 2
 MaskHeight (input_control)  extent.y → (integer)
 Height of the low pass MaskBase.
     Default value: 7
     Suggested values: 3, 5, 7, 9, 11, 15, 21, 25, 31, 39
     Typical range of values: 3 ≤ MaskHeight ≤ 201
     Minimum increment: 2
     Recommended increment: 2
 Factor (input_control)  real → (real)
 Intensity of contrast emphasis.
     Default value: 1.0
     Suggested values: 0.3, 0.5, 0.7, 1.0, 1.4, 1.8, 2.0
     Typical range of values: 0.0 ≤ Factor ≤ 20.0 (sqrt)
     Minimum increment: 0.01
     Recommended increment: 0.2
     Restriction: (0 < Factor) && (Factor < 20)
 */
 public  void Emphasize(ImageBase src_Image, ImageBase dst_Image,MaskBase maskEmphasize, HTuple factor)
 {
     HObject dst;
     HOperatorSet.Emphasize(src_Image.GetImage, out dst, maskEmphasize.W, maskEmphasize.H, factor);
     dst_Image.CopyImagetoThis(dst);
     dst.Dispose();
 }
 public static void ZoomImageFactor(ImageBase srcImage, ImageBase dstImage, HTuple scaleWidth, HTuple scaleHeight)
 {
     HObject tempImage = null;
     HOperatorSet.ZoomImageFactor(srcImage.GetImage, out tempImage, scaleWidth, scaleHeight, "constant");
     dstImage.CopyImagetoThis(tempImage);
     tempImage.Dispose();
 }
        public void ClearAll() {

            if (CreatModelID!=null) {
                HOperatorSet.ClearShapeModel(CreatModelID);
            }
            Find_RowCheck = null;
            Find_ColumnCheck = null;
            Find_AngleCheck = null;
            Find_Score = null;
            Template_rot_matrix = null;
            matrix_OtoObject = null;
            matrix_ObjecttoCenter = null;

            Reduce_Image.Dispose() ;
            
            CreatShapeModel.Dispose();
            ModelAtNewPosition.Dispose();
            ModelAtNewPosition_temp.Dispose();
            ImageAtNewPosition.Dispose();
            Template_Image_rot.Dispose();
            ROI_rot.Dispose();

            SelectImage.Clear();
            index.Clear();
            src_Image.SetImage = null;

        }
 public static void SetPen(HTuple hwindows, HTuple color, HTuple Draw, HTuple LineWidth)//線條參數
 {
     HOperatorSet.SetColor(hwindows, color);
     HOperatorSet.SetDraw(hwindows, Draw);
     HOperatorSet.SetLineWidth(hwindows, LineWidth);
     
 }
Exemple #12
0
        public static void set_list (HTuple hv_RowEdge, HTuple hv_ColumnEdge, HTuple hv_Amplitude, HTuple hv_Distance, System.Windows.Forms.ListView listView) {

            listView.BeginUpdate();   //数据更新,UI暂时挂起,直到EndUpdate绘制控件,可以有效避免闪烁并大大提高加载速度  
            listView.Items.Clear();
            for (int i = 0; i < hv_RowEdge.Length; i++) {

                string i_string = Convert.ToString(i);

                HTuple hv_RowEdge_string;
                HTuple hv_ColumnEdge_string;
                HTuple hv_Amplitude_string;
                HTuple hv_Distance_string;

                HOperatorSet.TupleString(hv_RowEdge, ".7f", out hv_RowEdge_string);
                HOperatorSet.TupleString(hv_ColumnEdge, ".7f", out hv_ColumnEdge_string);
                HOperatorSet.TupleString(hv_Amplitude, ".7f", out hv_Amplitude_string);
                HOperatorSet.TupleString(hv_Distance, ".7f", out hv_Distance_string);

                listView.Items.Add(i_string, i_string, 0);
                listView.Items[i_string].SubItems.Add(hv_RowEdge_string[i]);
                listView.Items[i_string].SubItems.Add(hv_ColumnEdge_string[i]);
                listView.Items[i_string].SubItems.Add(hv_Amplitude_string[i]);

                if(i != hv_RowEdge.Length-1)
                    listView.Items[i_string].SubItems.Add(hv_Distance_string[i]);

            }
            listView.EndUpdate();  //结束数据处理,UI界面一次性绘制。  
        }
 public FitLineResult(double row1, double col1, double row2, double col2)
 {
     this.Row1 = new HTuple(row1);
     this.Col1 = new HTuple(col1);
     this.Row2 = new HTuple(row2);
     this.Col2 = new HTuple(col2);
 }
 public LineResult(double row1, double col1, double row2, double col2, double distance)
 {
     this.Row1 = new HTuple(row1);
     this.Col1 = new HTuple(col1);
     this.Row2 = new HTuple(row2);
     this.Col2 = new HTuple(col2);
     this.Distance = new HTuple(distance);
 }
 /// <summary>
 /// Creates an edge result instance using the passed values.
 /// </summary>
 public EdgeResult(double Nrow, double Ncol,
     double Nampl, double Ndist)
 {
     rowEdge = new HTuple(Nrow);
     colEdge = new HTuple(Ncol);
     amplitude = new HTuple(Nampl);
     distance = new HTuple(Ndist);
 }
 public void Add_Object_disp(HObject obj, HTuple color, HTuple Draw, HTuple LineWidth)
 {
     setObjectdisplay OD = new setObjectdisplay();
     OD.color = color;
     OD.Draw = Draw;
     OD.LineWidth = LineWidth;
     Object_disp.Add(obj);
     setObject_display.Add(OD);
 }
        // Main procedure 
        public void Metrology_line(HTuple Windows,ImageBase IMG)
        {
            // Local iconic variables 

            HObject ho_Image, ho_MeasureConts, ho_Cross;
            HObject ho_line;
            // Local control variables 

            HTuple hv_WindowHandle = new HTuple(), hv_Width = null;
            HTuple hv_Height = null, hv_MetrologyHandle = null, hv_Row1 = null;
            HTuple hv_Column1 = null, hv_Row2 = null, hv_Column2 = null;
            HTuple hv_Index1 = null, hv_Par = null, hv_Rtmp = null;
            HTuple hv_Ctmp = null;
            // Initialize local and output iconic variables 
            HOperatorSet.GenEmptyObj(out ho_Image);
            HOperatorSet.GenEmptyObj(out ho_MeasureConts);
            HOperatorSet.GenEmptyObj(out ho_Cross);
            HOperatorSet.GenEmptyObj(out ho_line);

            ho_Image.Dispose();
            ho_Image = IMG.GetImage.Clone();
            //dev_close_window(...);
            //dev_open_window(...);
            HOperatorSet.DispObj(ho_Image, Windows);
            HOperatorSet.GetImageSize(ho_Image, out hv_Width, out hv_Height);
            HOperatorSet.CreateMetrologyModel(out hv_MetrologyHandle);
            HOperatorSet.SetMetrologyModelImageSize(hv_MetrologyHandle, hv_Width, hv_Height);
            HOperatorSet.DrawLine(Windows, out hv_Row1, out hv_Column1, out hv_Row2,
                out hv_Column2);
            HOperatorSet.AddMetrologyObjectLineMeasure(hv_MetrologyHandle, hv_Row1, hv_Column1,
                hv_Row2, hv_Column2, 20, 5, 1, 10, "measure_transition", "all", out hv_Index1);
            HOperatorSet.ApplyMetrologyModel(ho_Image, hv_MetrologyHandle);
            HOperatorSet.GetMetrologyObjectResult(hv_MetrologyHandle, "all", "all", "result_type",
                "all_param", out hv_Par);
            ho_MeasureConts.Dispose();
            HOperatorSet.GetMetrologyObjectMeasures(out ho_MeasureConts, hv_MetrologyHandle,
                "all", "all", out hv_Rtmp, out hv_Ctmp);
            ho_Cross.Dispose();
            HOperatorSet.GenCrossContourXld(out ho_Cross, hv_Rtmp, hv_Ctmp, 6, (new HTuple(45)).TupleRad()
                );

            HOperatorSet.DispObj(ho_Image, Windows);

            HOperatorSet.SetColor(Windows, "blue");
            HOperatorSet.DispObj(ho_Cross, Windows);

            HOperatorSet.SetColor(Windows, "red");
            ho_line.Dispose();
            HOperatorSet.GenRegionLine(out ho_line, hv_Par.TupleSelect(0), hv_Par.TupleSelect(
                1), hv_Par.TupleSelect(2), hv_Par.TupleSelect(3));
            HOperatorSet.DispObj(ho_line, Windows);

            ho_Image.Dispose();
            ho_MeasureConts.Dispose();
            ho_Cross.Dispose();
            ho_line.Dispose();
        }
 public CircleResult()
 {
     this.Radius = new HTuple();
     this.Row = new HTuple();
     this.Col = new HTuple();
     this.StartPhi = new HTuple();
     this.EndPhi = new HTuple();
     this.PointOrder = new HTuple();
 }
 public CircleResult(double row, double col, double radius, double startPhi, double EndPhi, string pointOrder)
 {
     this.Row = new HTuple(row);
     this.Col = new HTuple(col);
     this.Radius = new HTuple(radius);
     this.StartPhi = new HTuple(startPhi);
     this.EndPhi = new HTuple(EndPhi);
     this.PointOrder = new HTuple(pointOrder);
 }
Exemple #20
0
        public void disp_Measure_rectangle2(HTuple Window) {

                ho_Cross.Dispose();
            HOperatorSet.SetColor(Window, "blue");                                       //設定顏色及型態
            HOperatorSet.SetDraw(Window, "margin");
            HOperatorSet.GenCrossContourXld(out ho_Cross, hv_RowEdge, hv_ColumnEdge,                    //產生錨點標記十字
                Measure_retangle2 * 2, Measure_Phi);
            
            HOperatorSet.DispObj(ho_Cross, Window);
        }
    /// <summary>
    /// Evaluates the gray value contrast between the marks and the calibration 
    /// plate and the homogeneity of the used illumination.
    /// </summary>
    public void eval_caltab_contrast_homogeneity(HObject ho_Image, 
                                                HObject ho_Marks,
                                                out HTuple hv_Contrast, 
                                                out HTuple hv_ContrastScore, 
                                                out HTuple hv_HomogeneityScore)
    {
        // Local iconic variables

          HObject ho_Region, ho_RegionDilation;

          // Local control variables

          HTuple hv_Number, hv_Min, hv_Max, hv_Range;
          HTuple hv_MinContrast, hv_MaxContrast, hv_DeviationMax;

          // Initialize local and output iconic variables
          HOperatorSet.GenEmptyObj(out ho_Region);
          HOperatorSet.GenEmptyObj(out ho_RegionDilation);

          hv_ContrastScore = 0.0;
          hv_Contrast = 0.0;
          hv_HomogeneityScore = 0.0;
          HOperatorSet.CountObj(ho_Marks, out hv_Number);
          if ((int)(new HTuple(hv_Number.TupleLess(4))) != 0)
          {
          ho_Region.Dispose();
          ho_RegionDilation.Dispose();

          return;
          }
          ho_Region.Dispose();
          HOperatorSet.GenRegionContourXld(ho_Marks, out ho_Region, "margin");
          ho_RegionDilation.Dispose();
          HOperatorSet.DilationCircle(ho_Region, out ho_RegionDilation, 5.5);
          HOperatorSet.MinMaxGray(ho_RegionDilation, ho_Image, 3, out hv_Min, out hv_Max,
          out hv_Range);
          //Calculate contrast score
          hv_Contrast = hv_Range.TupleMean();
          hv_MinContrast = 70;
          hv_MaxContrast = 160;
          if ((int)(new HTuple(hv_Contrast.TupleGreater(hv_MinContrast))) != 0)
          {
          hv_ContrastScore = (hv_Contrast - hv_MinContrast) / (hv_MaxContrast - hv_MinContrast);
          hv_ContrastScore = ((hv_ContrastScore.TupleConcat(1.0))).TupleMin();
          }
          //Now for the homogeneity score
          HOperatorSet.TupleDeviation(hv_Max, out hv_DeviationMax);
          hv_HomogeneityScore = 1.1 - (hv_DeviationMax / 40.0);
          hv_HomogeneityScore = ((((((hv_HomogeneityScore.TupleConcat(1.0))).TupleMin()
          )).TupleConcat(0.0))).TupleMax();
          ho_Region.Dispose();
          ho_RegionDilation.Dispose();

          return;
    }
        public void ShowImage(HTuple Window)//將圖片顯示在指定的halcon視窗上  輸入變數:HTuple Window(視窗)
        {
            if (Image != null)
            {
                HOperatorSet.ClearWindow(Window);
                HOperatorSet.DispObj(Image, Window);
            }
            else
                MessageBox.Show("Error Image 是空的!");

        }
 public AutoFitPoint(ROI roi, MeasureAssistant mAssist)
     : base(roi, mAssist)
 {
     mResult = new EdgeResult();
     mResultWorld = new EdgeResult();
     if (mMeasAssist.IsCalibrationValid)
     {
         _cameraOut = HMisc.ChangeRadialDistortionCamPar("adaptive", mMeasAssist.CameraIn, 0.0);
     }
     UpdateMeasure();
 }
        public void GetMpositionSubPix(HTuple Window)
        {
            try
            {
                HOperatorSet.GetMpositionSubPix(Window, out row, out col, out Button);
            }
            catch (Exception)
            {

            }
        }
        /// <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;
        }
 public DistanceResult(HTuple rowBegin1, HTuple colBegin1, HTuple rowEnd1, HTuple colEnd1, HTuple rowBegin2, HTuple colBegin2, HTuple rowEnd2, HTuple colEnd2, HTuple angle, HTuple distance)
 {
     this.FirstRowBegin = new HTuple(rowBegin1);
     this.FirstColBegin = new HTuple(colBegin1);
     this.FirstRowEnd = new HTuple(rowEnd1);
     this.FirstColEnd = new HTuple(colEnd1);
     this.SecondRowBegin = new HTuple(rowBegin2);
     this.SecondColBegin = new HTuple(colBegin2);
     this.SecondRowEnd = new HTuple(rowEnd2);
     this.SecondColEnd = new HTuple(colEnd2);
     this.Angle = new HTuple(angle);
     this.Distance = new HTuple(distance);
 }
Exemple #27
0
        public void matchingNmeasure(MatchModel Model , Measure measure,ImageBase image_matchingNmeasure,RegionBase region_matchingNmeasure, RegionBase region_measure,HTuple window) {

           
            HOperatorSet.FindShapeModel(image_matchingNmeasure.GetImage, Model.get_ModelID, 0, (new HTuple(360)).TupleRad(), 0.6, 0, 0.5, "least_squares", 0, 0.7, out hv_RowCheck, out hv_ColumnCheck, out hv_AngleCheck, out hv_Score);

            HOperatorSet.GetShapeModelContours(out ho_ShapeModel, Model.get_ModelID, 1);

            HOperatorSet.VectorAngleToRigid(region_matchingNmeasure.GetRow, region_matchingNmeasure.GetColumn, 0, 0, 0, 0, out hv_MovementOfObject_O);          //計算元件ROI原點轉換到影像座標原點的矩陣為何
            HOperatorSet.AffineTransPoint2d(hv_MovementOfObject_O, region_measure.GetRow, region_measure.GetColumn,                                             //依照上面的旋轉矩陣去計算測量的矩形轉換到原點做標後的中心
                out hv_Row_Measure_O, out hv_Column_Measure_O);

            if ((int)(new HTuple((new HTuple(hv_Score.TupleLength())).TupleGreater(0.9))) != 0)
            {
                HOperatorSet.VectorAngleToRigid(0, 0, 0, hv_RowCheck, hv_ColumnCheck, hv_AngleCheck, out hv_MovementOfObject_contour);                          //產生旋轉矩陣(原點到匹配位置)

                HOperatorSet.AffineTransContourXld(Model.get_ShapeModel, out ho_ShapeModelAtNewPosition, hv_MovementOfObject_contour);                          //轉換Contour到匹配位置

                HOperatorSet.AffineTransPoint2d(hv_MovementOfObject_contour, hv_Row_Measure_O, hv_Column_Measure_O,                          //使用上面得到的旋轉矩陣去轉換測量矩形的中心從原點到匹配位置
                    out hv_Row_Measure_Search, out hv_Column_Measure_Search);



                HOperatorSet.GenRectangle2(out ho_Measure_ROI_Search, hv_Row_Measure_Search, hv_Column_Measure_Search,                      //產生測量ROI區域
                    hv_AngleCheck + region_measure.GetPhi, region_measure.GetLength1Rectangle,
                    region_measure.GetLength2Rectangle);

                HOperatorSet.GenRectangle2(out ho_line_show, hv_Row_Measure_Search, hv_Column_Measure_Search,                               //為了顯示而產生的Length2為零區域
                    hv_AngleCheck + region_measure.GetPhi, region_measure.GetLength1Rectangle, 0);

                HOperatorSet.GenMeasureRectangle2(hv_Row_Measure_Search, hv_Column_Measure_Search, hv_AngleCheck +                           //產生測量矩形
                    region_measure.GetPhi, region_measure.GetLength1Rectangle,region_measure.GetLength2Rectangle,
                    image_matchingNmeasure.GetWidth, image_matchingNmeasure.GetHeight, "nearest_neighbor", out hv_MeasureHandle);


                HOperatorSet.MeasurePos(image_matchingNmeasure.GetImage, hv_MeasureHandle, 1, 25, "all", "all", out hv_RowEdge, out hv_ColumnEdge,            //設定測量伐值  輸出測量錨點
                    out hv_Amplitude, out hv_Distance);

                HOperatorSet.GenCrossContourXld(out ho_Cross, hv_RowEdge, hv_ColumnEdge, 2 * region_measure.GetLength2Rectangle,             //產生十字點
                    hv_AngleCheck);

                HOperatorSet.DispObj(image_matchingNmeasure.GetImage, window); 
                HOperatorSet.DispObj(ho_ShapeModelAtNewPosition, window);
                HOperatorSet.SetColor(window, "blue");
                HOperatorSet.DispObj(ho_Cross, window);
                HOperatorSet.SetColor(window, "red");
                HOperatorSet.DispObj(ho_line_show, window);
                HOperatorSet.CloseMeasure(hv_MeasureHandle);
            }

        }
        public void drawROI(HTuple Window)                                                              //調整參數時重新顯示調整之後的線段                                                             
        {
            hv_ExpDefaultWinHandle = Window;

            ho_Rectangle.Dispose();                                                                     //清除ho_Rectangle

            HOperatorSet.GenRectangle2(out ho_Rectangle, hv_Rectangle_Row, hv_Rectangle_Column,         //產生ho_Rectangle ROI
                hv_Rectangle_Angle, hv_Rectangle_length1, hv_Rectangle_length2);

            HOperatorSet.GenRegionLine(out ho_line, hv_line_Row1, hv_line_Column1, hv_line_Row2,        //產生線段
                hv_line_Column2);

            HOperatorSet.DispObj(ho_line, hv_ExpDefaultWinHandle);                                      //顯示線段
        }
 public void ShowImage_autosize(HTuple Window)//將圖片顯示在指定的halcon視窗上  輸入變數:HTuple Window(視窗)
 {
     if (Image != null)
     {
         HOperatorSet.GetImageSize(Image, out hv_Width, out hv_Height);
         HOperatorSet.SetSystem("width", hv_Width);
         HOperatorSet.SetSystem("height", hv_Height);
         HOperatorSet.SetPart(Window, 0, 0, hv_Height - 1, hv_Width - 1);
         HOperatorSet.ClearWindow(Window);
         HOperatorSet.DispObj(Image, Window);
     }
     else
         MessageBox.Show("Error Image 是空的!");
 }
        public void Show(HTuple Window)                                                             //顯示找到的物件位置
        {
            HOperatorSet.SetColor(Window, "blue");                                       //設定顏色及型態
            HOperatorSet.SetDraw(Window, "margin");

            if (ho_ModelAtNewPosition!=null) {
                HOperatorSet.DispObj(ho_ModelAtNewPosition, Window);
            }
            if (ho_RegionAffineTrans != null)
            {
                HOperatorSet.DispObj(ho_RegionAffineTrans, Window);
            }
            
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="stdRow">訓練圖形中心點 Row</param>
        /// <param name="stdCol">訓練圖形中心點 Col</param>
        /// <param name="curModelAngle">目前圖形 Angle</param>
        /// <param name="hv_OffsetRow">hv_Img_Row - hv_STD_Row (現在圖形中心點 Row - 訓練圖形中心點 Row</param>
        /// <param name="hv_OffsetCol">hv_Img_Col - hv_STD_Col (現在圖形中心點 Col - 訓練圖形中心點 Col</param>
        /// <param name="roiRow">訓練圖形時設定的 ROI Row</param>
        /// <param name="roiCol">訓練圖形時設定的 ROI Col</param>
        /// <param name="curROI_Row">回傳值 - 重定位後的 Row</param>
        /// <param name="curROI_Col">回傳值 - 重定位後的 Col</param>
        private void ReLocater(HTuple stdRow, HTuple stdCol, HTuple curModelAngle, HTuple offsetRow, HTuple offsetCol
                               , HTuple roiRow, HTuple roiCol
                               , out HTuple curROI_Row, out HTuple curROI_Col)
        {
            //roiRow = 1110;
            //roiCol = 630;

            //STD 向量 STD_A_1_1_
            HTuple veterRow = roiRow - stdRow;
            HTuple vertCol  = roiCol - stdCol;

            HTuple roiVeterCol  = (vertCol * (curModelAngle.TupleCos())) + (veterRow * (curModelAngle.TupleSin()));
            HTuple roiVectorRow = (veterRow * (curModelAngle.TupleCos())) - (vertCol * (curModelAngle.TupleSin()));


            //目前圖形 A_1_1_ 位置
            curROI_Row = (stdRow + roiVectorRow) + offsetRow;
            curROI_Col = (stdCol + roiVeterCol) + offsetCol;
        }
        /// <summary>
        /// 图像匹配函数,测试使用,可重新编写
        /// 只实现了简单ncc匹配,不支持roi内匹配,只能匹配一个目标
        /// </summary>
        /// <param name="image">输入图像</param>
        /// <param name="model">模型</param>
        /// <param name="u">返回匹配行坐标,pixel,如果失败为null</param>
        /// <param name="v">返回匹配列坐标,pixel,如果失败为null</param>
        /// <param name="angle">返回匹配角度,弧度,如果失败为null</param>
        /// <returns>是否匹配成功</returns>
        public bool matchModel(int camInd, ref HObject image, Model model, out HTuple u, out HTuple v, out HTuple angle)
        {
            //HTuple _u = new HTuple(), _v = new HTuple(), _angle = new HTuple();
            //bool matched =  matchModel(image, model.modelID, model.scoreThresh.D, out _u, out _v, out _angle);
            //u = _u; v = _v; angle = _angle;
            //return matched;
            u     = null;
            v     = null;
            angle = null;
            try
            {
                HTuple scores = new HTuple();
                // HTuple a = new HTuple(); HTuple b = new HTuple();

                HTuple  us = new HTuple(), vs = new HTuple();
                HTuple  score;
                HObject cross = null;
                HOperatorSet.GenEmptyObj(out cross);

                HObject updateShowCont = null;
                HOperatorSet.GenEmptyObj(out updateShowCont);
                HTuple  updateDefRow = new HTuple(), updateDefCol = new HTuple(), hom2d, iFlag = new HTuple();
                HObject matchRegion = (model.matchRegion != null && model.matchRegion.IsInitialized()) ? model.matchRegion : image;
                //HOperatorSet.FindNccModel(image, modelID, -0.39, 0.78, 0.5, 1, 0.5, "true", 0, out u, out v, out angle, out score);
                //模版句柄
                for (int i = 0; i < model.modelID.Length; i++)
                {
                    updateShowCont.Dispose();

                    HOperatorSet.GenEmptyObj(out model.showContour);
                    //匹配起始角度为-1rad,范围为2rad,阈值为0.5
                    ToolKits.FunctionModule.Vision.find_model(image, matchRegion, model.showContour, out updateShowCont, model.modelType, model.modelID[i], -0.1, 0.2,
                                                              0.5, 1, model.defRows[i], model.defCols[i], out u, out v, out angle, out score, out updateDefRow, out updateDefCol,
                                                              out hom2d, out iFlag);

                    if (iFlag.I == 0)
                    {
                        scores.Append(score);
                        us.Append(updateDefRow);
                        vs.Append(updateDefCol);
                    }
                    else
                    {
                        us.Append(0);
                        vs.Append(0);
                        scores.Append(0);
                        updateShowCont.Dispose();
                        cross.Dispose();
                        return(false);
                    }
                }
                HTuple sortInd;
                //排数 从小到大
                HOperatorSet.TupleSortIndex(scores, out sortInd);
                //sortInd ???
                HTuple maxInd = sortInd[sortInd.Length - 1];
                score = scores[maxInd];
                bool status = false;
                //double
                if (score.D < 0.01)
                {
                    u     = null;
                    v     = null;
                    angle = null;
                    return(false);
                }
                else
                {
                    u      = us[maxInd];
                    v      = vs[maxInd];
                    angle  = 0;
                    status = true;
                }
                if (this.GrabImageDoneHandler != null && camInd >= 0)
                {
                    //Show _show = new Show();
                    //_show.CamInd = camInd;
                    //_show.Image = image.CopyObj(1, -1);
                    //_show.Mode = 2;
                    //_show.Row = status ? u.D : 0;
                    //_show.Column = status ? v.D : 0;
                    //;
                    //this.GrabImageDoneHandler(null, _show);
                }
                HOperatorSet.GenCrossContourXld(out cross, updateDefRow, updateDefCol, 300, 0);
                //App.mainWindow.ShowImage(frmCalibration.Instance.htWindowCalibration, image, cross);
                if (ImageSrc != null)
                {
                    ImageSrc.Dispose();
                }
                HOperatorSet.GenEmptyObj(out ImageSrc);
                //for (int i = 0; i < imageNum; i++)
                //{
                //    //从acq里取图并保存图片,行号-列号.tiff
                HOperatorSet.SelectObj(image, out ImageSrc, 1);
                ////frmCalibration.Instance.ShowImage(frmCalibration.Instance.htWindowCalibration, image, cross);
                _station._rtUi._fm.ShowImage(_station._rtUi._fm.htWindowCalibration, ImageSrc, cross);
                //HOperatorSet.WriteContourXldDxf(updateShowCont, "D://CONT");
                //htWindow.RefreshWindow(image, cross, "");
                cross.Dispose();
                updateShowCont.Dispose();
                return(status);
            }
            catch (HalconException EXP)
            {
                string errMsg = EXP.Message;
                return(false);
            }
        }
Exemple #33
0
        public void displayROI(List <Model.RoiData> roiDatas)
        {
            //this._hWndControl.resetAll();
            //this._hWndControl.repaint();

            List <Model.ROI> rois = new List <Model.ROI>();

            foreach (var roiData in roiDatas)
            {
                switch (roiData.Name)
                {
                case "Rectangle1":
                    genRect1(roiData.Rectangle1.Row1, roiData.Rectangle1.Column1, roiData.Rectangle1.Row2, roiData.Rectangle1.Column2, ref rois);

                    break;

                case "Rectangle2":
                    genRect2(roiData.Rectangle2.Row, roiData.Rectangle2.Column, roiData.Rectangle2.Phi,
                             roiData.Rectangle2.Lenth1, roiData.Rectangle2.Lenth2, ref rois);

                    break;

                case "Circle":
                    genCircle(roiData.Circle.Row, roiData.Circle.Column, roiData.Circle.Radius, ref rois);

                    break;

                case "Line":
                    genLine(roiData.Line.RowBegin, roiData.Line.ColumnBegin, roiData.Line.RowEnd, roiData.Line.ColumnEnd, ref rois);

                    break;
                }
            }


            foreach (var roi in rois)
            {
                HTuple m_roiData = null;
                m_roiData = roi.getModelData();

                switch (roi.Type)
                {
                case "ROIRectangle1":

                    if (m_roiData != null)
                    {
                        this._roiController.displayRect1(m_roiData[0].D, m_roiData[1].D, m_roiData[2].D, m_roiData[3].D);
                    }
                    break;

                case "ROIRectangle2":

                    if (m_roiData != null)
                    {
                        this._roiController.displayRect2(m_roiData[0].D, m_roiData[1].D, m_roiData[2].D, m_roiData[3].D, m_roiData[4].D);
                    }
                    break;

                case "ROICircle":

                    if (m_roiData != null)
                    {
                        this._roiController.displayCircle(m_roiData[0].D, m_roiData[1].D, m_roiData[2].D);
                    }
                    break;

                case "ROILine":

                    if (m_roiData != null)
                    {
                        this._roiController.displayLine(m_roiData[0].D, m_roiData[1].D, m_roiData[2].D, m_roiData[3].D);
                    }
                    break;

                default:
                    break;
                }
            }
        }
Exemple #34
0
        /// <summary>
        /// 生成Die的检测区域
        /// </summary>
        /// <param name="ho_dieMatchRegion"></param>
        /// <param name="hv_imgCenterX"></param>
        /// <param name="hv_imgCenterY"></param>
        /// <param name="hv_dieWidth"></param>
        /// <param name="hv_dieHeight"></param>
        /// <param name="hv_dieX"></param>
        /// <param name="hv_dieY"></param>
        /// <param name="hv_uvHxy"></param>
        /// <param name="hv_imgWidth"></param>
        /// <param name="hv_imgHeight"></param>
        /// <param name="hv_imgWidthFactor"></param>
        /// <param name="hv_imgHeightFactor"></param>
        /// <param name="hv_zoomFactor"></param>
        /// <param name="hv_dilationSize"></param>
        /// <param name="hv_mapRowCnt"></param>
        /// <param name="hv_mapColCnt"></param>
        /// <param name="hv_dieRow"></param>
        /// <param name="hv_dieCol"></param>
        /// <param name="hv_iFlag"></param>
        public void gen_die_match_region(out HObject ho_dieMatchRegion, HTuple hv_imgCenterX, HTuple hv_imgCenterY, HTuple hv_dieWidth, HTuple hv_dieHeight,
                                         HTuple hv_dieX, HTuple hv_dieY, HTuple hv_uvHxy, HTuple hv_imgWidth, HTuple hv_imgHeight, HTuple hv_imgWidthFactor,
                                         HTuple hv_imgHeightFactor, HTuple hv_zoomFactor, HTuple hv_dilationSize, HTuple hv_mapRowCnt, HTuple hv_mapColCnt,
                                         out HTuple hv_dieRow, out HTuple hv_dieCol, out HTuple hv_iFlag)
        {
            // Local iconic variables
            // Local control variables
            HTuple hv_uvHxyScaled = new HTuple(), hv_xyHuvScale = new HTuple();
            HTuple hv_viewWidth = new HTuple(), hv_viewHeight = new HTuple();
            HTuple hv_viewXLT = new HTuple(), hv_viewYLT = new HTuple();
            HTuple hv_viewXRB = new HTuple(), hv_viewYRB = new HTuple();
            HTuple hv_dieXLT = new HTuple(), hv_dieYLT = new HTuple();
            HTuple hv_dieXRB = new HTuple(), hv_dieYRB = new HTuple();
            HTuple hv_xLTGreater = new HTuple(), hv_yLTLess = new HTuple();
            HTuple hv_xRBLess = new HTuple(), hv_yRBGreater = new HTuple();
            HTuple hv_greater = new HTuple(), hv_greaterInd = new HTuple();
            HTuple hv_viewDieX = new HTuple(), hv_viewDieY = new HTuple();
            HTuple hv_deltaX = new HTuple(), hv_deltaY = new HTuple();
            HTuple hv_xyHuv = new HTuple(), hv_deltaRow = new HTuple();
            HTuple hv_deltaCol = new HTuple(), hv_dieImgRow = new HTuple();
            HTuple hv_dieImgCol = new HTuple(), hv_dieImgHeight = new HTuple();
            HTuple hv_dieImgWidth = new HTuple(), hv_row1 = new HTuple();
            HTuple hv_col1 = new HTuple(), hv_row2 = new HTuple();
            HTuple hv_col2 = new HTuple(), hv_Exception = null;
            HTuple hv_Less = new HTuple(), hv_Indices1 = new HTuple(), hv_Greater = new HTuple();

            // Initialize local and output iconic variables
            HOperatorSet.GenEmptyObj(out ho_dieMatchRegion);
            hv_iFlag = "Success";
            ho_dieMatchRegion.Dispose();
            HOperatorSet.GenEmptyObj(out ho_dieMatchRegion);
            hv_dieRow = new HTuple();
            hv_dieCol = new HTuple();
            try
            {
                HOperatorSet.HomMat2dScale(hv_uvHxy, 1 / hv_zoomFactor, 1 / hv_zoomFactor, 0, 0,
                                           out hv_uvHxyScaled);
                HOperatorSet.HomMat2dInvert(hv_uvHxyScaled, out hv_xyHuvScale);
                hv_viewWidth = (((((hv_uvHxy.TupleSelect(0)) * hv_imgHeight) * hv_imgHeightFactor) + (((hv_uvHxy.TupleSelect(
                                                                                                            1)) * hv_imgWidth) * hv_imgWidthFactor))).TupleAbs();
                hv_viewHeight = (((((hv_uvHxy.TupleSelect(3)) * hv_imgHeight) * hv_imgHeightFactor) + (((hv_uvHxy.TupleSelect(
                                                                                                             4)) * hv_imgWidth) * hv_imgWidthFactor))).TupleAbs();
                hv_viewXLT = hv_imgCenterX - (hv_viewWidth / 2.0);
                hv_viewYLT = hv_imgCenterY + (hv_viewHeight / 2.0);
                hv_viewXRB = hv_imgCenterX + (hv_viewWidth / 2.0);
                hv_viewYRB = hv_imgCenterY - (hv_viewHeight / 2.0);
                hv_dieXLT  = hv_dieX - (hv_dieWidth / 2.0);
                hv_dieYLT  = hv_dieY + (hv_dieHeight / 2.0);
                hv_dieXRB  = hv_dieX + (hv_dieWidth / 2.0);
                hv_dieYRB  = hv_dieY - (hv_dieHeight / 2.0);

                HOperatorSet.TupleGreaterEqualElem(hv_dieXLT, hv_viewXLT, out hv_xLTGreater);
                HOperatorSet.TupleGreaterEqualElem(hv_viewYLT, hv_dieYLT, out hv_yLTLess);
                HOperatorSet.TupleLessEqualElem(hv_dieXRB, hv_viewXRB, out hv_xRBLess);
                HOperatorSet.TupleLessEqualElem(hv_viewYRB, hv_dieYRB, out hv_yRBGreater);
                hv_greater = ((hv_xLTGreater * hv_yLTLess) * hv_xRBLess) * hv_yRBGreater;
                HOperatorSet.TupleFind(hv_greater, 1, out hv_greaterInd);
                if ((int)(new HTuple(hv_greaterInd.TupleEqual(-1))) != 0)
                {
                    return;
                }
                hv_viewDieX = hv_dieX.TupleSelect(hv_greaterInd);
                hv_viewDieY = hv_dieY.TupleSelect(hv_greaterInd);
                hv_deltaX   = hv_imgCenterX - hv_viewDieX;
                hv_deltaY   = hv_imgCenterY - hv_viewDieY;
                HOperatorSet.HomMat2dInvert(hv_uvHxy, out hv_xyHuv);
                hv_deltaRow = ((hv_xyHuv.TupleSelect(0)) * hv_deltaX) + ((hv_xyHuv.TupleSelect(
                                                                              1)) * hv_deltaY);
                hv_deltaCol = ((hv_xyHuv.TupleSelect(3)) * hv_deltaX) + ((hv_xyHuv.TupleSelect(
                                                                              4)) * hv_deltaY);
                hv_dieImgRow    = ((hv_imgHeight - 1) / 2.0) + hv_deltaRow;
                hv_dieImgCol    = ((hv_imgWidth - 1) / 2.0) + hv_deltaCol;
                hv_dieImgHeight = ((((hv_xyHuv.TupleSelect(0)) * hv_dieWidth) + ((hv_xyHuv.TupleSelect(
                                                                                      1)) * (-hv_dieHeight)))).TupleAbs();
                hv_dieImgWidth = ((((hv_xyHuv.TupleSelect(3)) * hv_dieWidth) + ((hv_xyHuv.TupleSelect(
                                                                                     4)) * (-hv_dieHeight)))).TupleAbs();
                hv_row1 = (hv_dieImgRow - (hv_dieImgHeight / 2.0)) - hv_dilationSize;
                hv_col1 = (hv_dieImgCol - (hv_dieImgWidth / 2.0)) - hv_dilationSize;
                hv_row2 = (hv_dieImgRow + (hv_dieImgHeight / 2.0)) + hv_dilationSize;
                hv_col2 = (hv_dieImgCol + (hv_dieImgWidth / 2.0)) + hv_dilationSize;
                //if ((int)((new HTuple((new HTuple((new HTuple(hv_row1.TupleLess(0))).TupleOr(
                //    new HTuple(hv_col1.TupleLess(0))))).TupleOr(
                //    new HTuple(hv_row2.TupleGreater(hv_imgHeight))))).TupleOr(
                //    new HTuple(hv_col2.TupleGreater(hv_imgWidth)))) != 0)
                //{

                //    return;
                //}
                //*2019/11/4 修改 解决膨胀区域超过图片像素时直接return的问题 上面注释的代码
                HOperatorSet.TupleLessElem(hv_row1, 0, out hv_Less);
                HOperatorSet.TupleFind(hv_Less, 1, out hv_Indices1);
                if ((int)(new HTuple(hv_Indices1.TupleNotEqual(-1))) != 0)
                {
                    if (hv_row1 == null)
                    {
                        hv_row1 = new HTuple();
                    }
                    hv_row1[hv_Indices1] = 0;
                }

                HOperatorSet.TupleLessElem(hv_col1, 0, out hv_Less);
                HOperatorSet.TupleFind(hv_Less, 1, out hv_Indices1);
                if ((int)(new HTuple(hv_Indices1.TupleNotEqual(-1))) != 0)
                {
                    if (hv_col1 == null)
                    {
                        hv_col1 = new HTuple();
                    }
                    hv_col1[hv_Indices1] = 0;
                }

                HOperatorSet.TupleGreaterElem(hv_row2, hv_imgHeight, out hv_Greater);
                HOperatorSet.TupleFind(hv_Greater, 1, out hv_Indices1);
                if ((int)(new HTuple(hv_Indices1.TupleNotEqual(-1))) != 0)
                {
                    if (hv_row2 == null)
                    {
                        hv_row2 = new HTuple();
                    }
                    hv_row2[hv_Indices1] = hv_imgHeight;
                }

                HOperatorSet.TupleGreaterElem(hv_col2, hv_imgWidth, out hv_Greater);
                HOperatorSet.TupleFind(hv_Less, 1, out hv_Indices1);
                if ((int)(new HTuple(hv_Indices1.TupleNotEqual(-1))) != 0)
                {
                    if (hv_col2 == null)
                    {
                        hv_col2 = new HTuple();
                    }
                    hv_col2[hv_Indices1] = hv_imgWidth;
                }
                ho_dieMatchRegion.Dispose();
                HOperatorSet.GenRectangle1(out ho_dieMatchRegion, hv_row1, hv_col1, hv_row2,
                                           hv_col2);
                hv_dieRow = hv_greaterInd / hv_mapColCnt;
                hv_dieCol = hv_greaterInd % hv_mapColCnt;
            }
            catch (HalconException HDevExpDefaultException1)
            {
                HDevExpDefaultException1.ToHTuple(out hv_Exception);
                GetErrInfo(hv_Exception, out hv_iFlag);
            }
            return;
        }
Exemple #35
0
 public HobjectString(HTuple x, HTuple y, string str)
 {
     this.X   = x;
     this.Y   = y;
     this.str = str;
 }
    private void rake(HObject hoImage, out HObject hoRegions, HTuple hvElements, HTuple hvDetectHeight,
                      HTuple hvDetectWidth, HTuple hvSigma, HTuple hvThreshold, HTuple hvTransition,
                      HTuple hvSelect, HTuple hvRow1, HTuple hvColumn1, HTuple hvRow2, HTuple hvColumn2,
                      out HTuple hvBeginRow, out HTuple hvBeginCol)
    {
        HDevProcedure     rakeProc = new HDevProcedure("rake");
        HDevProcedureCall rakeProcCall;

        rakeProcCall = new HDevProcedureCall(rakeProc);
        rakeProcCall.SetInputIconicParamObject("Image", hoImage);
        rakeProcCall.SetInputCtrlParamTuple("Elements", hvElements);
        rakeProcCall.SetInputCtrlParamTuple("DetectHeight", hvDetectHeight);
        rakeProcCall.SetInputCtrlParamTuple("DetectWidth", hvDetectWidth);
        rakeProcCall.SetInputCtrlParamTuple("Sigma", hvSigma);
        rakeProcCall.SetInputCtrlParamTuple("Threshold", hvThreshold);
        rakeProcCall.SetInputCtrlParamTuple("Transition", hvTransition);
        rakeProcCall.SetInputCtrlParamTuple("Select", hvSelect);
        rakeProcCall.SetInputCtrlParamTuple("Row1", hvRow1);
        rakeProcCall.SetInputCtrlParamTuple("Column1", hvColumn1);
        rakeProcCall.SetInputCtrlParamTuple("Row2", hvRow2);
        rakeProcCall.SetInputCtrlParamTuple("Column2", hvColumn2);
        rakeProcCall.Execute();
        // get output parameters from procedure call

        hoRegions  = rakeProcCall.GetOutputIconicParamXld("Regions");
        hvBeginRow = rakeProcCall.GetOutputCtrlParamTuple("ResultRow");
        hvBeginCol = rakeProcCall.GetOutputCtrlParamTuple("ResultColumn");

        rakeProcCall.Dispose();
        rakeProc.Dispose();
    }
    public void disp_message(HTuple hv_WindowHandle, HTuple hv_String, HTuple hv_CoordSystem,
                             HTuple hv_Row, HTuple hv_Column, HTuple hv_Color, HTuple hv_Box)
    {
        // Local iconic variables

        // Local control variables

        HTuple hv_GenParamName = null, hv_GenParamValue = null;
        HTuple hv_Color_COPY_INP_TMP       = hv_Color.Clone();
        HTuple hv_Column_COPY_INP_TMP      = hv_Column.Clone();
        HTuple hv_CoordSystem_COPY_INP_TMP = hv_CoordSystem.Clone();
        HTuple hv_Row_COPY_INP_TMP         = hv_Row.Clone();

        //Convert the parameters for disp_text.
        if ((int)((new HTuple(hv_Row_COPY_INP_TMP.TupleEqual(new HTuple()))).TupleOr(
                      new HTuple(hv_Column_COPY_INP_TMP.TupleEqual(new HTuple())))) != 0)
        {
            return;
        }
        if ((int)(new HTuple(hv_Row_COPY_INP_TMP.TupleEqual(-1))) != 0)
        {
            hv_Row_COPY_INP_TMP = 12;
        }
        if ((int)(new HTuple(hv_Column_COPY_INP_TMP.TupleEqual(-1))) != 0)
        {
            hv_Column_COPY_INP_TMP = 12;
        }
        //
        //Convert the parameter Box to generic parameters.
        hv_GenParamName  = new HTuple();
        hv_GenParamValue = new HTuple();
        if ((int)(new HTuple((new HTuple(hv_Box.TupleLength())).TupleGreater(0))) != 0)
        {
            if ((int)(new HTuple(((hv_Box.TupleSelect(0))).TupleEqual("false"))) != 0)
            {
                //Display no box
                hv_GenParamName  = hv_GenParamName.TupleConcat("box");
                hv_GenParamValue = hv_GenParamValue.TupleConcat("false");
            }
            else if ((int)(new HTuple(((hv_Box.TupleSelect(0))).TupleNotEqual("true"))) != 0)
            {
                //Set a color other than the default.
                hv_GenParamName  = hv_GenParamName.TupleConcat("box_color");
                hv_GenParamValue = hv_GenParamValue.TupleConcat(hv_Box.TupleSelect(0));
            }
        }
        if ((int)(new HTuple((new HTuple(hv_Box.TupleLength())).TupleGreater(1))) != 0)
        {
            if ((int)(new HTuple(((hv_Box.TupleSelect(1))).TupleEqual("false"))) != 0)
            {
                //Display no shadow.
                hv_GenParamName  = hv_GenParamName.TupleConcat("shadow");
                hv_GenParamValue = hv_GenParamValue.TupleConcat("false");
            }
            else if ((int)(new HTuple(((hv_Box.TupleSelect(1))).TupleNotEqual("true"))) != 0)
            {
                //Set a shadow color other than the default.
                hv_GenParamName  = hv_GenParamName.TupleConcat("shadow_color");
                hv_GenParamValue = hv_GenParamValue.TupleConcat(hv_Box.TupleSelect(1));
            }
        }
        //Restore default CoordSystem behavior.
        if ((int)(new HTuple(hv_CoordSystem_COPY_INP_TMP.TupleNotEqual("window"))) != 0)
        {
            hv_CoordSystem_COPY_INP_TMP = "image";
        }
        //
        if ((int)(new HTuple(hv_Color_COPY_INP_TMP.TupleEqual(""))) != 0)
        {
            //disp_text does not accept an empty string for Color.
            hv_Color_COPY_INP_TMP = new HTuple();
        }
        //
        HOperatorSet.DispText(3600, hv_String, hv_CoordSystem_COPY_INP_TMP,
                              hv_Row_COPY_INP_TMP, hv_Column_COPY_INP_TMP, hv_Color_COPY_INP_TMP, hv_GenParamName,
                              hv_GenParamValue);

        return;
    }
            public void MeasureRoundness(HObject image, out HObject region, /*out HTuple area,*/ out HTuple roundness, out HTuple numHoles, out HTuple diameter)
            {
                //area = new HTuple();
                roundness = new HTuple();
                numHoles  = new HTuple();
                diameter  = new HTuple();
                region    = new HObject();

                try
                {
                    HTuple absoluteHisto, relativeHisto, minThresh, maxThresh;
                    HTuple distance, sigma, /*roundness,*/ sides, row, column;

                    HOperatorSet.GrayHisto(image, image, out absoluteHisto, out relativeHisto);
                    HOperatorSet.HistoToThresh(relativeHisto, 8, out minThresh, out maxThresh);

                    HTuple threshMax = maxThresh[maxThresh.Length - 2];

                    for (int i = maxThresh.Length - 3; threshMax > 160 && i >= 0; i--)
                    {
                        threshMax = maxThresh[i];
                    }

                    threshMax = threshMax.I < 140 ? 140 : threshMax.I;

                    HTuple numConnected, /*numHoles,*/ row1, column1, row2, column2 /*, diameter*/, area, indices;

                    HOperatorSet.Threshold(image, out region, minThresh[0], threshMax);

                    HObject connectedRegions;
                    HOperatorSet.Connection(region, out connectedRegions);
                    HOperatorSet.AreaCenter(connectedRegions, out area, out row, out column);

                    HOperatorSet.TupleSortIndex(area, out indices);
                    HOperatorSet.TupleInverse(indices, out indices);
                    HOperatorSet.SelectObj(connectedRegions, out region, indices[0] + 1);


                    HOperatorSet.ConnectAndHoles(region, out numConnected, out numHoles);
                    HOperatorSet.DiameterRegion(region, out row1, out column1, out row2, out column2, out diameter);
                    HOperatorSet.Roundness(region, out distance, out sigma, out roundness, out sides);
                    //HOperatorSet.AreaCenter(region, out area, out row, out column);
                }
                catch (Exception e)
                {
                    Log.Show($"{e}");
                }
            }
Exemple #39
0
    // Procedures
    public void GetRegionByBinaryThresholdRect(HObject ho_Image, out HObject ho_FoundRegion,
                                               HTuple hv_MeanMaskWidth, HTuple hv_MeanMaskHeight, HTuple hv_ScaleAdd, HTuple hv_LightDark,
                                               HTuple hv_AreaMin, HTuple hv_AreaMax, HTuple hv_OpeningWidth, HTuple hv_OpeningHeight,
                                               HTuple hv_ClosingWidth, HTuple hv_ClosingHeight, HTuple hv_DilationRadius)
    {
        // Stack for temporary objects
        HObject[] OTemp = new HObject[20];

        // Local iconic variables

        HObject ho_Domain, ho_ImageMean, ho_ImageScaled = null;
        HObject ho_Regions, ho_ConnectedRegions, ho_SelectedRegions;
        HObject ho_RegionFillUp, ho_RegionUnion;

        // Local control variables

        HTuple hv_Value = null, hv_UsedThreshold = null;

        // Initialize local and output iconic variables
        HOperatorSet.GenEmptyObj(out ho_FoundRegion);
        HOperatorSet.GenEmptyObj(out ho_Domain);
        HOperatorSet.GenEmptyObj(out ho_ImageMean);
        HOperatorSet.GenEmptyObj(out ho_ImageScaled);
        HOperatorSet.GenEmptyObj(out ho_Regions);
        HOperatorSet.GenEmptyObj(out ho_ConnectedRegions);
        HOperatorSet.GenEmptyObj(out ho_SelectedRegions);
        HOperatorSet.GenEmptyObj(out ho_RegionFillUp);
        HOperatorSet.GenEmptyObj(out ho_RegionUnion);
        ho_Domain.Dispose();
        HOperatorSet.GetDomain(ho_Image, out ho_Domain);

        ho_ImageMean.Dispose();
        HOperatorSet.MeanImage(ho_Image, out ho_ImageMean, hv_MeanMaskWidth, hv_MeanMaskHeight);

        HOperatorSet.GrayFeatures(ho_Domain, ho_ImageMean, "mean", out hv_Value);

        if ((int)(new HTuple(hv_LightDark.TupleEqual("light"))) != 0)
        {
            ho_ImageScaled.Dispose();
            HOperatorSet.ScaleImage(ho_ImageMean, out ho_ImageScaled, 1, (255 - hv_Value) + hv_ScaleAdd);
        }
        else if ((int)(new HTuple(hv_LightDark.TupleEqual("dark"))) != 0)
        {
            ho_ImageScaled.Dispose();
            HOperatorSet.ScaleImage(ho_ImageMean, out ho_ImageScaled, 1, (-hv_Value) + hv_ScaleAdd);
        }

        ho_Regions.Dispose();
        HOperatorSet.BinaryThreshold(ho_ImageScaled, out ho_Regions, "max_separability",
                                     hv_LightDark, out hv_UsedThreshold);
        ho_ConnectedRegions.Dispose();
        HOperatorSet.Connection(ho_Regions, out ho_ConnectedRegions);
        ho_SelectedRegions.Dispose();
        HOperatorSet.SelectShape(ho_ConnectedRegions, out ho_SelectedRegions, "area",
                                 "and", hv_AreaMin, hv_AreaMax);
        ho_RegionFillUp.Dispose();
        HOperatorSet.FillUp(ho_SelectedRegions, out ho_RegionFillUp);

        if ((int)((new HTuple(hv_OpeningWidth.TupleGreater(0))).TupleAnd(new HTuple(hv_OpeningHeight.TupleGreater(
                                                                                        0)))) != 0)
        {
            {
                HObject ExpTmpOutVar_0;
                HOperatorSet.OpeningRectangle1(ho_RegionFillUp, out ExpTmpOutVar_0, hv_OpeningWidth,
                                               hv_OpeningHeight);
                ho_RegionFillUp.Dispose();
                ho_RegionFillUp = ExpTmpOutVar_0;
            }
        }

        if ((int)((new HTuple(hv_ClosingWidth.TupleGreater(0))).TupleAnd(new HTuple(hv_ClosingHeight.TupleGreater(
                                                                                        0)))) != 0)
        {
            {
                HObject ExpTmpOutVar_0;
                HOperatorSet.ClosingRectangle1(ho_RegionFillUp, out ExpTmpOutVar_0, hv_ClosingWidth,
                                               hv_ClosingHeight);
                ho_RegionFillUp.Dispose();
                ho_RegionFillUp = ExpTmpOutVar_0;
            }
        }

        if ((int)(new HTuple(hv_DilationRadius.TupleGreater(0))) != 0)
        {
            {
                HObject ExpTmpOutVar_0;
                HOperatorSet.DilationCircle(ho_RegionFillUp, out ExpTmpOutVar_0, hv_DilationRadius);
                ho_RegionFillUp.Dispose();
                ho_RegionFillUp = ExpTmpOutVar_0;
            }
        }

        ho_RegionUnion.Dispose();
        HOperatorSet.Union1(ho_RegionFillUp, out ho_RegionUnion);
        ho_FoundRegion.Dispose();
        HOperatorSet.MoveRegion(ho_RegionUnion, out ho_FoundRegion, 0, 0);

        ho_Domain.Dispose();
        ho_ImageMean.Dispose();
        ho_ImageScaled.Dispose();
        ho_Regions.Dispose();
        ho_ConnectedRegions.Dispose();
        ho_SelectedRegions.Dispose();
        ho_RegionFillUp.Dispose();
        ho_RegionUnion.Dispose();

        return;
    }
 public void RunHalcon(HTuple Window)
 {
     hv_ExpDefaultWinHandle = Window;
     action();
 }
    // Main procedure
    private void action()
    {
        // Local iconic variables

        HObject ho_Image = null, ho_ImageMean = null, ho_Regions1 = null;
        HObject ho_RegionFillUp = null, ho_ConnectedRegions1 = null;
        HObject ho_SelectedRegions = null, ho_RegionErosion = null;
        HObject ho_RegionDifference = null, ho_ImageReduced = null;
        HObject ho_Regions = null, ho_ConnectedRegions = null, ho_SelectedRegions1 = null;
        HObject ho_RegionDilation = null, ho_RegionFillUp1 = null, ho_SelectedRegions2 = null;
        HObject ho_RegionUnion = null, ho_Rectangle = null;

        // Local control variables

        HTuple hv_Index = null, hv_WindowHandle = new HTuple();
        HTuple hv_Area = new HTuple(), hv_Row = new HTuple(), hv_Column = new HTuple();
        HTuple hv_Area1 = new HTuple(), hv_Row1 = new HTuple();
        HTuple hv_Column1 = new HTuple(), hv_angles = new HTuple();
        HTuple hv_rectangles = new HTuple(), hv_index = new HTuple();
        HTuple hv_offset = new HTuple(), hv_Angle = new HTuple();
        HTuple hv_deltaRow = new HTuple(), hv_deltaColumn = new HTuple();
        HTuple hv_rectRow = new HTuple(), hv_rectColumn = new HTuple();
        HTuple hv_Indices = new HTuple(), hv_Sum = null;

        // Initialize local and output iconic variables
        HOperatorSet.GenEmptyObj(out ho_Image);
        HOperatorSet.GenEmptyObj(out ho_ImageMean);
        HOperatorSet.GenEmptyObj(out ho_Regions1);
        HOperatorSet.GenEmptyObj(out ho_RegionFillUp);
        HOperatorSet.GenEmptyObj(out ho_ConnectedRegions1);
        HOperatorSet.GenEmptyObj(out ho_SelectedRegions);
        HOperatorSet.GenEmptyObj(out ho_RegionErosion);
        HOperatorSet.GenEmptyObj(out ho_RegionDifference);
        HOperatorSet.GenEmptyObj(out ho_ImageReduced);
        HOperatorSet.GenEmptyObj(out ho_Regions);
        HOperatorSet.GenEmptyObj(out ho_ConnectedRegions);
        HOperatorSet.GenEmptyObj(out ho_SelectedRegions1);
        HOperatorSet.GenEmptyObj(out ho_RegionDilation);
        HOperatorSet.GenEmptyObj(out ho_RegionFillUp1);
        HOperatorSet.GenEmptyObj(out ho_SelectedRegions2);
        HOperatorSet.GenEmptyObj(out ho_RegionUnion);
        HOperatorSet.GenEmptyObj(out ho_Rectangle);
        //read_image (PicBlockid18773, 'C:/Users/sunru/Documents/WeChat Files/sunrh109989/FileStorage/File/2019-08/190808 五金件检测(1)/190808 五金件检测/1/2.bmp')
        for (hv_Index = 10; (int)hv_Index <= 10; hv_Index = (int)hv_Index + 1)
        {
            ho_Image.Dispose();
            HOperatorSet.ReadImage(out ho_Image, ("C:/Users/sunru/Documents/WeChat Files/sunrh109989/FileStorage/File/2019-08/190809/190809/2/" + hv_Index) + ".bmp");
            //dev_close_window(...);
            dev_open_window_fit_image(ho_Image, 0, 0, -1, -1, out hv_WindowHandle);
            ho_ImageMean.Dispose();
            HOperatorSet.MeanImage(ho_Image, out ho_ImageMean, 19, 19);

            //select region
            HOperatorSet.SetColor(hv_ExpDefaultWinHandle, "red");
            ho_Regions1.Dispose();
            HOperatorSet.Threshold(ho_ImageMean, out ho_Regions1, 160, 250);
            ho_RegionFillUp.Dispose();
            HOperatorSet.FillUp(ho_Regions1, out ho_RegionFillUp);
            ho_ConnectedRegions1.Dispose();
            HOperatorSet.Connection(ho_RegionFillUp, out ho_ConnectedRegions1);
            ho_SelectedRegions.Dispose();
            HOperatorSet.SelectShapeStd(ho_ConnectedRegions1, out ho_SelectedRegions, "max_area",
                                        70);
            ho_RegionErosion.Dispose();
            HOperatorSet.ErosionCircle(ho_SelectedRegions, out ho_RegionErosion, 400);
            ho_RegionDifference.Dispose();
            HOperatorSet.Difference(ho_SelectedRegions, ho_RegionErosion, out ho_RegionDifference
                                    );


            ho_ImageReduced.Dispose();
            HOperatorSet.ReduceDomain(ho_ImageMean, ho_RegionDifference, out ho_ImageReduced
                                      );



            ho_Regions.Dispose();
            HOperatorSet.Threshold(ho_ImageReduced, out ho_Regions, 13, 150);
            ho_ConnectedRegions.Dispose();
            HOperatorSet.Connection(ho_Regions, out ho_ConnectedRegions);


            ho_SelectedRegions1.Dispose();
            HOperatorSet.SelectShape(ho_ConnectedRegions, out ho_SelectedRegions1, "outer_radius",
                                     "and", 20.18, 122.94);
            ho_RegionDilation.Dispose();
            HOperatorSet.DilationCircle(ho_SelectedRegions1, out ho_RegionDilation, 20);
            ho_RegionFillUp1.Dispose();
            HOperatorSet.FillUp(ho_RegionDilation, out ho_RegionFillUp1);

            ho_SelectedRegions2.Dispose();
            HOperatorSet.SelectShape(ho_RegionFillUp1, out ho_SelectedRegions2, (new HTuple("circularity")).TupleConcat(
                                         "area"), "and", (new HTuple(0.78073)).TupleConcat(10963.3), (new HTuple(1)).TupleConcat(
                                         31697.3));


            HOperatorSet.AreaCenter(ho_SelectedRegions2, out hv_Area, out hv_Row, out hv_Column);
            HOperatorSet.SetColor(hv_ExpDefaultWinHandle, "green");
            HOperatorSet.DispCross(hv_ExpDefaultWinHandle, hv_Row, hv_Column, 86, 0);

            HOperatorSet.SetColor(hv_ExpDefaultWinHandle, "red");
            //Find the center of whole region
            ho_RegionUnion.Dispose();
            HOperatorSet.Union1(ho_SelectedRegions2, out ho_RegionUnion);
            HOperatorSet.AreaCenter(ho_RegionUnion, out hv_Area1, out hv_Row1, out hv_Column1);
            HOperatorSet.DispCross(hv_ExpDefaultWinHandle, hv_Row1, hv_Column1, 86, 0);
            hv_angles     = new HTuple();
            hv_rectangles = new HTuple();
            HOperatorSet.SetColor(hv_ExpDefaultWinHandle, "green");
            for (hv_index = 0; (int)hv_index <= 5; hv_index = (int)hv_index + 1)
            {
                //index := 0
                hv_offset = 0.7;

                HOperatorSet.AngleLx(hv_Row.TupleSelect(hv_index), hv_Column.TupleSelect(
                                         hv_index), hv_Row1, hv_Column1, out hv_Angle);
                hv_angles      = hv_angles.TupleConcat(hv_Angle);
                hv_deltaRow    = (hv_Row.TupleSelect(hv_index)) - hv_Row1;
                hv_deltaColumn = (hv_Column.TupleSelect(hv_index)) - hv_Column1;
                hv_rectRow     = (hv_offset * hv_deltaRow) + hv_Row1;
                hv_rectColumn  = (hv_offset * hv_deltaColumn) + hv_Column1;
                HOperatorSet.DispCross(hv_ExpDefaultWinHandle, hv_rectRow, hv_rectColumn,
                                       86, hv_Angle);

                //gen measure rectangle
                ho_Rectangle.Dispose();
                HOperatorSet.GenRectangle2(out ho_Rectangle, hv_rectRow, hv_rectColumn, hv_Angle,
                                           60, 150);

                hv_rectangles = ((((((hv_rectangles.TupleConcat(hv_rectRow))).TupleConcat(
                                        hv_rectColumn))).TupleConcat(hv_Angle))).TupleConcat((new HTuple(60)).TupleConcat(
                                                                                                 150));
            }

            //sort
            HOperatorSet.TupleSortIndex(hv_angles, out hv_Indices);
            HDevelopStop();
        }

        HOperatorSet.TupleAdd(hv_Indices, 1, out hv_Sum);


        ho_Image.Dispose();
        ho_ImageMean.Dispose();
        ho_Regions1.Dispose();
        ho_RegionFillUp.Dispose();
        ho_ConnectedRegions1.Dispose();
        ho_SelectedRegions.Dispose();
        ho_RegionErosion.Dispose();
        ho_RegionDifference.Dispose();
        ho_ImageReduced.Dispose();
        ho_Regions.Dispose();
        ho_ConnectedRegions.Dispose();
        ho_SelectedRegions1.Dispose();
        ho_RegionDilation.Dispose();
        ho_RegionFillUp1.Dispose();
        ho_SelectedRegions2.Dispose();
        ho_RegionUnion.Dispose();
        ho_Rectangle.Dispose();
    }
    // Main procedure
    private void action()
    {
        // Stack for temporary objects
        HObject[] OTemp = new HObject[20];

        // Local iconic variables

        HObject ho_Image = null, ho_SymbolXLDs = null;
        HObject ho_SymbolRegions = null, ho_ObjectSelected = null;

        // Local control variables

        HTuple hv_BarWidth = new HTuple(), hv_BarHeight = new HTuple();
        HTuple hv_DataCodeHandle = new HTuple(), hv_BarCodeHandle = new HTuple();
        HTuple hv_WindowHandle = new HTuple(), hv_AcqHandle = new HTuple();
        HTuple hv_ResultHandles = new HTuple(), hv_DecodedDataStrings = new HTuple();
        HTuple hv_someitem = new HTuple(), hv_Area = new HTuple();
        HTuple hv_BarIndex = new HTuple(), hv_Row = new HTuple();
        HTuple hv_Column = new HTuple(), hv_Exception = new HTuple();

        // Initialize local and output iconic variables
        HOperatorSet.GenEmptyObj(out ho_Image);
        HOperatorSet.GenEmptyObj(out ho_SymbolXLDs);
        HOperatorSet.GenEmptyObj(out ho_SymbolRegions);
        HOperatorSet.GenEmptyObj(out ho_ObjectSelected);
        try
        {
            //***
            //** INIT
            //* INIT CONST
            hv_BarWidth.Dispose();
            hv_BarWidth = 800;
            hv_BarHeight.Dispose();
            hv_BarHeight = 100;
            //* INIT IMAGE
            //* INIT DATACODE
            hv_DataCodeHandle.Dispose();
            HOperatorSet.CreateDataCode2dModel("Data Matrix ECC 200", new HTuple(), new HTuple(),
                                               out hv_DataCodeHandle);

            //* INIT BARCODE
            hv_BarCodeHandle.Dispose();
            HOperatorSet.CreateBarCodeModel(new HTuple(), new HTuple(), out hv_BarCodeHandle);
            HOperatorSet.SetBarCodeParam(hv_BarCodeHandle, "quiet_zone", "true");
            //* INIT LOC
            //* Info:
            //read_shape_model ('C:/Users/iwake/OneDrive - wake/Desktop/Localization/InvV1CaliInfo.shm', InfoModel)
            //get_shape_model_contours (InfoModelContours, InfoModel, 1)
            //* Sign
            //read_shape_model ('C:/Users/iwake/OneDrive - wake/Desktop/Localization/InvV1CaliSign.shm', SignModel)
            //get_shape_model_contours (SignModelContours, SignModel, 1)
            //***
            //** DISPLAY
            //* DISPLAY INIT
            hDevelo.dev_update_off();
            if (HDevWindowStack.IsOpen())
            {
                HOperatorSet.CloseWindow(HDevWindowStack.Pop());
            }
            HOperatorSet.SetWindowAttr("background_color", "black");
            //HOperatorSet.OpenWindow(30, 0, 800, 1500, 0, "visible", "", out hv_WindowHandle);
            HDevWindowStack.Push(hv_ExpDefaultWinHandle);


            //***
            //** LOOP
            //Image Acquisition 01: Code generated by Image Acquisition 01
            hv_AcqHandle.Dispose();
            hv_AcqHandle = acqHandle;
            while ((int)(1) != 0)
            {
                ho_Image.Dispose();
                HOperatorSet.GrabImage(out ho_Image, hv_AcqHandle);
                {
                    HObject ExpTmpOutVar_0;
                    hDevelo.image_cali_map(ho_Image, out ExpTmpOutVar_0, new HTuple(), new HTuple());
                    ho_Image.Dispose();
                    ho_Image = ExpTmpOutVar_0;
                    HOperatorSet.DispObj(ho_Image, hv_ExpImageRawWinHandle);
                }
                try
                {
                    //** PRE
                    //find_shape_model (Image, SignModel, rad(0), rad(360), 0.3, 1, 0.5, 'least_squares', [7,1], 0.6, InfoRow, InfoColumn, InfoAngle, InfoScore)
                    //rotate_image (Image, Image, deg(-InfoAngle), 'constant')
                    if (HDevWindowStack.IsOpen())
                    {
                        HOperatorSet.DispObj(ho_Image, HDevWindowStack.GetActive());
                    }
                    //** RECOGNITION
                    //* DataCode
                    ho_SymbolXLDs.Dispose(); hv_ResultHandles.Dispose(); hv_DecodedDataStrings.Dispose();
                    HOperatorSet.FindDataCode2d(ho_Image, out ho_SymbolXLDs, hv_DataCodeHandle,
                                                "stop_after_result_num", 3, out hv_ResultHandles, out hv_DecodedDataStrings);
                    hDevelo.image_display_datacode(ho_SymbolXLDs, hv_ResultHandles, hv_WindowHandle,
                                                   hv_DecodedDataStrings, hv_DataCodeHandle);
                    //* BARCODE
                    ho_SymbolRegions.Dispose(); hv_DecodedDataStrings.Dispose(); hv_someitem.Dispose();
                    hDevelo.image_get_bar(ho_Image, out ho_SymbolRegions, hv_BarCodeHandle, out hv_DecodedDataStrings,
                                          out hv_someitem);
                    //* LOC
                    //* Info:
                    //find_shape_model (Image, InfoModel, rad(0), rad(360), 0.3, 1, 0.5, 'least_squares', [7,1], 0.7, InfoRow, InfoColumn, InfoAngle, InfoScore)
                    //* HaedSign
                    //find_shape_model (Image, SignModel, rad(0), rad(360), 0.3, 1, 0.5, 'least_squares', [7,1], 0.7, SignRow, SignColumn, SignAngle, SignScore)
                    //* Ocr
                    //gen_rectangle2 (ROI_OCR_01_0, InfoRow + 70, InfoColumn - 700, InfoAngle, 100, 30)
                    //region_ocr_num_svm (Image, ROI_OCR_01_0, [], [], SymbolNames_OCR_01_0, Ocr_Split)
                    //area_center (ROI_OCR_01_0, Area, IDRow, IDColumn)
                    //smallest_rectangle1 (ROI_OCR_01_0, IDRow1, IDColumn1, IDRow2, IDColumn2)
                    //height_width_ratio (ROI_OCR_01_0, IDHeight, IDWidth, IDRatio)
                    //* Sign
                    //HeadSignScale := 1
                    //HeadSignRow := SignRow
                    //HeadSignCol := SignColumn
                    //HeadPhi := SignAngle
                    //region_judge_sign (Image, EDGE, HeadSignScale, HeadSignRow, HeadSignCol, HeadPhi, WindowHandle, sign)
                    //** DISPLAY
                    //* DISPLAY BARCODE
                    hDevelo.set_display_font(hv_WindowHandle, 14, "mono", "true", "false");
                    if (HDevWindowStack.IsOpen())
                    {
                        HOperatorSet.SetDraw(HDevWindowStack.GetActive(), "margin");
                    }
                    if (HDevWindowStack.IsOpen())
                    {
                        HOperatorSet.SetLineWidth(HDevWindowStack.GetActive(), 3);
                    }
                    if (HDevWindowStack.IsOpen())
                    {
                        HOperatorSet.SetColor(HDevWindowStack.GetActive(), "forest green");
                    }
                    if (HDevWindowStack.IsOpen())
                    {
                        HOperatorSet.DispObj(ho_SymbolRegions, HDevWindowStack.GetActive());
                    }
                    for (hv_BarIndex = 1; (int)hv_BarIndex <= (int)(new HTuple(hv_DecodedDataStrings.TupleLength()
                                                                               )); hv_BarIndex = (int)hv_BarIndex + 1)
                    {
                        ho_ObjectSelected.Dispose();
                        HOperatorSet.SelectObj(ho_SymbolRegions, out ho_ObjectSelected, hv_BarIndex);
                        hv_Area.Dispose(); hv_Row.Dispose(); hv_Column.Dispose();
                        HOperatorSet.AreaCenter(ho_ObjectSelected, out hv_Area, out hv_Row, out hv_Column);
                        using (HDevDisposeHelper dh = new HDevDisposeHelper())
                        {
                            HOperatorSet.SetTposition(hv_WindowHandle, hv_Row - hv_BarHeight, hv_Column - (0.25 * hv_BarWidth));
                        }
                        using (HDevDisposeHelper dh = new HDevDisposeHelper())
                        {
                            HOperatorSet.WriteString(hv_WindowHandle, hv_DecodedDataStrings.TupleSelect(
                                                         hv_BarIndex - 1));
                        }
                    }
                    //* DISPLAY LOC
                    if (HDevWindowStack.IsOpen())
                    {
                        HOperatorSet.SetLineWidth(HDevWindowStack.GetActive(), 1);
                    }
                    //* Info:
                    //hom_mat2d_identity (InfoHomMat2D)
                    //hom_mat2d_rotate (InfoHomMat2D, InfoAngle, 0, 0, InfoHomMat2D)
                    //hom_mat2d_translate (InfoHomMat2D, InfoRow, InfoColumn, InfoHomMat2D)
                    //affine_trans_contour_xld (InfoModelContours, InfoTransContours, InfoHomMat2D)
                    if (HDevWindowStack.IsOpen())
                    {
                        //dev_set_color ('green')
                    }
                    if (HDevWindowStack.IsOpen())
                    {
                        //dev_display (InfoTransContours)
                    }
                    //* Ocr
                    if (HDevWindowStack.IsOpen())
                    {
                        //dev_disp_text (Ocr_Split, 'image', IDRow1 + IDHeight, IDColumn1, 'blue', [], [])
                    }
                    //* HeadSign
                    //hom_mat2d_identity (SignHomMat2D)
                    //hom_mat2d_rotate (SignHomMat2D, SignAngle, 0, 0, SignHomMat2D)
                    //hom_mat2d_translate (SignHomMat2D, SignRow, SignColumn, SignHomMat2D)
                    //affine_trans_contour_xld (SignModelContours, SignTransContours, SignHomMat2D)
                    if (HDevWindowStack.IsOpen())
                    {
                        //dev_set_color ('green')
                    }
                    if (HDevWindowStack.IsOpen())
                    {
                        //dev_display (SignTransContours)
                    }
                    //* Sign
                    if (HDevWindowStack.IsOpen())
                    {
                        //dev_set_colored (12)
                    }
                    if (HDevWindowStack.IsOpen())
                    {
                        //dev_display (EDGE)
                    }
                    //dump_window_image (ImageResult, WindowHandle)

                    //stop ()
                }
                // catch (Exception)
                catch (HalconException HDevExpDefaultException1)
                {
                    HDevExpDefaultException1.ToHTuple(out hv_Exception);
                }
            }
            HOperatorSet.CloseFramegrabber(hv_AcqHandle);
        }
        catch (HalconException HDevExpDefaultException)
        {
            ho_Image.Dispose();
            ho_SymbolXLDs.Dispose();
            ho_SymbolRegions.Dispose();
            ho_ObjectSelected.Dispose();

            hv_BarWidth.Dispose();
            hv_BarHeight.Dispose();
            hv_DataCodeHandle.Dispose();
            hv_BarCodeHandle.Dispose();
            hv_WindowHandle.Dispose();
            hv_AcqHandle.Dispose();
            hv_ResultHandles.Dispose();
            hv_DecodedDataStrings.Dispose();
            hv_someitem.Dispose();
            hv_Area.Dispose();
            hv_BarIndex.Dispose();
            hv_Row.Dispose();
            hv_Column.Dispose();
            hv_Exception.Dispose();

            throw HDevExpDefaultException;
        }
        ho_Image.Dispose();
        ho_SymbolXLDs.Dispose();
        ho_SymbolRegions.Dispose();
        ho_ObjectSelected.Dispose();

        hv_BarWidth.Dispose();
        hv_BarHeight.Dispose();
        hv_DataCodeHandle.Dispose();
        hv_BarCodeHandle.Dispose();
        hv_WindowHandle.Dispose();
        hv_AcqHandle.Dispose();
        hv_ResultHandles.Dispose();
        hv_DecodedDataStrings.Dispose();
        hv_someitem.Dispose();
        hv_Area.Dispose();
        hv_BarIndex.Dispose();
        hv_Row.Dispose();
        hv_Column.Dispose();
        hv_Exception.Dispose();
    }
Exemple #43
0
 /// <summary>
 /// Triggers an update of the measure object for all
 /// changes concerning the shape of the ROI or the measurement
 /// parameters.
 /// </summary>
 public void UpdateROI()
 {
     mROICoord = mRoi.getModelData();
     UpdateMeasure();
 }
            public void MeasureCircle(HObject image, double row, double column, double radian, out HTuple diameterMax, out HTuple diameterMin,
                                      out HTuple disLeft, out HTuple disRight, out HTuple edgeRow, out HTuple edgeColumn, out HObject contour)
            {
                diameterMax = new HTuple(999);
                diameterMin = new HTuple(999);
                disLeft     = new HTuple(999);
                disRight    = new HTuple(999);
                edgeRow     = new HTuple(999);
                edgeColumn  = new HTuple(999);

                HOperatorSet.GenEmptyObj(out contour);

                try
                {
                    //平移测量对象
                    HOperatorSet.TranslateMeasure(Handle1, row, column);
                    HOperatorSet.TranslateMeasure(Handle2, row, column);

                    //测量矩形中点
                    HObject cross;
                    HOperatorSet.GenCrossContourXld(out cross, row, column, 5, radian);
                    HOperatorSet.ConcatObj(contour, cross, out contour);

                    //HTuple leftRow, leftCol, topRow, topCol, rightRow, rightCol, bottomRow, bottomCol;
                    HTuple centerRow = null, centerCol = null;

                    HTuple rowEdgeFirst     = new HTuple();
                    HTuple columnEdgeFirst  = new HTuple();
                    HTuple amplitudeFirst   = new HTuple();
                    HTuple rowEdgeSecond    = new HTuple();
                    HTuple columnEdgeSecond = new HTuple();
                    HTuple amplitudeSecond  = new HTuple();
                    HTuple intraDistance    = new HTuple();
                    HTuple interDistance    = new HTuple();

                    //左右测量边缘对
                    for (int i = 0; i <= 5; i++)
                    {
                        HTuple threshold = Threshold - i * 2;
                        if (threshold < 1)
                        {
                            threshold = 1;
                        }

                        HOperatorSet.MeasurePairs(image, Handle1, Sigma, threshold, "all", "all",
                                                  out rowEdgeFirst, out columnEdgeFirst, out amplitudeFirst,
                                                  out rowEdgeSecond, out columnEdgeSecond, out amplitudeSecond,
                                                  out intraDistance, out interDistance);

                        if (intraDistance.Length >= 2)
                        {
                            break;
                        }
                    }

                    if (intraDistance.Length >= 2)
                    {
                        diameterMax = interDistance[0];
                        disLeft     = intraDistance[0];
                        disRight    = intraDistance[1];


                        //centerRow = (rowEdgeSecond[0] + rowEdgeFirst[1]) / 2;
                        centerCol = (columnEdgeSecond[0] + columnEdgeFirst[1]) / 2;
                    }

                    //显示
                    for (int j = 0; j < rowEdgeFirst.Length; j++)
                    {
                        HTuple rowEdgeFirstBegin;
                        HTuple rowEdgeFirstEnd;
                        HTuple rowEdgeSecondBegin;
                        HTuple rowEdgeSecondEnd;
                        HOperatorSet.TupleAdd(rowEdgeFirst, Height / 2, out rowEdgeFirstBegin);
                        HOperatorSet.TupleSub(rowEdgeFirst, Height / 2, out rowEdgeFirstEnd);

                        HOperatorSet.TupleAdd(rowEdgeSecond, Height / 2, out rowEdgeSecondBegin);
                        HOperatorSet.TupleSub(rowEdgeSecond, Height / 2, out rowEdgeSecondEnd);

                        HTuple columnEdgeFirstBegin  = new HTuple();
                        HTuple columnEdgeFirstEnd    = new HTuple();
                        HTuple columnEdgeSecondBegin = new HTuple();
                        HTuple columnEdgeSecondEnd   = new HTuple();

                        HTuple homMat2D;
                        HTuple rowBegin1;
                        HTuple columnBegin1;
                        HTuple rowEnd1;
                        HTuple columnEnd1;
                        HTuple rowBegin2;
                        HTuple columnBegin2;
                        HTuple rowEnd2;
                        HTuple columnEnd2;

                        HObject lineFirst;

                        HOperatorSet.HomMat2dIdentity(out homMat2D);
                        HOperatorSet.HomMat2dRotate(homMat2D, radian, rowEdgeFirst[j], columnEdgeFirst[j], out homMat2D);
                        HOperatorSet.AffineTransPixel(homMat2D, rowEdgeFirstBegin[j], columnEdgeFirst[j], out rowBegin1, out columnBegin1);
                        HOperatorSet.AffineTransPixel(homMat2D, rowEdgeFirstEnd[j], columnEdgeFirst[j], out rowEnd1, out columnEnd1);

                        HOperatorSet.HomMat2dIdentity(out homMat2D);
                        HOperatorSet.HomMat2dRotate(homMat2D, radian, rowEdgeSecond[j], columnEdgeSecond[j], out homMat2D);
                        HOperatorSet.AffineTransPixel(homMat2D, rowEdgeSecondBegin[j], columnEdgeSecond[j], out rowBegin2, out columnBegin2);
                        HOperatorSet.AffineTransPixel(homMat2D, rowEdgeSecondEnd[j], columnEdgeSecond[j], out rowEnd2, out columnEnd2);

                        HOperatorSet.GenContourPolygonXld(out lineFirst,
                                                          new HTuple(rowBegin1, rowEnd1, rowEnd2, rowBegin2, rowBegin1),
                                                          new HTuple(columnBegin1, columnEnd1, columnEnd2, columnBegin2, columnBegin1));

                        HOperatorSet.ConcatObj(contour, lineFirst, out contour);
                    }

                    //测量碳点垂直方向直径
                    for (int i = 0; i <= 5; i++)
                    {
                        HTuple threshold = Threshold - i * 2;
                        if (threshold < 1)
                        {
                            threshold = 1;
                        }

                        HOperatorSet.MeasurePairs(image, Handle2, Sigma, threshold, "negative", "all",
                                                  out rowEdgeFirst, out columnEdgeFirst, out amplitudeFirst,
                                                  out rowEdgeSecond, out columnEdgeSecond, out amplitudeSecond,
                                                  out intraDistance, out interDistance);

                        if (intraDistance.Length >= 1)
                        {
                            break;
                        }
                    }

                    //获得结果,当没有测量到边缘对
                    if (intraDistance.Length < 1)
                    {
                        diameterMin = diameterMax;

                        edgeRow    = 0;
                        edgeColumn = 0;
                    }

                    //测量到边缘对
                    if (intraDistance.Length >= 1)
                    {
                        if (diameterMax.D == 999)
                        {
                            diameterMin = intraDistance[0];
                            diameterMax = intraDistance[0];

                            centerCol = (columnEdgeSecond[0] + columnEdgeFirst[0]) / 2;
                        }
                        else
                        {
                            if (intraDistance[0] < diameterMax)
                            {
                                diameterMin = intraDistance[0];
                            }
                            else
                            {
                                diameterMin = diameterMax[0];
                                diameterMax = intraDistance[0];
                            }
                        }

                        centerRow = (rowEdgeSecond[0] + rowEdgeFirst[0]) / 2;

                        edgeRow    = rowEdgeSecond[0];
                        edgeColumn = columnEdgeSecond[0];
                    }

                    //显示
                    if (intraDistance.Length > 0)
                    {
                        HTuple columnEdgeFirstBegin, columnEdgeFirstEnd, columnEdgeSecondBegin, columnEdgeSecondEnd;
                        HTuple rowBegin1, columnBegin1, rowEnd1, columnEnd1, rowBegin2, columnBegin2, rowEnd2, columnEnd2;

                        HOperatorSet.TupleAdd(columnEdgeFirst, Width / 2, out columnEdgeFirstBegin);
                        HOperatorSet.TupleSub(columnEdgeFirst, Width / 2, out columnEdgeFirstEnd);

                        HOperatorSet.TupleAdd(columnEdgeSecond, Width / 2, out columnEdgeSecondBegin);
                        HOperatorSet.TupleSub(columnEdgeSecond, Width / 2, out columnEdgeSecondEnd);

                        for (int i = 0; i < intraDistance.Length; i++)
                        {
                            HTuple homMat2D;
                            HOperatorSet.HomMat2dIdentity(out homMat2D);
                            HOperatorSet.HomMat2dRotate(homMat2D, radian, rowEdgeFirst[i], columnEdgeFirst[i], out homMat2D);
                            HOperatorSet.AffineTransPixel(homMat2D, rowEdgeFirst[i], columnEdgeFirstBegin[i], out rowBegin1, out columnBegin1);
                            HOperatorSet.AffineTransPixel(homMat2D, rowEdgeFirst[i], columnEdgeFirstEnd[i], out rowEnd1, out columnEnd1);

                            HOperatorSet.HomMat2dIdentity(out homMat2D);
                            HOperatorSet.HomMat2dRotate(homMat2D, radian, rowEdgeSecond[i], columnEdgeSecond[i], out homMat2D);
                            HOperatorSet.AffineTransPixel(homMat2D, rowEdgeSecond[i], columnEdgeSecondBegin[i], out rowBegin2, out columnBegin2);
                            HOperatorSet.AffineTransPixel(homMat2D, rowEdgeSecond[i], columnEdgeSecondEnd[i], out rowEnd2, out columnEnd2);

                            HObject lineFirst;
                            HOperatorSet.GenContourPolygonXld(out lineFirst,
                                                              new HTuple(rowBegin1, rowEnd1, rowEnd2, rowBegin2, rowBegin1),
                                                              new HTuple(columnBegin1, columnEnd1, columnEnd2, columnBegin2, columnBegin1));

                            HOperatorSet.ConcatObj(contour, lineFirst, out contour);
                        }
                    }


                    if (diameterMax.D != 999 && disLeft.D != 999 && disRight.D != 999 &&
                        centerRow != null && centerCol != null)
                    {
                        HObject rect, imageReduced, region;
                        HTuple  numHoles, roundness, diameter;
                        HTuple  length = (int)(diameterMax.D / 2 + 5);
                        HOperatorSet.GenRectangle2(out rect, centerRow, centerCol, radian, length, length);
                        HOperatorSet.ReduceDomain(image, rect, out imageReduced);
                        MeasureRoundness(imageReduced, out region, out roundness, out numHoles, out diameter);

                        //if (roundness < 0.85 || numHoles > 0)
                        if (roundness < 0.9 || numHoles > 0)
                        {
                            diameterMax = 999;
                            //HOperatorSet.ConcatObj(contour, region, out contour);
                        }

                        //diameterMax = diameterMax > diameter ? diameterMax : diameter;
                    }
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
    public HTuple process_image(HObject ho_Image, out HObject ho_EdgeAmplitude, HTuple hv_WindowHandle,
                                HTuple hv_DrawID)
    {
        // Local iconic variables
        HObject ho_Region, ho_ImageReduced;

        // Initialize local and output iconic variables
        HOperatorSet.GenEmptyObj(out ho_EdgeAmplitude);
        HOperatorSet.GenEmptyObj(out ho_Region);
        HOperatorSet.GenEmptyObj(out ho_ImageReduced);
        HOperatorSet.GenEmptyObj(out ho_ModelContours);
        HOperatorSet.GenEmptyObj(out ho_TransContours);
        ho_TransContours.Dispose();
        try
        {
            //Apply an Sobel edge filter on the background
            //image within the region of interest defined
            //by the drawing object.
            ho_Region.Dispose();
            HOperatorSet.GetDrawingObjectIconic(out ho_Region, hv_DrawID);
            ho_ImageReduced.Dispose();
            ho_EdgeAmplitude.Dispose();
            HOperatorSet.ReduceDomain(ho_Image, ho_Region, out ho_EdgeAmplitude);

            try
            {
                HOperatorSet.CreateShapeModel(ho_EdgeAmplitude, 2, (new HTuple(0)).TupleRad(),
                                              (new HTuple(360)).TupleRad(), (new HTuple(6.2177)).TupleRad(), (new HTuple("none")).TupleConcat(
                                                  "no_pregeneration"), "use_polarity", ((new HTuple(10)).TupleConcat(13)).TupleConcat(4), 10, out hv_ModelId);
            }
            catch (Exception ex)
            {
                return(null);
            }
            try
            {
                ho_ModelContours.Dispose();
                HOperatorSet.GetShapeModelContours(out ho_ModelContours, hv_ModelId, 1);
            }
            catch (Exception ex)
            {
                return(null);
            }
            try
            {
                HOperatorSet.SetColor(hv_WindowHandle, "blue");
                HOperatorSet.SetLineWidth(hv_WindowHandle, 1);



                HOperatorSet.HomMat2dIdentity(out hv_HomMat);
                HOperatorSet.HomMat2dRotate(hv_HomMat, 0, 0, 0, out hv_HomMat);

                HOperatorSet.HomMat2dTranslate(hv_HomMat, 100, 100, out hv_HomMat);


                HOperatorSet.AffineTransContourXld(ho_ModelContours, out ho_TransContours, hv_HomMat);



                HOperatorSet.SetWindowParam(hv_WindowHandle, "flush", "false");
                HOperatorSet.ClearWindow(hv_WindowHandle);
                HOperatorSet.DispObj(ho_TransContours, hv_WindowHandle);
                HOperatorSet.SetWindowParam(hv_WindowHandle, "flush", "true");
                HOperatorSet.FlushBuffer(hv_WindowHandle);

                return(hv_ModelId);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return(null);
            }
            ho_Region.Dispose();
            ho_ImageReduced.Dispose();

            return(null);
        }
        catch (HalconException HDevExpDefaultException)
        {
            ho_Region.Dispose();
            ho_ImageReduced.Dispose();
            throw HDevExpDefaultException;
        }
    }
            public void MeasurePos(HObject image, HObject edgeContour)
            {
                //记录测量数量
                int meaCount = 0;

                try
                {
                    HTuple row    = CenterRow;
                    HTuple column = CenterColumn;
                    HTuple radian = Radian;

                    HTuple homMat2D, rowTrans, columnTrans;

                    /*
                     * HOperatorSet.HomMat2dIdentity(out homMat2D);
                     * HOperatorSet.HomMat2dTranslate(homMat2D, 0, PinDistance * PinCount / 2, out homMat2D);
                     * HOperatorSet.HomMat2dRotate(homMat2D, radian, row, column, out homMat2D);
                     * HOperatorSet.AffineTransPixel(homMat2D, row, column, out rowTrans, out columnTrans);
                     *
                     * HObject rect;
                     * HOperatorSet.GenRectangle2(out rect, rowTrans, columnTrans, radian, PinDistance * PinCount / 2 + Width, 100);
                     * HOperatorSet.ReduceDomain(image, rect, out image);
                     *
                     * HOperatorSet.AnisotropicDiffusion(image, out image, "weickert", 5, 1, 10);
                     * HOperatorSet.Emphasize(image, out image, 15, 15, 1);
                     *
                     * HOperatorSet.ConcatObj(LineEdge, image, out LineEdge);
                     */

                    //HTuple edgeRow1, edgeColumn1, edgeRow2, edgeColumn2;
                    //FindEdge(image, row, column, radian, out edgeRow1, out edgeColumn1, out edgeRow2, out edgeColumn2);
                    HOperatorSet.ConcatObj(LineEdge, edgeContour, out LineEdge);

                    //测量所有碳碳点
                    for (int i = 0; i < PinCount; i++)
                    {
                        //变换检测位置
                        //HTuple homMat2D, rowTrans, columnTrans;
                        HOperatorSet.HomMat2dIdentity(out homMat2D);
                        HOperatorSet.HomMat2dTranslate(homMat2D, 0, i * PinDistance, out homMat2D);
                        HOperatorSet.HomMat2dRotate(homMat2D, radian, row, column, out homMat2D);
                        HOperatorSet.AffineTransPixel(homMat2D, row, column, out rowTrans, out columnTrans);

                        //检测碳点
                        HObject contour;
                        HTuple  diameterMax, diameterMin, disLeft, disRight, edgeRow, edgeColumn;
                        MeasureCircle(image, rowTrans, columnTrans, radian, out diameterMax, out diameterMin, out disLeft, out disRight,
                                      out edgeRow, out edgeColumn, out contour);

                        //测量碳点到玻璃边缘的距离
                        HTuple disTop, distanceMax;
                        //HOperatorSet.DistancePl(edgeRow, edgeColumn, edgeRow1, edgeColumn1, edgeRow2, edgeColumn2, out disTop);
                        HOperatorSet.DistancePc(edgeContour, edgeRow, edgeColumn, out disTop, out distanceMax);


                        //像素转毫米
                        double maxDiameter = Math.Round((PlatformCalibData.PixelToMm(diameterMax) + MeasureMgr.GetInstance().OffsetDia), 2);
                        double minDiameter = Math.Round(PlatformCalibData.PixelToMm(diameterMin), 2);
                        double leftPos     = Math.Round(PlatformCalibData.PixelToMm(disLeft), 2);
                        double reghtPos    = Math.Round(PlatformCalibData.PixelToMm(disRight), 2);
                        double topPos      = Math.Round(PlatformCalibData.PixelToMm(disTop), 2);

                        //优先判断面积NG,后判断位置NG
                        double LimiteMax = PlatformCalibData.PixelToMm(PinDistance);
                        if (maxDiameter > LimiteDiameterMax || maxDiameter < LimiteDiameterMin)
                        {
                            HOperatorSet.ConcatObj(ContourAreaNG, contour, out ContourAreaNG);
                            CountAreaNG++;
                        }
                        else if (leftPos < LimiteLeft || leftPos > LimiteMax ||
                                 reghtPos < LimiteRight || reghtPos > LimiteMax ||
                                 topPos < LimiteTopMin || topPos > LimiteTopMax)
                        {
                            HOperatorSet.ConcatObj(ContourPosNG, contour, out ContourPosNG);
                            CountPosNG++;
                        }
                        else
                        {
                            HOperatorSet.ConcatObj(ContourOk, contour, out ContourOk);
                            CountOK++;
                        }

                        //添加到参数列表
                        DiameterMax.Append(maxDiameter);
                        DiameterMin.Append(minDiameter);
                        DisLeft.Append(leftPos);
                        DisRight.Append(reghtPos);
                        DisTop.Append(topPos);

                        //计数
                        meaCount++;
                    }
                }
                catch (Exception e)
                {
                    throw e;
                }
                finally
                {
                    //未测量完成计入面积NG
                    if (PinCount != meaCount)
                    {
                        CountAreaNG += PinCount - meaCount;
                    }
                }
            }
    public void SpokeCircle(HObject ho_Image, HTuple hv_ROICirCentre_Row, HTuple hv_ROICirCentre_Column,
                            HTuple hv_ROIBigCirRadius, HTuple hv_ROISmallCirRadius,
                            HTuple hv_Elements,
//        HTuple hv_DetectHeight ,
                            HTuple hv_DetectWidth,
                            HTuple hv_Sigma, HTuple hv_Threshold, HTuple hv_Transition, HTuple hv_Select,
                            HTuple hv_Direct, out HTuple hv_CirCentre_Row, out HTuple hv_CirCentre_Column,
                            out HTuple hv_CirRadius, out HTuple hv_CirRoundness)
    {
        // Local iconic variables

        HObject ho_Regions, ho_Circle, ho_Cross, ho_Region;


        // Local control variables

        HTuple
            hv_DetectHeight = null,
            hv_ROIRadius    = null;
        HTuple
//            hv_Elements = null,
            hv_ROIRows = null,
            hv_ROICols = null;
        HTuple hv_ResultRow = null, hv_ResultColumn = null, hv_ArcType = null;
        HTuple hv_Distance = null, hv_Sigma1 = null, hv_Sides = null;

        // Initialize local and output iconic variables
        HOperatorSet.GenEmptyObj(out ho_Regions);
        HOperatorSet.GenEmptyObj(out ho_Circle);
        HOperatorSet.GenEmptyObj(out ho_Cross);
        HOperatorSet.GenEmptyObj(out ho_Region);

        hv_DetectHeight = hv_ROIBigCirRadius - hv_ROISmallCirRadius;
        hv_ROIRadius    = hv_ROISmallCirRadius + (hv_DetectHeight / 2);
//        hv_Elements = ((2*3.1415926)*hv_ROIRadius)/hv_DetectWidth;
        hv_ROIRows = new HTuple();
        hv_ROICols = new HTuple();
        if (hv_ROIRows == null)
        {
            hv_ROIRows = new HTuple();
        }
        hv_ROIRows[0] = hv_ROICirCentre_Row;
        if (hv_ROICols == null)
        {
            hv_ROICols = new HTuple();
        }
        hv_ROICols[0] = hv_ROICirCentre_Column + hv_ROIRadius;
        if (hv_ROIRows == null)
        {
            hv_ROIRows = new HTuple();
        }
        hv_ROIRows[1] = hv_ROICirCentre_Row + hv_ROIRadius;
        if (hv_ROICols == null)
        {
            hv_ROICols = new HTuple();
        }
        hv_ROICols[1] = hv_ROICirCentre_Column;
        if (hv_ROIRows == null)
        {
            hv_ROIRows = new HTuple();
        }
        hv_ROIRows[2] = hv_ROICirCentre_Row;
        if (hv_ROICols == null)
        {
            hv_ROICols = new HTuple();
        }
        hv_ROICols[2] = hv_ROICirCentre_Column - hv_ROIRadius;
        if (hv_ROIRows == null)
        {
            hv_ROIRows = new HTuple();
        }
        hv_ROIRows[3] = hv_ROICirCentre_Row - hv_ROIRadius;
        if (hv_ROICols == null)
        {
            hv_ROICols = new HTuple();
        }
        hv_ROICols[3] = hv_ROICirCentre_Column;
        if (hv_ROIRows == null)
        {
            hv_ROIRows = new HTuple();
        }
        hv_ROIRows[4] = hv_ROICirCentre_Row;
        if (hv_ROICols == null)
        {
            hv_ROICols = new HTuple();
        }
        hv_ROICols[4] = hv_ROICirCentre_Column + hv_ROIRadius;
        ho_Regions.Dispose();
        spoke(ho_Image, out ho_Regions, hv_Elements, hv_DetectHeight, hv_DetectWidth,
              hv_Sigma, hv_Threshold, hv_Transition, hv_Select, hv_ROIRows, hv_ROICols,
              hv_Direct, out hv_ResultRow, out hv_ResultColumn, out hv_ArcType);
        ho_Circle.Dispose();
        pts_to_best_circle(out ho_Circle, hv_ResultRow, hv_ResultColumn, 3, "circle",
                           out hv_CirCentre_Row, out hv_CirCentre_Column, out hv_CirRadius);
        ho_Cross.Dispose();
        HOperatorSet.GenCrossContourXld(out ho_Cross, hv_ResultRow, hv_ResultColumn,
                                        12, 0.785398);
        ho_Region.Dispose();
        HOperatorSet.GenRegionContourXld(ho_Circle, out ho_Region, "filled");
        HOperatorSet.Roundness(ho_Region, out hv_Distance, out hv_Sigma1, out hv_CirRoundness,
                               out hv_Sides);
        ho_Regions.Dispose();
        ho_Circle.Dispose();
        ho_Cross.Dispose();
        ho_Region.Dispose();

        return;
    }
            public void FindEdge(HObject image, HTuple row, HTuple column, HTuple radian, out HTuple edgeRow1, out HTuple edgeColumn1, out HTuple edgeRow2, out HTuple edgeColumn2)
            {
                HTuple homMat2D, rowTrans, columnTrans;

                //测量外边缘
                edgeRow1    = 0;
                edgeColumn1 = 0;
                edgeRow2    = 0;
                edgeColumn2 = 0;

                HOperatorSet.GenMeasureRectangle2(row + DisHanldeRow, column /*+ DisHanldeColumn*/, Radian + Math.PI / 2, 20, 40,
                                                  ImageWidth, ImageHeight, Interpolation, out HandleLine);

                for (int i = 0; i <= 5; i++)
                {
                    //设置幅度值
                    HTuple threshold = Threshold - 10 - i * 2;
                    if (threshold < 1)
                    {
                        threshold = 1;
                    }

                    HTuple rows    = new HTuple();
                    HTuple columns = new HTuple();

                    for (int j = 0; j < PinCount; j++)
                    {
                        HTuple rowEdge, columnEdge, amplitude, distance;

                        //变换检测位置
                        //HTuple homMat2D, rowTrans, columnTrans;
                        HOperatorSet.HomMat2dIdentity(out homMat2D);
                        HOperatorSet.HomMat2dTranslate(homMat2D, DisHanldeRow, j * PinDistance, out homMat2D);
                        HOperatorSet.HomMat2dRotate(homMat2D, radian, row, column, out homMat2D);
                        HOperatorSet.AffineTransPixel(homMat2D, row, column, out rowTrans, out columnTrans);

                        HOperatorSet.TranslateMeasure(HandleLine, rowTrans, columnTrans);

                        HOperatorSet.MeasurePos(image, HandleLine, Sigma, threshold, "negative", "first",
                                                out rowEdge, out columnEdge, out amplitude, out distance);

                        if (rowEdge.Length > 0)
                        {
                            rows.Append(rowEdge);
                            columns.Append(columnEdge);
                        }
                    }

                    if (rows.Length >= PinCount / 2)
                    {
                        //生成轮廓
                        HObject contour;
                        HTuple  nr, nc, dist;
                        HOperatorSet.GenContourPolygonXld(out contour, rows, columns);

                        //拟合
                        HOperatorSet.FitLineContourXld(contour, "tukey", -1, 0, 5, 2,
                                                       out edgeRow1, out edgeColumn1, out edgeRow2, out edgeColumn2,
                                                       out nr, out nc, out dist);

                        //生成直线,用于显示
                        contour?.Dispose();
                        HOperatorSet.GenContourPolygonXld(out contour, new HTuple(edgeRow1, edgeRow2), new HTuple(edgeColumn1, edgeColumn2));
                        HOperatorSet.ConcatObj(LineEdge, contour, out LineEdge);

                        break;
                    }
                }

                HOperatorSet.CloseMeasure(HandleLine);
            }
        public MeasureResult Action()
        {
            #region 輸出結果
            DistanceResult mResult = null;
            #endregion

            HTuple hv_STD_Row;
            HTuple hv_STD_Col, hv_Img_Row, hv_Img_Col, hv_Img_Rotate_Angle;
            HTuple hv_OffsetRow, hv_OffsetCol;
            HOperatorSet.SetSystem("border_shape_models", "false");

            //STD 中心點
            hv_STD_Row = 772;
            hv_STD_Col = 1003;

            //目前圖形 中心點
            hv_Img_Row = hv_AllModelRow.Clone();
            hv_Img_Col = hv_AllModelColumn.Clone();

            //目前圖形 Rotate Angle
            hv_Img_Rotate_Angle = hv_AllModelAngle.Clone();

            //目前圖形偏移量
            hv_OffsetRow = hv_Img_Row - hv_STD_Row;
            hv_OffsetCol = hv_Img_Col - hv_STD_Col;

            //第一個 線段 ROI
            HTuple f_angle = 1.57;
            HTuple f_angle_offset = f_angle - hv_Img_Rotate_Angle;
            HTuple f_ROI_Row = 317.88, f_ROI_Col = 1173.106;
            HTuple f_ROI_Cur_Row, f_ROI_Cur_Col;
            ReLocater(hv_STD_Row, hv_STD_Col, hv_AllModelAngle, hv_OffsetRow, hv_OffsetCol, f_ROI_Row, f_ROI_Col, out f_ROI_Cur_Row, out f_ROI_Cur_Col);

            //

            //第二個 線段 ROI
            HTuple s_angle = 1.57;
            HTuple s_angle_offset = s_angle - hv_Img_Rotate_Angle;
            HTuple s_ROI_Row = 331.45, s_ROI_Col = 1248.75;
            HTuple s_ROI_Cur_Row, s_ROI_Cur_Col;
            ReLocater(hv_STD_Row, hv_STD_Col, hv_AllModelAngle, hv_OffsetRow, hv_OffsetCol
                      , s_ROI_Row, s_ROI_Col, out s_ROI_Cur_Row, out s_ROI_Cur_Col);
            //roiS.MakeROI(s_ROI_Cur_Row, s_ROI_Col, 0, 13.3, 75.7);



            /**/

            #region Measure
            var cROIController = new ROIController();
            var cAssistant     = new MeasureAssistant(cROIController);

            var hImage = ho_Image as HImage;
            cAssistant.setImage(hImage);

            /*參數值*/
            cAssistant.mThresh         = 40.0;
            cAssistant.mSigma          = 1.0;
            cAssistant.mRoiWidth       = 10;
            cAssistant.mInterpolation  = "nearest_neighbor";
            cAssistant.mSelPair        = false;
            cAssistant.mTransition     = "all";
            cAssistant.mPosition       = "all";
            cAssistant.mDispEdgeLength = 30;
            cAssistant.mDispROIWidth   = true;
            cAssistant.setUnit("cm");

            cAssistant.mInitThresh   = 40.0;
            cAssistant.mInitSigma    = 1.0;
            cAssistant.mInitRoiWidth = 10;

            var roiF = new ROIRectangle2()
            {
                ROIMeasureType = MeasureType.Line
            };
            //roiF.MakeROI(416, 998, 0, 26.5, 71.2);
            roiF.MakeROI(f_ROI_Cur_Row, f_ROI_Cur_Col, f_angle_offset, 46.466, 41.411);

            var roiS = new ROIRectangle2()
            {
                ROIMeasureType = MeasureType.Line
            };
            //roiS.MakeROI(400, 1041, 0, 13.3, 75.7);
            roiS.MakeROI(s_ROI_Cur_Row, s_ROI_Cur_Col, s_angle_offset, 47.496, 45.163);

            var lineF = new MeasurementEdge(roiF, cAssistant);
            var lineS = new MeasurementEdge(roiS, cAssistant);
            mResult = LineToLine(lineF, lineS);

            #endregion

            return(mResult);
        }
    // Chapter: Filter / Arithmetic
    // Short Description: Scale the gray values of an image from the interval [Min,Max] to [0,255]
    public void scale_image_range(HObject ho_Image, out HObject ho_ImageScaled, HTuple hv_Min,
                                  HTuple hv_Max)
    {
        // Stack for temporary objects
        HObject[] OTemp = new HObject[20];
        long      SP_O  = 0;

        // Local iconic variables

        HObject ho_SelectedChannel = null, ho_LowerRegion = null;
        HObject ho_UpperRegion = null;

        HObject ho_Image_COPY_INP_TMP;

        ho_Image_COPY_INP_TMP = ho_Image.CopyObj(1, -1);


        // Local control variables

        HTuple hv_LowerLimit = new HTuple(), hv_UpperLimit = new HTuple();
        HTuple hv_Mult, hv_Add, hv_Channels, hv_Index, hv_MinGray = new HTuple();
        HTuple hv_MaxGray = new HTuple(), hv_Range = new HTuple();

        HTuple hv_Max_COPY_INP_TMP = hv_Max.Clone();
        HTuple hv_Min_COPY_INP_TMP = hv_Min.Clone();

        // Initialize local and output iconic variables
        HOperatorSet.GenEmptyObj(out ho_ImageScaled);
        HOperatorSet.GenEmptyObj(out ho_SelectedChannel);
        HOperatorSet.GenEmptyObj(out ho_LowerRegion);
        HOperatorSet.GenEmptyObj(out ho_UpperRegion);

        //Convenience procedure to scale the gray values of the
        //input image Image from the interval [Min,Max]
        //to the interval [0,255] (default).
        //Gray values < 0 or > 255 (after scaling) are clipped.
        //
        //If the image shall be scaled to an interval different from [0,255],
        //this can be achieved by passing tuples with 2 values [From, To]
        //as Min and Max.
        //Example:
        //scale_image_range(Image:ImageScaled:[100,50],[200,250])
        //maps the gray values of Image from the interval [100,200] to [50,250].
        //All other gray values will be clipped.
        //
        //input parameters:
        //Image: the input image
        //Min: the minimum gray value which will be mapped to 0
        //     If a tuple with two values is given, the first value will
        //     be mapped to the second value.
        //Max: The maximum gray value which will be mapped to 255
        //     If a tuple with two values is given, the first value will
        //     be mapped to the second value.
        //
        //output parameter:
        //ImageScale: the resulting scaled image
        //
        if ((int)(new HTuple((new HTuple(hv_Min_COPY_INP_TMP.TupleLength())).TupleEqual(
                                 2))) != 0)
        {
            hv_LowerLimit       = hv_Min_COPY_INP_TMP[1];
            hv_Min_COPY_INP_TMP = hv_Min_COPY_INP_TMP[0];
        }
        else
        {
            hv_LowerLimit = 0.0;
        }
        if ((int)(new HTuple((new HTuple(hv_Max_COPY_INP_TMP.TupleLength())).TupleEqual(
                                 2))) != 0)
        {
            hv_UpperLimit       = hv_Max_COPY_INP_TMP[1];
            hv_Max_COPY_INP_TMP = hv_Max_COPY_INP_TMP[0];
        }
        else
        {
            hv_UpperLimit = 255.0;
        }
        //
        //Calculate scaling parameters
        hv_Mult = (((hv_UpperLimit - hv_LowerLimit)).TupleReal()) / (hv_Max_COPY_INP_TMP - hv_Min_COPY_INP_TMP);
        hv_Add  = ((-hv_Mult) * hv_Min_COPY_INP_TMP) + hv_LowerLimit;
        //
        //Scale image
        OTemp[SP_O] = ho_Image_COPY_INP_TMP.CopyObj(1, -1);
        SP_O++;
        ho_Image_COPY_INP_TMP.Dispose();
        HOperatorSet.ScaleImage(OTemp[SP_O - 1], out ho_Image_COPY_INP_TMP, hv_Mult, hv_Add);
        OTemp[SP_O - 1].Dispose();
        SP_O = 0;
        //
        //Clip gray values if necessary
        //This must be done for each channel separately
        HOperatorSet.CountChannels(ho_Image_COPY_INP_TMP, out hv_Channels);
        for (hv_Index = 1; hv_Index.Continue(hv_Channels, 1); hv_Index = hv_Index.TupleAdd(1))
        {
            ho_SelectedChannel.Dispose();
            HOperatorSet.AccessChannel(ho_Image_COPY_INP_TMP, out ho_SelectedChannel, hv_Index);
            HOperatorSet.MinMaxGray(ho_SelectedChannel, ho_SelectedChannel, 0, out hv_MinGray,
                                    out hv_MaxGray, out hv_Range);
            ho_LowerRegion.Dispose();
            HOperatorSet.Threshold(ho_SelectedChannel, out ho_LowerRegion, ((hv_MinGray.TupleConcat(
                                                                                 hv_LowerLimit))).TupleMin(), hv_LowerLimit);
            ho_UpperRegion.Dispose();
            HOperatorSet.Threshold(ho_SelectedChannel, out ho_UpperRegion, hv_UpperLimit,
                                   ((hv_UpperLimit.TupleConcat(hv_MaxGray))).TupleMax());
            OTemp[SP_O] = ho_SelectedChannel.CopyObj(1, -1);
            SP_O++;
            ho_SelectedChannel.Dispose();
            HOperatorSet.PaintRegion(ho_LowerRegion, OTemp[SP_O - 1], out ho_SelectedChannel,
                                     hv_LowerLimit, "fill");
            OTemp[SP_O - 1].Dispose();
            SP_O        = 0;
            OTemp[SP_O] = ho_SelectedChannel.CopyObj(1, -1);
            SP_O++;
            ho_SelectedChannel.Dispose();
            HOperatorSet.PaintRegion(ho_UpperRegion, OTemp[SP_O - 1], out ho_SelectedChannel,
                                     hv_UpperLimit, "fill");
            OTemp[SP_O - 1].Dispose();
            SP_O = 0;
            if ((int)(new HTuple(hv_Index.TupleEqual(1))) != 0)
            {
                ho_ImageScaled.Dispose();
                HOperatorSet.CopyObj(ho_SelectedChannel, out ho_ImageScaled, 1, 1);
            }
            else
            {
                OTemp[SP_O] = ho_ImageScaled.CopyObj(1, -1);
                SP_O++;
                ho_ImageScaled.Dispose();
                HOperatorSet.AppendChannel(OTemp[SP_O - 1], ho_SelectedChannel, out ho_ImageScaled
                                           );
                OTemp[SP_O - 1].Dispose();
                SP_O = 0;
            }
        }
        ho_Image_COPY_INP_TMP.Dispose();
        ho_SelectedChannel.Dispose();
        ho_LowerRegion.Dispose();
        ho_UpperRegion.Dispose();

        return;
    }
Exemple #51
0
        /// <summary>
        /// 生成芯片实际扫描点位
        /// </summary>
        /// <param name="imgs"></param>
        /// <param name="snapX"></param>
        /// <param name="snapY"></param>
        /// <param name="icsCenterX"></param>
        /// <param name="icsCenterY"></param>
        /// <param name="fovsOffsetX"></param>
        /// <param name="fovsOffsetY"></param>
        /// <param name="errorInfo"></param>
        /// <returns></returns>
        public bool CalibProduct(IJFImage[] imgs, double[] snapX, double[] snapY, out double[] icsCenterX, out double[] icsCenterY,
                                 out double[] fovsOffsetX, out double[] fovsOffsetY, out string errorInfo)
        {
            if (!_isInitOK)
            {
                icsCenterX  = null;
                icsCenterY  = null;
                fovsOffsetX = null;
                fovsOffsetY = null;
                errorInfo   = "初始化未完成";
                return(false);
            }

            HObject[] himgs = new HObject[] { null, null };
            object    oi;

            if (0 != imgs[0].GenHalcon(out oi))
            {
                icsCenterX  = null;
                icsCenterY  = null;
                fovsOffsetX = null;
                fovsOffsetY = null;
                errorInfo   = "左Mark图像转Halcon失败!";
                return(false);
            }
            himgs[0] = oi as HObject;

            if (0 != imgs[1].GenHalcon(out oi))
            {
                icsCenterX  = null;
                icsCenterY  = null;
                fovsOffsetX = null;
                fovsOffsetY = null;
                errorInfo   = "右Mark图像转Halcon失败!";
                return(false);
            }
            himgs[1] = oi as HObject;

            //左矫正点
            HTuple hv_iFlag            = new HTuple();
            HTuple hvLeftModeHMap      = new HTuple();
            HTuple hvDefLeft_coorX     = new HTuple();
            HTuple hvDefLeft_coorY     = new HTuple();
            HTuple hvDefLeft_updateX   = new HTuple();
            HTuple hvDefLeft_updateY   = new HTuple();
            HTuple hvDefLeft_updateRow = new HTuple();
            HTuple hvDefLeft_updateCol = new HTuple();

            if (_leftMarkModel.matchRegion == null || !_leftMarkModel.matchRegion.IsInitialized())
            {
                HOperatorSet.GetDomain(himgs[0], out _leftMarkModel.matchRegion);
            }

            VisionMethon.coor_uvToxy_point(himgs[0], _leftMarkModel.defRows, _leftMarkModel.defCols, _recipe.CheckPosX, _recipe.CheckPosY,
                                           _cmrCalibData, out hvDefLeft_coorX, out hvDefLeft_coorY, out hv_iFlag);
            if (hv_iFlag.S != "")
            {
                icsCenterX        = null;
                icsCenterY        = null;
                fovsOffsetX       = null;
                fovsOffsetY       = null;
                hvDefLeft_updateX = null;
                hvDefLeft_updateY = null;
                errorInfo         = "左模板中心像素转换成实际坐标失败!" + hv_iFlag.S;
                return(false);
            }
            VisionMethon.Map_Points_Match(himgs[0], _leftMarkModel.matchRegion, _leftMarkModel.modelType, _leftMarkModel.modelID,
                                          _recipe.CheckPosScoreThresh, _leftMarkModel.defRows, _leftMarkModel.defCols, hvDefLeft_coorX, hvDefLeft_coorY,
                                          _cmrCalibData, out hvLeftModeHMap, out hvDefLeft_updateX, out hvDefLeft_updateY, out hvDefLeft_updateRow, out hvDefLeft_updateCol, out hv_iFlag);
            if (hv_iFlag.S != "")
            {
                icsCenterX        = null;
                icsCenterY        = null;
                fovsOffsetX       = null;
                fovsOffsetY       = null;
                hvDefLeft_updateX = null;
                hvDefLeft_updateY = null;
                errorInfo         = "左矫正点匹配失败!" + hv_iFlag.S;
                return(false);
            }

            //if (showRegion != null) showRegion.Dispose();
            //HOperatorSet.GenCrossContourXld(out showRegion, hvDefLeft_updateRow, hvDefLeft_updateCol, 512, 0);
            //ShowImage(hTWindow, himgs[0], showRegion);

            //左矫正点
            HTuple hvRightModeHMap      = new HTuple();
            HTuple hvDefRight_coorX     = new HTuple();
            HTuple hvDefRight_coorY     = new HTuple();
            HTuple hvDefRight_updateX   = new HTuple();
            HTuple hvDefRight_updateY   = new HTuple();
            HTuple hvDefRight_updateRow = new HTuple();
            HTuple hvDefRight_updateCol = new HTuple();

            if (_rightMarkModel.matchRegion == null || !_rightMarkModel.matchRegion.IsInitialized())
            {
                HOperatorSet.GetDomain(himgs[1], out _rightMarkModel.matchRegion);
            }

            VisionMethon.coor_uvToxy_point(himgs[1], _rightMarkModel.defRows, _rightMarkModel.defCols, _recipe.CheckPosRX, _recipe.CheckPosRY,
                                           _cmrCalibData, out hvDefRight_coorX, out hvDefRight_coorY, out hv_iFlag);
            if (hv_iFlag.S != "")
            {
                icsCenterX  = null;
                icsCenterY  = null;
                fovsOffsetX = null;
                fovsOffsetY = null;
                errorInfo   = "右模板中心像素转换成实际坐标失败!" + hv_iFlag.S;
                return(false);
            }
            VisionMethon.Map_Points_Match(himgs[1], _rightMarkModel.matchRegion, _rightMarkModel.modelType, _rightMarkModel.modelID,
                                          _recipe.CheckPosRScoreThresh, _rightMarkModel.defRows, _rightMarkModel.defCols, hvDefRight_coorX, hvDefRight_coorY,
                                          _cmrCalibData, out hvRightModeHMap, out hvDefRight_updateX, out hvDefRight_updateY, out hvDefRight_updateRow, out hvDefRight_updateCol, out hv_iFlag);
            if (hv_iFlag.S != "")
            {
                icsCenterX  = null;
                icsCenterY  = null;
                fovsOffsetX = null;
                fovsOffsetY = null;
                errorInfo   = "右矫正点匹配失败!" + hv_iFlag.S;
                return(false);
            }

            //if (showRegion != null) showRegion.Dispose();
            //HOperatorSet.GenCrossContourXld(out showRegion, hvDefLeft_updateRow, hvDefLeft_updateCol, 512, 0);
            //ShowImage(hTWindow, himgs[1], showRegion);

            //生成矫正后芯片扫描点位
            HTuple hvAfterFix_SnapX = new HTuple();
            HTuple hvAfterFix_SnapY = new HTuple();
            HTuple hvAfterFix_ICX   = null;
            HTuple hvAfterFix_ICY   = null;
            HTuple hv_du            = null;
            HTuple hv_dv            = null;

            VisionMethon.update_map_correction(_recipe.icMapX, _recipe.icMapY, _recipe.snapMapX, _recipe.snapMapY,
                                               hvDefLeft_coorX, hvDefLeft_coorY, hvDefRight_coorX, hvDefRight_coorY, hvDefLeft_updateX,
                                               hvDefLeft_updateY, hvDefRight_updateX, hvDefRight_updateY, _cmrCalibData, out hvAfterFix_ICX,
                                               out hvAfterFix_ICY, out hvAfterFix_SnapX, out hvAfterFix_SnapY, out hv_iFlag, out hv_du, out hv_dv);
            if (hv_iFlag.S != "")
            {
                icsCenterX  = null;
                icsCenterY  = null;
                fovsOffsetX = null;
                fovsOffsetY = null;
                errorInfo   = "生成矫正点后扫描点位失败!" + hv_iFlag.S;
                return(false);
            }

            //Fov矫正日后添加
            int fovCount = _recipe.FovCount;

            fovsOffsetX = new double[fovCount];
            fovsOffsetY = new double[fovCount];
            for (int i = 0; i < fovCount; i++)
            {
                _recipe.GetFovOffset(_recipe.FovNames()[i], out fovsOffsetX[i], out fovsOffsetY[i]);
            }



            double[] _icsCenterX = new double[hvAfterFix_SnapX.Length];
            double[] _icsCenterY = new double[hvAfterFix_SnapX.Length];
            icsCenterX = new double[hvAfterFix_SnapX.Length];
            icsCenterY = new double[hvAfterFix_SnapX.Length];

            for (int i = 0; i < hvAfterFix_SnapX.Length; i++)
            {
                _icsCenterX[i] = hvAfterFix_SnapX.TupleSelect(i).D;
                _icsCenterY[i] = hvAfterFix_SnapY.TupleSelect(i).D;
            }

            //重新排序每行扫描按照从左到右进行扫描
            int currentIndex = 0;

            for (int m = 0; m < _recipe.RowCount; m++)
            {
                for (int n = 0; n < _recipe.ColCount; n++)
                {
                    int index = 0;
                    if (m % 2 == 0)
                    {
                        index = (int)(m * _recipe.ColCount + n);
                    }
                    else
                    {
                        index = (int)(m * _recipe.ColCount + (_recipe.ColCount - 1 - n));
                    }
                    icsCenterX[currentIndex] = _icsCenterX[index];
                    icsCenterY[currentIndex] = _icsCenterY[index];

                    currentIndex++;
                }
            }
            errorInfo = "Success";
            return(true);
        }
Exemple #52
0
    //public void InitHalcon()
    //{
    //  // Default settings used in HDevelop
    //  HOperatorSet.SetSystem("width", 512);
    //  HOperatorSet.SetSystem("height", 512);
    //}

    public void RunCAM3(HTuple Window)
    {
        hv_ExpDefaultWinHandle = Window;
        action3();
    }
    // Procedures
    public void GetRegionOfAntennaAroundOfS1423A(HObject ho_Image, out HObject ho_FoundRegion,
                                                 HTuple hv_LightDark, HTuple hv_WidthMin, HTuple hv_WidthMax, HTuple hv_HeightMin,
                                                 HTuple hv_HeightMax, HTuple hv_DilationlWidth, HTuple hv_DilationHeight)
    {
        // Local iconic variables

        HObject ho_Region, ho_ConnectedRegions, ho_SelectedRegions;
        HObject ho_SelectedRegions1, ho_RegionUnion, ho_Rectangle;

        // Local control variables

        HTuple hv_UsedThreshold = null, hv_Row1 = null;
        HTuple hv_Column1 = null, hv_Row2 = null, hv_Column2 = null;

        // Initialize local and output iconic variables
        HOperatorSet.GenEmptyObj(out ho_FoundRegion);
        HOperatorSet.GenEmptyObj(out ho_Region);
        HOperatorSet.GenEmptyObj(out ho_ConnectedRegions);
        HOperatorSet.GenEmptyObj(out ho_SelectedRegions);
        HOperatorSet.GenEmptyObj(out ho_SelectedRegions1);
        HOperatorSet.GenEmptyObj(out ho_RegionUnion);
        HOperatorSet.GenEmptyObj(out ho_Rectangle);
        ho_Region.Dispose();
        HOperatorSet.BinaryThreshold(ho_Image, out ho_Region, "max_separability", hv_LightDark,
                                     out hv_UsedThreshold);
        ho_ConnectedRegions.Dispose();
        HOperatorSet.Connection(ho_Region, out ho_ConnectedRegions);
        ho_SelectedRegions.Dispose();
        HOperatorSet.SelectShape(ho_ConnectedRegions, out ho_SelectedRegions, "width",
                                 "and", hv_WidthMin, hv_WidthMax);
        ho_SelectedRegions1.Dispose();
        HOperatorSet.SelectShape(ho_SelectedRegions, out ho_SelectedRegions1, "height",
                                 "and", hv_HeightMin, hv_HeightMax);
        ho_RegionUnion.Dispose();
        HOperatorSet.Union1(ho_SelectedRegions1, out ho_RegionUnion);
        HOperatorSet.SmallestRectangle1(ho_RegionUnion, out hv_Row1, out hv_Column1,
                                        out hv_Row2, out hv_Column2);
        ho_Rectangle.Dispose();
        HOperatorSet.GenRectangle1(out ho_Rectangle, hv_Row1, hv_Column1, hv_Row2, hv_Column2);
        ho_FoundRegion.Dispose();
        HOperatorSet.DilationRectangle1(ho_Rectangle, out ho_FoundRegion, hv_DilationlWidth,
                                        hv_DilationHeight);


        ho_Region.Dispose();
        ho_ConnectedRegions.Dispose();
        ho_SelectedRegions.Dispose();
        ho_SelectedRegions1.Dispose();
        ho_RegionUnion.Dispose();
        ho_Rectangle.Dispose();

        return;
    }
        // Local procedures
        public static void Get_11_Point_Coordinates(HObject ho_Image, HTuple hv_Diameter, HTuple hv_Threshold,
                                                    out HTuple hv_isFind, out HTuple hv_Rows_cc, out HTuple hv_Cols_cc)
        {
            // Stack for temporary objects
            HObject[] OTemp = new HObject[20];

            // Local iconic variables

            HObject ho_ImageOut = null, ho_Region, ho_RegionOpening;
            HObject ho_ConnectedRegions, ho_Regions_11_Circles, ho_RegionUnion100;
            HObject ho_RegionClosing, ho_Regions_9_Circles, ho_Regions_2_Circles;

            // Local control variables

            HTuple hv_Channels = null, hv_Areas11 = null;
            HTuple hv_Rows11 = null, hv_Columns11 = null, hv_Indices0 = null;
            HTuple hv_x1 = null, hv_y1 = null, hv_x3 = null, hv_y3 = null;
            HTuple hv_Dist1_3 = null, hv_Areas = null, hv_Rows = null;
            HTuple hv_Columns = null, hv_Distances = null, hv_i = null;
            HTuple hv_Dist = new HTuple(), hv_Indices = null, hv_x9 = null;
            HTuple hv_y9 = null, hv_x7 = null, hv_y7 = null, hv_x5_ = null;
            HTuple hv_y5_ = null, hv_x5 = null, hv_y5 = null, hv_x2_ = null;
            HTuple hv_y2_ = null, hv_x2 = null, hv_y2 = null, hv_x6_ = null;
            HTuple hv_y6_ = null, hv_x6 = null, hv_y6 = null, hv_x8_ = null;
            HTuple hv_y8_ = null, hv_x8 = null, hv_y8 = null, hv_x4_ = null;
            HTuple hv_y4_ = null, hv_x4 = null, hv_y4 = null, hv_Areas2 = null;
            HTuple hv_Rows2 = null, hv_Columns2 = null, hv_x11 = null;
            HTuple hv_y11 = null, hv_x10 = null, hv_y10 = null;

            // Initialize local and output iconic variables
            HOperatorSet.GenEmptyObj(out ho_ImageOut);
            HOperatorSet.GenEmptyObj(out ho_Region);
            HOperatorSet.GenEmptyObj(out ho_RegionOpening);
            HOperatorSet.GenEmptyObj(out ho_ConnectedRegions);
            HOperatorSet.GenEmptyObj(out ho_Regions_11_Circles);
            HOperatorSet.GenEmptyObj(out ho_RegionUnion100);
            HOperatorSet.GenEmptyObj(out ho_RegionClosing);
            HOperatorSet.GenEmptyObj(out ho_Regions_9_Circles);
            HOperatorSet.GenEmptyObj(out ho_Regions_2_Circles);
            hv_Rows_cc = new HTuple();
            hv_Cols_cc = new HTuple();
            try
            {
                //说明:
                //1、Diameter指的是常规的9个圆的直径大小(以像素计量),如果懒得设置,可以令Diameter := 0。isFind ==1 表示成功找到11个圆。
                //2、每个黑圆中央必须有一个小白点清晰可见,并且黑圆的个数必须为11个,否则函数将计算失败。
                //3、当标定板摆正时,圆的排序“先从左到右,再从上到下”,最小的圆是圆1,最大的圆是圆3
                //4、标定板可以任意角度摆放,不一定需要摆正。标定板表面不得有其他脏污,否则可能计算失败。标定板图像需黑白分明。
                //5、halcon的x、y(Rows_cc和Cols_cc)和其他编程语言中的图像中x、y值刚好是相反的。具体使用时,要把x、y的值调换顺序。
                //6、圆10和圆11必须离圆1-9比较远
                //7、如程序执行异常需要优化,可联系[email protected]


                ho_ImageOut.Dispose();
                ho_ImageOut = ho_Image.CopyObj(1, -1);
                hv_isFind   = 0;
                HOperatorSet.CountChannels(ho_ImageOut, out hv_Channels);
                if ((int)(new HTuple(hv_Channels.TupleGreaterEqual(3))) != 0)
                {
                    {
                        HObject ExpTmpOutVar_0;
                        HOperatorSet.Rgb1ToGray(ho_ImageOut, out ExpTmpOutVar_0);
                        ho_ImageOut.Dispose();
                        ho_ImageOut = ExpTmpOutVar_0;
                    }
                }

                ho_Region.Dispose();
                HOperatorSet.Threshold(ho_ImageOut, out ho_Region, 0, hv_Threshold);
                {
                    HObject ExpTmpOutVar_0;
                    HOperatorSet.FillUp(ho_Region, out ExpTmpOutVar_0);
                    ho_Region.Dispose();
                    ho_Region = ExpTmpOutVar_0;
                }
                ho_RegionOpening.Dispose();
                HOperatorSet.OpeningCircle(ho_Region, out ho_RegionOpening, 4.0);
                ho_ConnectedRegions.Dispose();
                HOperatorSet.Connection(ho_RegionOpening, out ho_ConnectedRegions);
                ho_Regions_11_Circles.Dispose();
                HOperatorSet.SelectShape(ho_ConnectedRegions, out ho_Regions_11_Circles, (new HTuple("circularity")).TupleConcat(
                                             "area"), "and", (new HTuple(0.9)).TupleConcat(10000), (new HTuple(1.0)).TupleConcat(
                                             9999999999));
                if ((int)(new HTuple(hv_Diameter.TupleNotEqual(0))) != 0)
                {
                    {
                        HObject ExpTmpOutVar_0;
                        HOperatorSet.SelectShape(ho_Regions_11_Circles, out ExpTmpOutVar_0, "width",
                                                 "and", hv_Diameter * 0.3, hv_Diameter * 3);
                        ho_Regions_11_Circles.Dispose();
                        ho_Regions_11_Circles = ExpTmpOutVar_0;
                    }
                }


                HOperatorSet.AreaCenter(ho_Regions_11_Circles, out hv_Areas11, out hv_Rows11,
                                        out hv_Columns11);
                ho_RegionUnion100.Dispose();
                HOperatorSet.Union1(ho_Regions_11_Circles, out ho_RegionUnion100);

                if ((int)(new HTuple((new HTuple(hv_Areas11.TupleLength())).TupleNotEqual(11))) != 0)
                {
                    hv_isFind = 0;
                    ho_ImageOut.Dispose();
                    ho_Region.Dispose();
                    ho_RegionOpening.Dispose();
                    ho_ConnectedRegions.Dispose();
                    ho_Regions_11_Circles.Dispose();
                    ho_RegionUnion100.Dispose();
                    ho_RegionClosing.Dispose();
                    ho_Regions_9_Circles.Dispose();
                    ho_Regions_2_Circles.Dispose();

                    return;
                }

                HOperatorSet.TupleSortIndex(hv_Areas11, out hv_Indices0);
                //直径最小的是圆1
                hv_x1 = hv_Rows11.TupleSelect(hv_Indices0.TupleSelect(0));
                hv_y1 = hv_Columns11.TupleSelect(hv_Indices0.TupleSelect(0));

                //直径最大的是圆3
                hv_x3 = hv_Rows11.TupleSelect(hv_Indices0.TupleSelect((new HTuple(hv_Areas11.TupleLength()
                                                                                  )) - 1));
                hv_y3 = hv_Columns11.TupleSelect(hv_Indices0.TupleSelect((new HTuple(hv_Areas11.TupleLength()
                                                                                     )) - 1));

                HOperatorSet.DistancePp(hv_x1, hv_y1, hv_x3, hv_y3, out hv_Dist1_3);
                ho_RegionClosing.Dispose();
                HOperatorSet.ClosingCircle(ho_RegionUnion100, out ho_RegionClosing, 5 + (hv_Dist1_3 / 4));
                {
                    HObject ExpTmpOutVar_0;
                    HOperatorSet.FillUp(ho_RegionClosing, out ExpTmpOutVar_0);
                    ho_RegionClosing.Dispose();
                    ho_RegionClosing = ExpTmpOutVar_0;
                }
                {
                    HObject ExpTmpOutVar_0;
                    HOperatorSet.Connection(ho_RegionClosing, out ExpTmpOutVar_0);
                    ho_RegionClosing.Dispose();
                    ho_RegionClosing = ExpTmpOutVar_0;
                }
                {
                    HObject ExpTmpOutVar_0;
                    HOperatorSet.SelectShapeStd(ho_RegionClosing, out ExpTmpOutVar_0, "max_area",
                                                70);
                    ho_RegionClosing.Dispose();
                    ho_RegionClosing = ExpTmpOutVar_0;
                }

                ho_Regions_9_Circles.Dispose();
                HOperatorSet.SelectShapeProto(ho_Regions_11_Circles, ho_RegionClosing, out ho_Regions_9_Circles,
                                              "overlaps_rel", 80, 100);
                HOperatorSet.AreaCenter(ho_Regions_9_Circles, out hv_Areas, out hv_Rows, out hv_Columns);

                if ((int)(new HTuple((new HTuple(hv_Areas.TupleLength())).TupleNotEqual(9))) != 0)
                {
                    hv_isFind = 0;
                    ho_ImageOut.Dispose();
                    ho_Region.Dispose();
                    ho_RegionOpening.Dispose();
                    ho_ConnectedRegions.Dispose();
                    ho_Regions_11_Circles.Dispose();
                    ho_RegionUnion100.Dispose();
                    ho_RegionClosing.Dispose();
                    ho_Regions_9_Circles.Dispose();
                    ho_Regions_2_Circles.Dispose();

                    return;
                }

                //离圆1最远的是圆9
                hv_Distances = new HTuple();
                for (hv_i = 0; (int)hv_i <= (int)((new HTuple(hv_Areas.TupleLength())) - 1); hv_i = (int)hv_i + 1)
                {
                    HOperatorSet.DistancePp(hv_x1, hv_y1, hv_Rows.TupleSelect(hv_i), hv_Columns.TupleSelect(
                                                hv_i), out hv_Dist);
                    hv_Distances = hv_Distances.TupleConcat(hv_Dist);
                }
                HOperatorSet.TupleSortIndex(hv_Distances, out hv_Indices);
                hv_x9 = hv_Rows.TupleSelect(hv_Indices.TupleSelect(8));
                hv_y9 = hv_Columns.TupleSelect(hv_Indices.TupleSelect(8));

                //离圆3最远的是圆7
                hv_Distances = new HTuple();
                for (hv_i = 0; (int)hv_i <= (int)((new HTuple(hv_Areas.TupleLength())) - 1); hv_i = (int)hv_i + 1)
                {
                    HOperatorSet.DistancePp(hv_x3, hv_y3, hv_Rows.TupleSelect(hv_i), hv_Columns.TupleSelect(
                                                hv_i), out hv_Dist);
                    hv_Distances = hv_Distances.TupleConcat(hv_Dist);
                }
                HOperatorSet.TupleSortIndex(hv_Distances, out hv_Indices);
                hv_x7 = hv_Rows.TupleSelect(hv_Indices.TupleSelect(8));
                hv_y7 = hv_Columns.TupleSelect(hv_Indices.TupleSelect(8));

                //圆1、9中间的是圆5
                hv_x5_       = (hv_x1 + hv_x9) / 2;
                hv_y5_       = (hv_y1 + hv_y9) / 2;
                hv_Distances = new HTuple();
                for (hv_i = 0; (int)hv_i <= (int)((new HTuple(hv_Areas.TupleLength())) - 1); hv_i = (int)hv_i + 1)
                {
                    HOperatorSet.DistancePp(hv_x5_, hv_y5_, hv_Rows.TupleSelect(hv_i), hv_Columns.TupleSelect(
                                                hv_i), out hv_Dist);
                    hv_Distances = hv_Distances.TupleConcat(hv_Dist);
                }
                HOperatorSet.TupleSortIndex(hv_Distances, out hv_Indices);
                hv_x5 = hv_Rows.TupleSelect(hv_Indices.TupleSelect(0));
                hv_y5 = hv_Columns.TupleSelect(hv_Indices.TupleSelect(0));

                //圆1、3中间的是圆2
                hv_x2_       = (hv_x1 + hv_x3) / 2;
                hv_y2_       = (hv_y1 + hv_y3) / 2;
                hv_Distances = new HTuple();
                for (hv_i = 0; (int)hv_i <= (int)((new HTuple(hv_Areas.TupleLength())) - 1); hv_i = (int)hv_i + 1)
                {
                    HOperatorSet.DistancePp(hv_x2_, hv_y2_, hv_Rows.TupleSelect(hv_i), hv_Columns.TupleSelect(
                                                hv_i), out hv_Dist);
                    hv_Distances = hv_Distances.TupleConcat(hv_Dist);
                }
                HOperatorSet.TupleSortIndex(hv_Distances, out hv_Indices);
                hv_x2 = hv_Rows.TupleSelect(hv_Indices.TupleSelect(0));
                hv_y2 = hv_Columns.TupleSelect(hv_Indices.TupleSelect(0));


                //圆3、9中间的是圆6
                hv_x6_       = (hv_x3 + hv_x9) / 2;
                hv_y6_       = (hv_y3 + hv_y9) / 2;
                hv_Distances = new HTuple();
                for (hv_i = 0; (int)hv_i <= (int)((new HTuple(hv_Areas.TupleLength())) - 1); hv_i = (int)hv_i + 1)
                {
                    HOperatorSet.DistancePp(hv_x6_, hv_y6_, hv_Rows.TupleSelect(hv_i), hv_Columns.TupleSelect(
                                                hv_i), out hv_Dist);
                    hv_Distances = hv_Distances.TupleConcat(hv_Dist);
                }
                HOperatorSet.TupleSortIndex(hv_Distances, out hv_Indices);
                hv_x6 = hv_Rows.TupleSelect(hv_Indices.TupleSelect(0));
                hv_y6 = hv_Columns.TupleSelect(hv_Indices.TupleSelect(0));

                //圆7、9中间的是圆8
                hv_x8_       = (hv_x7 + hv_x9) / 2;
                hv_y8_       = (hv_y7 + hv_y9) / 2;
                hv_Distances = new HTuple();
                for (hv_i = 0; (int)hv_i <= (int)((new HTuple(hv_Areas.TupleLength())) - 1); hv_i = (int)hv_i + 1)
                {
                    HOperatorSet.DistancePp(hv_x8_, hv_y8_, hv_Rows.TupleSelect(hv_i), hv_Columns.TupleSelect(
                                                hv_i), out hv_Dist);
                    hv_Distances = hv_Distances.TupleConcat(hv_Dist);
                }
                HOperatorSet.TupleSortIndex(hv_Distances, out hv_Indices);
                hv_x8 = hv_Rows.TupleSelect(hv_Indices.TupleSelect(0));
                hv_y8 = hv_Columns.TupleSelect(hv_Indices.TupleSelect(0));

                //圆1、7中间的是圆4
                hv_x4_       = (hv_x1 + hv_x7) / 2;
                hv_y4_       = (hv_y1 + hv_y7) / 2;
                hv_Distances = new HTuple();
                for (hv_i = 0; (int)hv_i <= (int)((new HTuple(hv_Areas.TupleLength())) - 1); hv_i = (int)hv_i + 1)
                {
                    HOperatorSet.DistancePp(hv_x4_, hv_y4_, hv_Rows.TupleSelect(hv_i), hv_Columns.TupleSelect(
                                                hv_i), out hv_Dist);
                    hv_Distances = hv_Distances.TupleConcat(hv_Dist);
                }
                HOperatorSet.TupleSortIndex(hv_Distances, out hv_Indices);
                hv_x4 = hv_Rows.TupleSelect(hv_Indices.TupleSelect(0));
                hv_y4 = hv_Columns.TupleSelect(hv_Indices.TupleSelect(0));

                hv_Rows_cc = new HTuple();
                hv_Rows_cc = hv_Rows_cc.TupleConcat(hv_x1);
                hv_Rows_cc = hv_Rows_cc.TupleConcat(hv_x2);
                hv_Rows_cc = hv_Rows_cc.TupleConcat(hv_x3);
                hv_Rows_cc = hv_Rows_cc.TupleConcat(hv_x4);
                hv_Rows_cc = hv_Rows_cc.TupleConcat(hv_x5);
                hv_Rows_cc = hv_Rows_cc.TupleConcat(hv_x6);
                hv_Rows_cc = hv_Rows_cc.TupleConcat(hv_x7);
                hv_Rows_cc = hv_Rows_cc.TupleConcat(hv_x8);
                hv_Rows_cc = hv_Rows_cc.TupleConcat(hv_x9);
                hv_Cols_cc = new HTuple();
                hv_Cols_cc = hv_Cols_cc.TupleConcat(hv_y1);
                hv_Cols_cc = hv_Cols_cc.TupleConcat(hv_y2);
                hv_Cols_cc = hv_Cols_cc.TupleConcat(hv_y3);
                hv_Cols_cc = hv_Cols_cc.TupleConcat(hv_y4);
                hv_Cols_cc = hv_Cols_cc.TupleConcat(hv_y5);
                hv_Cols_cc = hv_Cols_cc.TupleConcat(hv_y6);
                hv_Cols_cc = hv_Cols_cc.TupleConcat(hv_y7);
                hv_Cols_cc = hv_Cols_cc.TupleConcat(hv_y8);
                hv_Cols_cc = hv_Cols_cc.TupleConcat(hv_y9);


                //找最后两个点
                ho_Regions_2_Circles.Dispose();
                HOperatorSet.SelectShapeProto(ho_Regions_11_Circles, ho_RegionClosing, out ho_Regions_2_Circles,
                                              "overlaps_rel", 0, 30);
                HOperatorSet.AreaCenter(ho_Regions_2_Circles, out hv_Areas2, out hv_Rows2,
                                        out hv_Columns2);

                if ((int)(new HTuple((new HTuple(hv_Areas2.TupleLength())).TupleNotEqual(2))) != 0)
                {
                    hv_isFind = 0;
                    ho_ImageOut.Dispose();
                    ho_Region.Dispose();
                    ho_RegionOpening.Dispose();
                    ho_ConnectedRegions.Dispose();
                    ho_Regions_11_Circles.Dispose();
                    ho_RegionUnion100.Dispose();
                    ho_RegionClosing.Dispose();
                    ho_Regions_9_Circles.Dispose();
                    ho_Regions_2_Circles.Dispose();

                    return;
                }


                //离圆1最远的是圆11
                hv_Distances = new HTuple();
                for (hv_i = 0; (int)hv_i <= (int)((new HTuple(hv_Areas2.TupleLength())) - 1); hv_i = (int)hv_i + 1)
                {
                    HOperatorSet.DistancePp(hv_x1, hv_y1, hv_Rows2.TupleSelect(hv_i), hv_Columns2.TupleSelect(
                                                hv_i), out hv_Dist);
                    hv_Distances = hv_Distances.TupleConcat(hv_Dist);
                }
                HOperatorSet.TupleSortIndex(hv_Distances, out hv_Indices);
                hv_x11 = hv_Rows2.TupleSelect(hv_Indices.TupleSelect(1));
                hv_y11 = hv_Columns2.TupleSelect(hv_Indices.TupleSelect(1));

                //另一个点就是最近的
                hv_x10 = hv_Rows2.TupleSelect(hv_Indices.TupleSelect(0));
                hv_y10 = hv_Columns2.TupleSelect(hv_Indices.TupleSelect(0));

                hv_Rows_cc = new HTuple();
                hv_Rows_cc = hv_Rows_cc.TupleConcat(hv_x1);
                hv_Rows_cc = hv_Rows_cc.TupleConcat(hv_x2);
                hv_Rows_cc = hv_Rows_cc.TupleConcat(hv_x3);
                hv_Rows_cc = hv_Rows_cc.TupleConcat(hv_x4);
                hv_Rows_cc = hv_Rows_cc.TupleConcat(hv_x5);
                hv_Rows_cc = hv_Rows_cc.TupleConcat(hv_x6);
                hv_Rows_cc = hv_Rows_cc.TupleConcat(hv_x7);
                hv_Rows_cc = hv_Rows_cc.TupleConcat(hv_x8);
                hv_Rows_cc = hv_Rows_cc.TupleConcat(hv_x9);
                hv_Rows_cc = hv_Rows_cc.TupleConcat(hv_x10);
                hv_Rows_cc = hv_Rows_cc.TupleConcat(hv_x11);
                hv_Cols_cc = new HTuple();
                hv_Cols_cc = hv_Cols_cc.TupleConcat(hv_y1);
                hv_Cols_cc = hv_Cols_cc.TupleConcat(hv_y2);
                hv_Cols_cc = hv_Cols_cc.TupleConcat(hv_y3);
                hv_Cols_cc = hv_Cols_cc.TupleConcat(hv_y4);
                hv_Cols_cc = hv_Cols_cc.TupleConcat(hv_y5);
                hv_Cols_cc = hv_Cols_cc.TupleConcat(hv_y6);
                hv_Cols_cc = hv_Cols_cc.TupleConcat(hv_y7);
                hv_Cols_cc = hv_Cols_cc.TupleConcat(hv_y8);
                hv_Cols_cc = hv_Cols_cc.TupleConcat(hv_y9);
                hv_Cols_cc = hv_Cols_cc.TupleConcat(hv_y10);
                hv_Cols_cc = hv_Cols_cc.TupleConcat(hv_y11);

                hv_isFind = 1;
                ho_ImageOut.Dispose();
                ho_Region.Dispose();
                ho_RegionOpening.Dispose();
                ho_ConnectedRegions.Dispose();
                ho_Regions_11_Circles.Dispose();
                ho_RegionUnion100.Dispose();
                ho_RegionClosing.Dispose();
                ho_Regions_9_Circles.Dispose();
                ho_Regions_2_Circles.Dispose();

                return;
            }
            catch (HalconException HDevExpDefaultException)
            {
                ho_ImageOut.Dispose();
                ho_Region.Dispose();
                ho_RegionOpening.Dispose();
                ho_ConnectedRegions.Dispose();
                ho_Regions_11_Circles.Dispose();
                ho_RegionUnion100.Dispose();
                ho_RegionClosing.Dispose();
                ho_Regions_9_Circles.Dispose();
                ho_Regions_2_Circles.Dispose();

                throw HDevExpDefaultException;
            }
        }
        /// <summary>
        /// 已测试
        /// 软触发拍照下,计算相机的uv->xy坐标系变换的操作,如large相机
        /// 要求之前设置好相机/光源/触发至“合理”状态
        /// [x]   =   [ H1  H2  H3  ]    [u]
        /// [y]   =   [ H4  H5  H6  ] *  [v]
        ///                              [1]
        /// </summary>
        /// <param name="matUV2XY">uv->xy变换矩阵,将2*3的矩阵按照行堆叠的方式存储为1*6的数组, ref传递方式,需要数组有一个初始值</param>
        /// <param name="cam">相机控制类,注意曝光时间需要设置合适。软触发拍照建议曝光时间在100ms左右</param>
        /// <param name="modelID">匹配的ncc模板</param>
        /// <param name="score_thresh">匹配分数,需要大于0.5</param>
        /// <param name="axisPara">运动轴信息(xy插补),具体包括轴速,加速度</param>
        /// <param name="initPoint">初始点,中间仅适用了xy信息,需要保证走到初始点时室内内包含完整的,可匹配的model</param>
        /// <param name="lightInd">软触发拍照对应的光源id,需要事先设置好对应光源合适的时间</param>
        /// <param name="axisInd">x,y轴号</param>
        /// <param name="xyRange">计算变换时,以初始点为中心,随机走位的范围,单位mm</param>
        /// <param name="nPoints">随机走位多少个点</param>
        /// <param name="lightDelay">软触发拍照光源的延迟,单位us,典型值10us</param>
        /// <param name="timeOut">单次运动的延迟,单位ms</param>
        /// <param name="winID">(调试用)显示窗口ID</param>
        /// <returns>操作是否成功</returns>
        public bool calibUV2XY
        (
            int camInd,
            ref HTuple matUV2XY,
            Model model,
            double xyRange,
            int nPoints = 20
        )

        {
            //if (model.ReadModel(CalibrUV2XYModelPath) == false)
            //{
            //    HTUi.PopError("加载标定模版失败!");
            //    return false;
            //}
            string errMsg = "";

            if (_station.operation.MultiAxisMove(_station.AxisXYZ, new double[] { _xUv2xy, _yUv2xy, _zUv2xy }, true, out errMsg) != 0)
            {
                HTUi.PopError("无法移动至标定点位置!");
                return(false);
            }
            Thread.Sleep(200);
            //  App.obj_light.FlashMultiLight(LightUseFor.ScanPoint1st);

            //if(_station.operation.SWPosTrig(_station.AxisX,out errMsg)!=0)
            //{
            //    HTUi.PopError(errMsg);
            //    return false;
            //}

            Thread.Sleep(10);
            if (image != null)
            {
                image.Dispose();
            }
            HOperatorSet.GenEmptyObj(out image);

            if (_station.operation.CaputreOneImage(_station.CamereDev[camInd], "Halcon", out image, out errMsg) != 0)
            {
                HTUi.PopError("采集图像失败:" + errMsg);
                return(false);
            }

            //3. match
            HTuple  u, v, angle;
            bool    status     = matchModel(camInd, ref image, model, out u, out v, out angle);
            HObject showRegion = new HObject();

            showRegion.Dispose();
            HOperatorSet.GenCrossContourXld(out showRegion, u, v, 512, 0);
            _station._rtUi._fm.ShowImage(_station._rtUi._fm.htWindowCalibration, image, showRegion);
            //image.Dispose();
            if (!status)
            {
                HTUi.PopError("获取匹配初始位置图像失败");
                return(false);
            }
            HTuple xArr = new HTuple(), yArr = new HTuple(), uArr = new HTuple(), vArr = new HTuple();
            Random rand = new Random();

            //4. for ... snap , match, add <u,v,x,y>
            for (int i = 0; i < nPoints; i++)
            {
                DateTime t1 = DateTime.Now;
                //大于或等于 0.0 且小于 1.0 的双精度浮点数
                double x = (rand.NextDouble() - 0.5) * xyRange + _xUv2xy;
                double y = (rand.NextDouble() - 0.5) * xyRange + _yUv2xy;

                if (_station.operation.MultiAxisMove(new string[] { _station.AxisXYZ[0], _station.AxisXYZ[1], }, new double[] { x, y }, true, out errMsg) != 0)
                {
                    HTUi.PopError("无法移动至标定点位置!");
                    return(false);
                }

                Thread.Sleep(200);;

                //if (_station.operation.SWPosTrig(_station.AxisX, out errMsg) != 0)
                //{
                //    HTUi.PopError(errMsg);
                //    return false;
                //}

                Thread.Sleep(10);
                if (image != null)
                {
                    image.Dispose();
                }
                HOperatorSet.GenEmptyObj(out image);

                if (_station.operation.CaputreOneImage(_station.CamereDev[camInd], "Halcon", out image, out errMsg) != 0)
                {
                    HTUi.PopError("采集图像失败:" + errMsg);
                    return(false);
                }

                if (matchModel(camInd, ref image, model, out u, out v, out angle)) //found something
                {
                    xArr.Append(x); yArr.Append(y); uArr.Append(u); vArr.Append(v);
                }
                showRegion.Dispose();
                HOperatorSet.GenCrossContourXld(out showRegion, u, v, 512, 0);
                _station._rtUi._fm.ShowImage(_station._rtUi._fm.htWindowCalibration, image, showRegion);
                //image.Dispose();
            }
            if (xArr.Length < 10)
            {
                HTUi.PopError("有效点数不够");
                return(false);
            }
            //5. least square estimation
            Matrix <double> In = Matrix <double> .Build.Dense(3, xArr.Length, 1.0); //by default In[2,:] = 1.0

            Matrix <double> Out = Matrix <double> .Build.Dense(2, xArr.Length);

            Out.SetRow(0, xArr.ToDArr());
            Out.SetRow(1, yArr.ToDArr());
            In.SetRow(0, uArr.ToDArr());
            In.SetRow(1, vArr.ToDArr());
            Matrix <double> A = vec2Mat(In, Out);

            //6. move to center of uv space
            double[] aArr = A.ToRowWiseArray(); //need to be tested
            _station._calibrationUV2XYParameter = string.Join(",", aArr.ToArray());
            //parse
            if (matUV2XY == null)
            {
                matUV2XY = new HTuple();
            }
            for (int i = 0; i < 6; i++)
            {
                matUV2XY.Append(aArr[i]);
            }
            return(true);
        }
Exemple #56
0
        /// <summary>
        /// If calibration data is available and valid, then transform the
        /// distance between measure result edges into world coordinates,
        /// else leave them the same.
        /// </summary>
        public HTuple Distance(HTuple row1, HTuple col1, HTuple row2, HTuple col2, int shift)
        {
            HTuple   rows, cols, rowRect, colRect;
            HTuple   distance = new HTuple();
            HXLDCont contour;


            if (shift == 0)
            {
                if (mROIType == ROI.ROI_TYPE_CIRCLEARC)
                {
                    double cRow, cCol, radius, extent, phi1, phi2, phi, res, length, tmp;

                    cRow   = mROICoord[0].D;
                    cCol   = mROICoord[1].D;
                    radius = mROICoord[2].D;
                    extent = mROICoord[4].D;

                    HOperatorSet.TupleGenConst(new HTuple(row1.Length), 0.0, out distance);

                    for (int i = 0; i < distance.Length; i++)
                    {
                        phi1 = HMisc.AngleLx(cRow, cCol, row1[i].D, col1[i].D);
                        phi2 = HMisc.AngleLx(cRow, cCol, row2[i].D, col2[i].D);

                        if (extent < 0)
                        {
                            tmp  = phi1;
                            phi1 = phi2;
                            phi2 = tmp;
                        }

                        phi = phi2 - phi1;

                        if (phi < 0)
                        {
                            phi += 2 * Math.PI;
                        }

                        res = 0.05 * 24.0 / (radius * phi);

                        contour = new HXLDCont();
                        contour.GenEllipseContourXld(cRow, cCol, 0, radius, radius, phi1, phi2, "positive", res);
                        contour.GetContourXld(out rows, out cols);
                        Rectify(rows, cols, out rowRect, out colRect);
                        contour.Dispose();
                        contour.GenContourPolygonXld(rowRect, colRect);
                        length        = contour.LengthXld();
                        distance[i].D = length;
                        contour.Dispose();
                    }
                }
                else if (mROIType == ROI.ROI_TYPE_LINE)
                {
                    HTuple rRect1, cRect1, rRect2, cRect2;
                    Rectify(row1, col1, out rRect1, out cRect1);
                    Rectify(row2, col2, out rRect2, out cRect2);
                    distance = HMisc.DistancePp(rRect1, cRect1, rRect2, cRect2);
                }
                return(distance);
            }
            else
            {
                HTuple rClip1, cClip1, rShift2, cShift2;

                rClip1  = row1.TupleSelectRange(new HTuple(0), new HTuple(row1.Length - shift - 1));
                cClip1  = col1.TupleSelectRange(new HTuple(0), new HTuple(col1.Length - shift - 1));
                rShift2 = row2.TupleSelectRange(new HTuple(shift), new HTuple(row2.Length - 1));
                cShift2 = col2.TupleSelectRange(new HTuple(shift), new HTuple(col2.Length - 1));

                return(this.Distance(rClip1, cClip1, rShift2, cShift2, 0));
            }
        }
Exemple #57
0
 public HDevelopExport(HTuple HDWindow, string ImagePath_)
 {
     // Default settings used in HDevelop
     HOperatorSet.SetSystem("do_low_error", "false");
     action(HDWindow, ImagePath_);
 }
    // Chapter: Graphics / Text
    // Short Description: Set font independent of OS
    public void set_display_font(HTuple hv_WindowHandle, HTuple hv_Size, HTuple hv_Font,
                                 HTuple hv_Bold, HTuple hv_Slant)
    {
        // Local control variables

        HTuple hv_OS, hv_Exception = new HTuple();
        HTuple hv_AllowedFontSizes = new HTuple(), hv_Distances = new HTuple();
        HTuple hv_Indices = new HTuple();

        HTuple hv_Bold_COPY_INP_TMP  = hv_Bold.Clone();
        HTuple hv_Font_COPY_INP_TMP  = hv_Font.Clone();
        HTuple hv_Size_COPY_INP_TMP  = hv_Size.Clone();
        HTuple hv_Slant_COPY_INP_TMP = hv_Slant.Clone();

        // Initialize local and output iconic variables

        //This procedure sets the text font of the current window with
        //the specified attributes.
        //It is assumed that following fonts are installed on the system:
        //Windows: Courier New, Arial Times New Roman
        //Linux: courier, helvetica, times
        //Because fonts are displayed smaller on Linux than on Windows,
        //a scaling factor of 1.25 is used the get comparable results.
        //For Linux, only a limited number of font sizes is supported,
        //to get comparable results, it is recommended to use one of the
        //following sizes: 9, 11, 14, 16, 20, 27
        //(which will be mapped internally on Linux systems to 11, 14, 17, 20, 25, 34)
        //
        //input parameters:
        //WindowHandle: The graphics window for which the font will be set
        //Size: The font size. If Size=-1, the default of 16 is used.
        //Bold: If set to 'true', a bold font is used
        //Slant: If set to 'true', a slanted font is used
        //
        HOperatorSet.GetSystem("operating_system", out hv_OS);
        if ((int)((new HTuple(hv_Size_COPY_INP_TMP.TupleEqual(new HTuple()))).TupleOr(
                      new HTuple(hv_Size_COPY_INP_TMP.TupleEqual(-1)))) != 0)
        {
            hv_Size_COPY_INP_TMP = 16;
        }
        if ((int)(new HTuple((((hv_OS.TupleStrFirstN(2)).TupleStrLastN(0))).TupleEqual(
                                 "Win"))) != 0)
        {
            //set font on Windows systems
            if ((int)((new HTuple((new HTuple(hv_Font_COPY_INP_TMP.TupleEqual("mono"))).TupleOr(
                                      new HTuple(hv_Font_COPY_INP_TMP.TupleEqual("Courier"))))).TupleOr(new HTuple(hv_Font_COPY_INP_TMP.TupleEqual(
                                                                                                                       "courier")))) != 0)
            {
                hv_Font_COPY_INP_TMP = "Courier New";
            }
            else if ((int)(new HTuple(hv_Font_COPY_INP_TMP.TupleEqual("sans"))) != 0)
            {
                hv_Font_COPY_INP_TMP = "Arial";
            }
            else if ((int)(new HTuple(hv_Font_COPY_INP_TMP.TupleEqual("serif"))) != 0)
            {
                hv_Font_COPY_INP_TMP = "Times New Roman";
            }
            if ((int)(new HTuple(hv_Bold_COPY_INP_TMP.TupleEqual("true"))) != 0)
            {
                hv_Bold_COPY_INP_TMP = 1;
            }
            else if ((int)(new HTuple(hv_Bold_COPY_INP_TMP.TupleEqual("false"))) != 0)
            {
                hv_Bold_COPY_INP_TMP = 0;
            }
            else
            {
                hv_Exception = "Wrong value of control parameter Bold";
                throw new HalconException(hv_Exception);
            }
            if ((int)(new HTuple(hv_Slant_COPY_INP_TMP.TupleEqual("true"))) != 0)
            {
                hv_Slant_COPY_INP_TMP = 1;
            }
            else if ((int)(new HTuple(hv_Slant_COPY_INP_TMP.TupleEqual("false"))) != 0)
            {
                hv_Slant_COPY_INP_TMP = 0;
            }
            else
            {
                hv_Exception = "Wrong value of control parameter Slant";
                throw new HalconException(hv_Exception);
            }
            try
            {
                HOperatorSet.SetFont(hv_WindowHandle, ((((((("-" + hv_Font_COPY_INP_TMP) + "-") + hv_Size_COPY_INP_TMP) + "-*-") + hv_Slant_COPY_INP_TMP) + "-*-*-") + hv_Bold_COPY_INP_TMP) + "-");
            }
            // catch (Exception)
            catch (HalconException HDevExpDefaultException1)
            {
                HDevExpDefaultException1.ToHTuple(out hv_Exception);
                throw new HalconException(hv_Exception);
            }
        }
        else
        {
            //set font for UNIX systems
            hv_Size_COPY_INP_TMP   = hv_Size_COPY_INP_TMP * 1.25;
            hv_AllowedFontSizes    = new HTuple();
            hv_AllowedFontSizes[0] = 11;
            hv_AllowedFontSizes[1] = 14;
            hv_AllowedFontSizes[2] = 17;
            hv_AllowedFontSizes[3] = 20;
            hv_AllowedFontSizes[4] = 25;
            hv_AllowedFontSizes[5] = 34;
            if ((int)(new HTuple(((hv_AllowedFontSizes.TupleFind(hv_Size_COPY_INP_TMP))).TupleEqual(
                                     -1))) != 0)
            {
                hv_Distances = ((hv_AllowedFontSizes - hv_Size_COPY_INP_TMP)).TupleAbs();
                HOperatorSet.TupleSortIndex(hv_Distances, out hv_Indices);
                hv_Size_COPY_INP_TMP = hv_AllowedFontSizes.TupleSelect(hv_Indices.TupleSelect(
                                                                           0));
            }
            if ((int)((new HTuple(hv_Font_COPY_INP_TMP.TupleEqual("mono"))).TupleOr(new HTuple(hv_Font_COPY_INP_TMP.TupleEqual(
                                                                                                   "Courier")))) != 0)
            {
                hv_Font_COPY_INP_TMP = "courier";
            }
            else if ((int)(new HTuple(hv_Font_COPY_INP_TMP.TupleEqual("sans"))) != 0)
            {
                hv_Font_COPY_INP_TMP = "helvetica";
            }
            else if ((int)(new HTuple(hv_Font_COPY_INP_TMP.TupleEqual("serif"))) != 0)
            {
                hv_Font_COPY_INP_TMP = "times";
            }
            if ((int)(new HTuple(hv_Bold_COPY_INP_TMP.TupleEqual("true"))) != 0)
            {
                hv_Bold_COPY_INP_TMP = "bold";
            }
            else if ((int)(new HTuple(hv_Bold_COPY_INP_TMP.TupleEqual("false"))) != 0)
            {
                hv_Bold_COPY_INP_TMP = "medium";
            }
            else
            {
                hv_Exception = "Wrong value of control parameter Bold";
                throw new HalconException(hv_Exception);
            }
            if ((int)(new HTuple(hv_Slant_COPY_INP_TMP.TupleEqual("true"))) != 0)
            {
                if ((int)(new HTuple(hv_Font_COPY_INP_TMP.TupleEqual("times"))) != 0)
                {
                    hv_Slant_COPY_INP_TMP = "i";
                }
                else
                {
                    hv_Slant_COPY_INP_TMP = "o";
                }
            }
            else if ((int)(new HTuple(hv_Slant_COPY_INP_TMP.TupleEqual("false"))) != 0)
            {
                hv_Slant_COPY_INP_TMP = "r";
            }
            else
            {
                hv_Exception = "Wrong value of control parameter Slant";
                throw new HalconException(hv_Exception);
            }
            try
            {
                HOperatorSet.SetFont(hv_WindowHandle, ((((((("-adobe-" + hv_Font_COPY_INP_TMP) + "-") + hv_Bold_COPY_INP_TMP) + "-") + hv_Slant_COPY_INP_TMP) + "-normal-*-") + hv_Size_COPY_INP_TMP) + "-*-*-*-*-*-*-*");
            }
            // catch (Exception)
            catch (HalconException HDevExpDefaultException1)
            {
                HDevExpDefaultException1.ToHTuple(out hv_Exception);
                throw new HalconException(hv_Exception);
            }
        }

        return;
    }
    // Procedures
    // External procedures
    // Chapter: Develop
    // Short Description: Open a new graphics window that preserves the aspect ratio of the given image.
    public void dev_open_window_fit_image(HObject ho_Image, HTuple hv_Row, HTuple hv_Column,
                                          HTuple hv_WidthLimit, HTuple hv_HeightLimit, out HTuple hv_WindowHandle)
    {
        // Local control variables

        HTuple hv_MinWidth = new HTuple(), hv_MaxWidth = new HTuple();
        HTuple hv_MinHeight = new HTuple(), hv_MaxHeight = new HTuple();
        HTuple hv_ResizeFactor, hv_ImageWidth, hv_ImageHeight;
        HTuple hv_TempWidth, hv_TempHeight, hv_WindowWidth, hv_WindowHeight;

        // Initialize local and output iconic variables

        //This procedure opens a new graphics window and adjusts the size
        //such that it fits into the limits specified by WidthLimit
        //and HeightLimit, but also maintains the correct image aspect ratio.
        //
        //If it is impossible to match the minimum and maximum extent requirements
        //at the same time (f.e. if the image is very long but narrow),
        //the maximum value gets a higher priority,
        //
        //Parse input tuple WidthLimit
        if ((int)((new HTuple((new HTuple(hv_WidthLimit.TupleLength())).TupleEqual(0))).TupleOr(
                      new HTuple(hv_WidthLimit.TupleLess(0)))) != 0)
        {
            hv_MinWidth = 500;
            hv_MaxWidth = 800;
        }
        else if ((int)(new HTuple((new HTuple(hv_WidthLimit.TupleLength())).TupleEqual(
                                      1))) != 0)
        {
            hv_MinWidth = 0;
            hv_MaxWidth = hv_WidthLimit.Clone();
        }
        else
        {
            hv_MinWidth = hv_WidthLimit[0];
            hv_MaxWidth = hv_WidthLimit[1];
        }
        //Parse input tuple HeightLimit
        if ((int)((new HTuple((new HTuple(hv_HeightLimit.TupleLength())).TupleEqual(0))).TupleOr(
                      new HTuple(hv_HeightLimit.TupleLess(0)))) != 0)
        {
            hv_MinHeight = 400;
            hv_MaxHeight = 600;
        }
        else if ((int)(new HTuple((new HTuple(hv_HeightLimit.TupleLength())).TupleEqual(
                                      1))) != 0)
        {
            hv_MinHeight = 0;
            hv_MaxHeight = hv_HeightLimit.Clone();
        }
        else
        {
            hv_MinHeight = hv_HeightLimit[0];
            hv_MaxHeight = hv_HeightLimit[1];
        }
        //
        //Test, if window size has to be changed.
        hv_ResizeFactor = 1;
        HOperatorSet.GetImageSize(ho_Image, out hv_ImageWidth, out hv_ImageHeight);
        //First, expand window to the minimum extents (if necessary).
        if ((int)((new HTuple(hv_MinWidth.TupleGreater(hv_ImageWidth))).TupleOr(new HTuple(hv_MinHeight.TupleGreater(
                                                                                               hv_ImageHeight)))) != 0)
        {
            hv_ResizeFactor = (((((hv_MinWidth.TupleReal()) / hv_ImageWidth)).TupleConcat(
                                    (hv_MinHeight.TupleReal()) / hv_ImageHeight))).TupleMax();
        }
        hv_TempWidth  = hv_ImageWidth * hv_ResizeFactor;
        hv_TempHeight = hv_ImageHeight * hv_ResizeFactor;
        //Then, shrink window to maximum extents (if necessary).
        if ((int)((new HTuple(hv_MaxWidth.TupleLess(hv_TempWidth))).TupleOr(new HTuple(hv_MaxHeight.TupleLess(
                                                                                           hv_TempHeight)))) != 0)
        {
            hv_ResizeFactor = hv_ResizeFactor * ((((((hv_MaxWidth.TupleReal()) / hv_TempWidth)).TupleConcat(
                                                       (hv_MaxHeight.TupleReal()) / hv_TempHeight))).TupleMin());
        }
        hv_WindowWidth  = hv_ImageWidth * hv_ResizeFactor;
        hv_WindowHeight = hv_ImageHeight * hv_ResizeFactor;
        //Resize window
        HOperatorSet.SetWindowAttr("background_color", "black");
        HOperatorSet.OpenWindow(hv_Row, hv_Column, hv_WindowWidth, hv_WindowHeight, 0, "", "", out hv_WindowHandle);
        HDevWindowStack.Push(hv_WindowHandle);
        if (HDevWindowStack.IsOpen())
        {
            HOperatorSet.SetPart(HDevWindowStack.GetActive(), 0, 0, hv_ImageHeight - 1, hv_ImageWidth - 1);
        }

        return;
    }
Exemple #60
0
        private void action(HTuple HDWindow_, string imgPath)
        {
            HDevWindowStack.Push(HDWindow_);
            // Local iconic variables

            HObject ho_Image, ho_DotImage, ho_Region, ho_RegionDilation;
            HObject ho_RegionClosing, ho_ConnectedRegions, ho_SelectedRegions;
            HObject ho_RegionUnion, ho_RegionClosing2, ho_ConnectedRegions2;
            HObject ho_SelectedRegions5, ho_RegionIntersection, ho_RegionAffineTrans1;
            HObject ho_rotateImage, ho_RegionDilation1, ho_RegionClosing1;
            HObject ho_RegionOpening, ho_ConnectedRegions1, ho_SelectedRegions1;
            HObject ho_RegionTrans, ho_Partitioned, ho_SelectedRegions2;
            HObject ho_RegionIntersection1, ho_SortedRegions1, ho_SelectedRegions3;
            HObject ho_RegionTrans1, ho_Partitioned1, ho_SelectedRegions4;
            HObject ho_RegionIntersection2, ho_SortedRegions2;


            // Local control variables

            HTuple hv_Row, hv_Column, hv_Phi, hv_Length1;
            HTuple hv_Length2, hv_HomMat2DIdentity, hv_HomMat2DRotate;
            HTuple hv_Area, hv_Row1, hv_Column1, hv_Area11, hv_Row11;
            HTuple hv_Column11, hv_Number1, hv_OCRHandle, hv_Chars1;
            HTuple hv_Confidence1, hv_Area12, hv_Row12, hv_Column12;
            HTuple hv_Number2, hv_Chars2, hv_Confidence2;

            // Initialize local and output iconic variables
            HOperatorSet.GenEmptyObj(out ho_Image);
            HOperatorSet.GenEmptyObj(out ho_DotImage);
            HOperatorSet.GenEmptyObj(out ho_Region);
            HOperatorSet.GenEmptyObj(out ho_RegionDilation);
            HOperatorSet.GenEmptyObj(out ho_RegionClosing);
            HOperatorSet.GenEmptyObj(out ho_ConnectedRegions);
            HOperatorSet.GenEmptyObj(out ho_SelectedRegions);
            HOperatorSet.GenEmptyObj(out ho_RegionUnion);
            HOperatorSet.GenEmptyObj(out ho_RegionClosing2);
            HOperatorSet.GenEmptyObj(out ho_ConnectedRegions2);
            HOperatorSet.GenEmptyObj(out ho_SelectedRegions5);
            HOperatorSet.GenEmptyObj(out ho_RegionIntersection);
            HOperatorSet.GenEmptyObj(out ho_RegionAffineTrans1);
            HOperatorSet.GenEmptyObj(out ho_rotateImage);
            HOperatorSet.GenEmptyObj(out ho_RegionDilation1);
            HOperatorSet.GenEmptyObj(out ho_RegionClosing1);
            HOperatorSet.GenEmptyObj(out ho_RegionOpening);
            HOperatorSet.GenEmptyObj(out ho_ConnectedRegions1);
            HOperatorSet.GenEmptyObj(out ho_SelectedRegions1);
            HOperatorSet.GenEmptyObj(out ho_RegionTrans);
            HOperatorSet.GenEmptyObj(out ho_Partitioned);
            HOperatorSet.GenEmptyObj(out ho_SelectedRegions2);
            HOperatorSet.GenEmptyObj(out ho_RegionIntersection1);
            HOperatorSet.GenEmptyObj(out ho_SortedRegions1);
            HOperatorSet.GenEmptyObj(out ho_SelectedRegions3);
            HOperatorSet.GenEmptyObj(out ho_RegionTrans1);
            HOperatorSet.GenEmptyObj(out ho_Partitioned1);
            HOperatorSet.GenEmptyObj(out ho_SelectedRegions4);
            HOperatorSet.GenEmptyObj(out ho_RegionIntersection2);
            HOperatorSet.GenEmptyObj(out ho_SortedRegions2);

            ho_Image.Dispose();
            HOperatorSet.ReadImage(out ho_Image, imgPath);
            ho_DotImage.Dispose();
            HOperatorSet.DotsImage(ho_Image, out ho_DotImage, 5, "dark", 2);
            ho_Region.Dispose();
            HOperatorSet.Threshold(ho_DotImage, out ho_Region, 110, 255);
            ho_RegionDilation.Dispose();
            HOperatorSet.DilationCircle(ho_Region, out ho_RegionDilation, 2.5);
            ho_RegionClosing.Dispose();
            HOperatorSet.ClosingRectangle1(ho_RegionDilation, out ho_RegionClosing, 3, 3);
            ho_ConnectedRegions.Dispose();
            HOperatorSet.Connection(ho_RegionClosing, out ho_ConnectedRegions);
            ho_SelectedRegions.Dispose();
            HOperatorSet.SelectShape(ho_ConnectedRegions, out ho_SelectedRegions, (new HTuple("width")).TupleConcat(
                                         "height"), "and", (new HTuple(15)).TupleConcat(15), (new HTuple(80)).TupleConcat(
                                         80));
            ho_RegionUnion.Dispose();
            HOperatorSet.Union1(ho_SelectedRegions, out ho_RegionUnion);
            ho_RegionClosing2.Dispose();
            HOperatorSet.ClosingRectangle1(ho_RegionUnion, out ho_RegionClosing2, 30, 20);
            ho_ConnectedRegions2.Dispose();
            HOperatorSet.Connection(ho_RegionClosing2, out ho_ConnectedRegions2);
            ho_SelectedRegions5.Dispose();
            HOperatorSet.SelectShape(ho_ConnectedRegions2, out ho_SelectedRegions5, "area",
                                     "and", 10000, 20000);

            ho_RegionIntersection.Dispose();
            HOperatorSet.Intersection(ho_Region, ho_SelectedRegions5, out ho_RegionIntersection
                                      );
            HOperatorSet.SmallestRectangle2(ho_RegionIntersection, out hv_Row, out hv_Column,
                                            out hv_Phi, out hv_Length1, out hv_Length2);
            HOperatorSet.HomMat2dIdentity(out hv_HomMat2DIdentity);
            HOperatorSet.HomMat2dRotate(hv_HomMat2DIdentity, -hv_Phi, hv_Column, hv_Row,
                                        out hv_HomMat2DRotate);
            ho_RegionAffineTrans1.Dispose();
            HOperatorSet.AffineTransRegion(ho_RegionIntersection, out ho_RegionAffineTrans1,
                                           hv_HomMat2DRotate, "true");
            ho_rotateImage.Dispose();
            HOperatorSet.AffineTransImage(ho_Image, out ho_rotateImage, hv_HomMat2DRotate,
                                          "bilinear", "false");
            ho_RegionDilation1.Dispose();
            HOperatorSet.DilationCircle(ho_RegionAffineTrans1, out ho_RegionDilation1, 2.5);
            ho_RegionClosing1.Dispose();
            HOperatorSet.ClosingRectangle1(ho_RegionDilation1, out ho_RegionClosing1, 3,
                                           3);
            ho_RegionOpening.Dispose();
            HOperatorSet.OpeningCircle(ho_RegionClosing1, out ho_RegionOpening, 2.5);
            ho_ConnectedRegions1.Dispose();
            HOperatorSet.Connection(ho_RegionOpening, out ho_ConnectedRegions1);
            HOperatorSet.AreaCenter(ho_RegionAffineTrans1, out hv_Area, out hv_Row1, out hv_Column1);

            ho_SelectedRegions1.Dispose();
            HOperatorSet.SelectShape(ho_ConnectedRegions1, out ho_SelectedRegions1, "row",
                                     "and", hv_Row1 - 30, hv_Row1);
            ho_RegionTrans.Dispose();
            HOperatorSet.ShapeTrans(ho_SelectedRegions1, out ho_RegionTrans, "rectangle1");
            ho_Partitioned.Dispose();
            HOperatorSet.PartitionDynamic(ho_RegionTrans, out ho_Partitioned, 20, 20);
            ho_SelectedRegions2.Dispose();
            HOperatorSet.SelectShape(ho_Partitioned, out ho_SelectedRegions2, "height", "and",
                                     25, 48);
            ho_RegionIntersection1.Dispose();
            HOperatorSet.Intersection(ho_SelectedRegions2, ho_RegionAffineTrans1, out ho_RegionIntersection1
                                      );
            ho_SortedRegions1.Dispose();
            HOperatorSet.SortRegion(ho_RegionIntersection1, out ho_SortedRegions1, "first_point",
                                    "true", "column");
            HOperatorSet.AreaCenter(ho_SortedRegions1, out hv_Area11, out hv_Row11, out hv_Column11);
            HOperatorSet.CountObj(ho_SortedRegions1, out hv_Number1);
            //FontFile := 'D:/github/CodeRecognition/tzb1112.omc'
            HOperatorSet.ReadOcrClassMlp("C:/Program Files/MVTec/HALCON-10.0/ocr/DotPrint_0-9A-Z.omc",
                                         out hv_OCRHandle);
            HOperatorSet.DoOcrMultiClassMlp(ho_SortedRegions1, ho_rotateImage, hv_OCRHandle,
                                            out hv_Chars1, out hv_Confidence1);

            ho_SelectedRegions3.Dispose();
            HOperatorSet.SelectShape(ho_ConnectedRegions1, out ho_SelectedRegions3, "row",
                                     "and", hv_Row1, hv_Row1 + 40);
            ho_RegionTrans1.Dispose();
            HOperatorSet.ShapeTrans(ho_SelectedRegions3, out ho_RegionTrans1, "rectangle1");
            ho_Partitioned1.Dispose();
            HOperatorSet.PartitionDynamic(ho_RegionTrans1, out ho_Partitioned1, 20, 1);
            ho_SelectedRegions4.Dispose();
            HOperatorSet.SelectShape(ho_Partitioned1, out ho_SelectedRegions4, "height",
                                     "and", 25, 48);
            ho_RegionIntersection2.Dispose();
            HOperatorSet.Intersection(ho_SelectedRegions4, ho_RegionAffineTrans1, out ho_RegionIntersection2
                                      );
            ho_SortedRegions2.Dispose();
            HOperatorSet.SortRegion(ho_RegionIntersection2, out ho_SortedRegions2, "first_point",
                                    "true", "column");
            HOperatorSet.AreaCenter(ho_SortedRegions2, out hv_Area12, out hv_Row12, out hv_Column12);
            HOperatorSet.CountObj(ho_SortedRegions2, out hv_Number2);
            HOperatorSet.DoOcrMultiClassMlp(ho_SortedRegions2, ho_rotateImage, hv_OCRHandle,
                                            out hv_Chars2, out hv_Confidence2);

            //word := ['d']
            //TrainFile := 'D:/github/CodeRecognition/tzb1112.trf'
            //dev_set_check ('~give_error')
            //delete_file (TrainFile)
            //dev_set_check ('~give_error')
            //for i := 7 to Number2 by 1
            //select_obj (SortedRegions2, SingleWord, i)
            //append_ocr_trainf (SingleWord, rotateImage, word, TrainFile)
            //endfor
            //read_ocr_trainf_names (TrainFile, CharacterNames, CharacterCount)
            //trainf_ocr_class_mlp (OCRHandle, TrainFile, 200, 1, 0.01, Error, ErrorLog)
            //write_ocr_class_mlp (OCRHandle, FontFile)

            //120, 68, 147, 183, 188, 0, 0, 107, 162, 197, 138, 0, 123
            //120, 68, 147, 183, 146, 202, 0, 107, 162, 197, 138, 169, 123
            if (HDevWindowStack.IsOpen())
            {
                HOperatorSet.ClearWindow(HDevWindowStack.GetActive());
            }
            if (HDevWindowStack.IsOpen())
            {
                HOperatorSet.DispObj(ho_Image, HDevWindowStack.GetActive());
            }
            if (HDevWindowStack.IsOpen())
            {
                HOperatorSet.SetColor(HDevWindowStack.GetActive(), "blue");
            }
            if (HDevWindowStack.IsOpen())
            {
                HOperatorSet.DispObj(ho_SortedRegions1, HDevWindowStack.GetActive());
            }
            if (HDevWindowStack.IsOpen())
            {
                HOperatorSet.DispObj(ho_SortedRegions2, HDevWindowStack.GetActive());
            }

            ho_Image.Dispose();
            ho_DotImage.Dispose();
            ho_Region.Dispose();
            ho_RegionDilation.Dispose();
            ho_RegionClosing.Dispose();
            ho_ConnectedRegions.Dispose();
            ho_SelectedRegions.Dispose();
            ho_RegionUnion.Dispose();
            ho_RegionClosing2.Dispose();
            ho_ConnectedRegions2.Dispose();
            ho_SelectedRegions5.Dispose();
            ho_RegionIntersection.Dispose();
            ho_RegionAffineTrans1.Dispose();
            ho_rotateImage.Dispose();
            ho_RegionDilation1.Dispose();
            ho_RegionClosing1.Dispose();
            ho_RegionOpening.Dispose();
            ho_ConnectedRegions1.Dispose();
            ho_SelectedRegions1.Dispose();
            ho_RegionTrans.Dispose();
            ho_Partitioned.Dispose();
            ho_SelectedRegions2.Dispose();
            ho_RegionIntersection1.Dispose();
            ho_SortedRegions1.Dispose();
            ho_SelectedRegions3.Dispose();
            ho_RegionTrans1.Dispose();
            ho_Partitioned1.Dispose();
            ho_SelectedRegions4.Dispose();
            ho_RegionIntersection2.Dispose();
            ho_SortedRegions2.Dispose();

            //errorCounts = hv_errorCounts;
            RecognitionStr1 = hv_Chars1;
            RecognitionStr2 = hv_Chars2;
        }