Ejemplo n.º 1
0
        /// <summary>
        /// 计算出每个Pin针的偏移量
        /// </summary>
        /// <param name="InspectPinParamIn"></param>
        /// <param name="PinRows"></param>
        /// <param name="PinCols"></param>
        /// <param name="OffSetRows"></param>
        /// <param name="OffSetCols"></param>
        /// <param name="OffSetDist"></param>
        /// <returns></returns>
        public static bool CalculatePinOffset(St_InspectPinParam InspectPinParamIn, HTuple PinRows, HTuple PinCols, out HTuple OffSetRows, out HTuple OffSetCols, out HTuple OffSetDist)
        {
            OffSetRows = new HTuple();
            OffSetCols = new HTuple();
            OffSetDist = new HTuple();
            HTuple TeachPinRows = new HTuple(), TeachPinCols = new HTuple();

            for (int i = 0; i < InspectPinParamIn.Elements.Count(); i++)
            {
                HTuple row0 = new HTuple(), col0 = new HTuple();
                MyVisionBase.ListToHTuple(InspectPinParamIn.ListRows[i], out row0);
                MyVisionBase.ListToHTuple(InspectPinParamIn.ListCols[i], out col0);
                TeachPinRows = TeachPinRows.TupleConcat(row0);
                TeachPinCols = TeachPinCols.TupleConcat(col0);
            }
            HTuple HomMat = new HTuple();

            HOperatorSet.VectorToHomMat2d(TeachPinCols, TeachPinRows, PinCols, PinRows, out HomMat); //计算平移矩阵
            HTuple TargetRows = new HTuple(), TargetCols = new HTuple();

            HOperatorSet.AffineTransPixel(HomMat, TeachPinCols, TeachPinRows, out TargetCols, out TargetRows); //平移示教点的坐标
            if (TargetRows.Length != TeachPinRows.Length)
            {
                return(false);
            }
            HTuple OffSetRows0 = new HTuple(), OffSetCols0 = new HTuple(), OffSetDist0 = new HTuple();

            OffSetCols0 = PinCols - TargetCols;
            OffSetRows0 = PinRows - TargetRows;
            HOperatorSet.DistancePp(TargetRows, TargetCols, PinRows, PinCols, out OffSetDist0); //计算出偏移量
            OffSetRows = OffSetRows0;
            OffSetCols = OffSetCols0;
            OffSetDist = OffSetDist0;
            return(true);
        }
Ejemplo n.º 2
0
        ///<summary>
        ///创建直线检测模板(仿射变换)
        ///</summary>
        public void CreateLineModel(HTuple hv_HomMat2D, HTuple hv_MeasureRow1, HTuple hv_MeasureColumn1, HTuple hv_MeasureRow2, HTuple hv_MeasureColumn2,
                                    HTuple hv_MeasureLength1, HTuple hv_MeasureLength2, HTuple hv_MeasureSigma, HTuple hv_MeasureThreshold, out HTuple hv_MetrologyHandle, out HTuple hv_Index)
        {
            HTuple mhv_Row1;
            HTuple mhv_Column1;
            HTuple mhv_Row2;
            HTuple mhv_Column2;

            HTuple mhv_MetrologyHandle = new HTuple();

            hv_Index           = new HTuple();
            hv_MetrologyHandle = new HTuple();

            try
            {
                HOperatorSet.ClearMetrologyModel(mhv_MetrologyHandle);
                HOperatorSet.CreateMetrologyModel(out hv_MetrologyHandle);

                HOperatorSet.AffineTransPixel(hv_HomMat2D, hv_MeasureRow1, hv_MeasureColumn1, out mhv_Row1, out mhv_Column1);
                HOperatorSet.AffineTransPixel(hv_HomMat2D, hv_MeasureRow2, hv_MeasureColumn2, out mhv_Row2, out mhv_Column2);

                HOperatorSet.DistancePp(mhv_Row1, mhv_Column1, mhv_Row2, mhv_Column2, out HTuple DistancePp);
                hv_MeasureLength2 = DistancePp / 2;
                HOperatorSet.AddMetrologyObjectLineMeasure(mhv_MetrologyHandle, mhv_Row1, mhv_Column1, mhv_Row2, mhv_Column2,
                                                           hv_MeasureLength1, hv_MeasureLength2, hv_MeasureSigma, hv_MeasureThreshold,
                                                           new HTuple(), new HTuple(), out hv_Index);

                hv_MetrologyHandle = mhv_MetrologyHandle;
                return;
            }
            catch (Exception)
            {
                return;
            }
        }
Ejemplo n.º 3
0
        public void MeasureAll(HObject image, double row, double column, double radian)
        {
            foreach (var mea in MeasureList)
            {
                //仿射变换测量位置
                HTuple rowTrans, columnTrans;
                HTuple homMat2D;
                HOperatorSet.AffineTransPixel(mea.PosHomMat2d, row, column, out rowTrans, out columnTrans);
                HOperatorSet.HomMat2dIdentity(out homMat2D);
                HOperatorSet.HomMat2dRotate(homMat2D, radian - mea.ModelRadian, row, column, out homMat2D);
                HOperatorSet.AffineTransPixel(homMat2D, rowTrans, columnTrans, out rowTrans, out columnTrans);


                HObject contour;
                mea.MeasurePinCount(image, rowTrans, columnTrans, radian, out mea.LineEdge, out contour);

                if (mea.PinCount == mea.CountPinMea)
                {
                    mea.ContourOk = contour;
                }
                else
                {
                    mea.ContourAreaNG = contour;
                }

                //mea.ClearResult();

                //HTuple rowTrans, columnTrans;
                //HOperatorSet.AffineTransPixel(mea.PosHomMat2d, row, column, out rowTrans, out columnTrans);

                //mea.Gen(rowTrans, columnTrans, radian);
                //mea.MeasurePos(image);
                //mea.Close();
            }
        }
Ejemplo n.º 4
0
        public override int Measure(HObject ho_Image)                                 //测量
        {
            measureResult = Result.OK;                                                //测量结果初始OK
            try { ho_ROI.Dispose(); } catch (Exception) { }//释放ho_ROI资源
            Rectangle2 ROI = parameter.rectangle2.GetShapePositioned() as Rectangle2; //获取ROI矩形

            ho_ROI = Func_HalconFunction.GenRectangle2(ROI);                          //创建ROI
            //灰度处理,并选出最大面积
            try { ho_SelectedRegions.Dispose(); } catch (Exception) { }//释放ho_SelectedRegions资源
            ho_SelectedRegions = Func_ImageProcessing.Threshold_SelectMaxRegion(ho_Image, ho_ROI, parameter.hv_MinGray, parameter.hv_MaxGray);
            if (ROI.hv_Phi.D != 0)//角度不为零?
            {
                //hv_HomMat2D;//变换矩阵
                HOperatorSet.VectorAngleToRigid(ROI.hv_Row, ROI.hv_Column, 0, ROI.hv_Row, ROI.hv_Column, -ROI.hv_Phi, out HTuple hv_HomMat2D); //将区域旋转为水平的变换矩阵
                // ho_RegionRotate;//水平后的Region
                HOperatorSet.AffineTransRegion(ho_SelectedRegions, out HObject ho_RegionRotate, hv_HomMat2D, "nearest_neighbor");              //应用变换
                SetLine(Func_ImageProcessing.getLine_FromRegion(ho_RegionRotate, TPLR, b, AngularPoint));                                      //从区域获取线
                HOperatorSet.VectorAngleToRigid(ROI.hv_Row, ROI.hv_Column, 0, ROI.hv_Row, ROI.hv_Column, ROI.hv_Phi, out hv_HomMat2D);         //将线从水平变回原角度的变换矩阵
                HOperatorSet.AffineTransPixel(hv_HomMat2D, hv_Row1, hv_Column1, out hv_Row1, out hv_Column1);                                  //应用变换
                HOperatorSet.AffineTransPixel(hv_HomMat2D, hv_Row2, hv_Column2, out hv_Row2, out hv_Column2);                                  //应用变换
            }
            else
            {
                SetLine(Func_ImageProcessing.getLine_FromRegion(ho_SelectedRegions, TPLR, b, AngularPoint));//从区域获取线
            }
            if (DP == null)
            {
                DP = new Point(0, 0);
            }
            DP.hv_Column = (hv_Column1);
            DP.hv_Row    = (hv_Row1);
            AxByC0       = AxByC0.GetAxByC(this); //求该线的一半直线方程
            MeasureDone  = true;                  //已测量标志为true
            return(Convert.ToInt32(measureResult));
        }
        public bool setTarget(List <HHomMat2D> mat2DsList)
        {
            if (mat2DsList == null || mat2DsList.Count < 1)
            {
                return(false);
            }

            if (GrabXld != null && GrabXld.IsInitialized())
            {
                GrabXld.Dispose();
            }
            else
            {
                GrabXld = new HXLDCont();
                GrabXld.GenEmptyObj();
            }

            GrabRowTarget = new HTuple();
            GrabColTarget = new HTuple();
            HTuple rowTemp, colTemp;

            for (int i = 0; i < mat2DsList.Count; i++)
            {
                HOperatorSet.AffineTransPixel(mat2DsList[i], new HTuple(GrabRowOrg), new HTuple(GrabColOrg), out rowTemp, out colTemp);
                GrabRowTarget = GrabRowTarget.TupleConcat(rowTemp);
                GrabColTarget = GrabColTarget.TupleConcat(colTemp);
            }
            return(true);
        }
Ejemplo n.º 6
0
 /// <summary>
 /// 获取逆变后的实例
 /// </summary>
 /// <returns></returns>
 public override BaseShape GetShapeInvert()
 {
     base.GetShapeInvert();
     GetHomMat2D();
     HOperatorSet.AffineTransPixel(hv_HomMat2DInvert, hv_Row1, hv_Column1, out hv_Row1, out hv_Column1);
     HOperatorSet.AffineTransPixel(hv_HomMat2DInvert, hv_Row2, hv_Column2, out hv_Row2, out hv_Column2);
     return(this);
 }
Ejemplo n.º 7
0
        ///<summary>
        ///直线拟合(仿射变换)
        ///</summary>
        public void FindLine(HTuple hv_HomMat2DPix, HObject ho_Image, HTuple hv_MetrologyHandle, HTuple hv_Index, HTuple hv_MeasureNumInstances, HTuple hv_MeasureDistThreshold, HTuple hv_MeasureTransition,
                             HTuple hv_MeasureSelect, HTuple hv_MeasurePointsNum, HTuple hv_MeasureMinScore, HTuple hv_MaxNumIterations, HTuple hv_MeasureInterpolation, HTuple hv_MeasureIORegions,
                             out HTuple hv_CrossRow, out HTuple hv_CrossColumn, out HTuple hv_LineRowBegin_Real, out HTuple hv_LineColumnBegin_Real, out HTuple hv_LineRowEnd_Real, out HTuple hv_LineColumnEnd_Real)
        {
            HObject ho_Contours        = new HObject();
            HTuple  hv_LineRowBegin    = new HTuple();
            HTuple  hv_LineColumnBegin = new HTuple();
            HTuple  hv_LineRowEnd      = new HTuple();
            HTuple  hv_LineColumnEnd   = new HTuple();

            hv_CrossRow             = new HTuple();
            hv_CrossColumn          = new HTuple();
            hv_LineRowBegin_Real    = new HTuple();
            hv_LineColumnBegin_Real = new HTuple();
            hv_LineRowEnd_Real      = new HTuple();
            hv_LineColumnEnd_Real   = new HTuple();

            try
            {
                //1.直线拟合数量:默认值: 1 值的列表: 1,2,3,4
                HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, hv_Index, "num_instances", hv_MeasureNumInstances);
                //2.距离剔除:默认值: 3.5  值的列表: 0,1.0,2.0, 3.5,5.0
                HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, hv_Index, "distance_threshold", hv_MeasureDistThreshold);
                //3.明暗方向:值列表: 'all','negative', 'positive','uniform'
                HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, hv_Index, "measure_transition", hv_MeasureTransition);
                //4.边缘选取:'all','first','last'
                HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, hv_Index, "measure_select", hv_MeasureSelect);
                //5.Roi数量:'num_measures'
                HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, hv_Index, "num_measures", hv_MeasurePointsNum);
                //6.最小得分:'min_score'
                HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, hv_Index, "min_score", hv_MeasureMinScore);
                //7.迭代次数: 默认值:-1  值的列表: 10,100,1000
                HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, hv_Index, "max_num_iterations", hv_MaxNumIterations);
                //8.插值类型:nearest_neighbor'灰度值是从最近像素的灰度值获得;'bilinear',使用双线性插值 ;'bicubic',则使用双三次插值。
                HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, hv_Index, "measure_interpolation", hv_MeasureInterpolation);
                //9.指定对测量结果的验证:默认值: “ false”  值列表: 'true','false'
                HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, hv_Index, "instances_outside_measure_regions", hv_MeasureIORegions);

                HOperatorSet.ApplyMetrologyModel(ho_Image, hv_MetrologyHandle);
                HOperatorSet.GetMetrologyObjectMeasures(out ho_Contours, hv_MetrologyHandle, "all", "all", out hv_CrossRow, out hv_CrossColumn);
                HOperatorSet.GetMetrologyObjectResult(hv_MetrologyHandle, "all", "all", "result_type", "row_begin", out hv_LineRowBegin);
                HOperatorSet.GetMetrologyObjectResult(hv_MetrologyHandle, "all", "all", "result_type", "column_begin", out hv_LineColumnBegin);
                HOperatorSet.GetMetrologyObjectResult(hv_MetrologyHandle, "all", "all", "result_type", "row_end", out hv_LineRowEnd);
                HOperatorSet.GetMetrologyObjectResult(hv_MetrologyHandle, "all", "all", "result_type", "column_end", out hv_LineColumnEnd);

                HOperatorSet.AffineTransPixel(hv_HomMat2DPix, hv_LineRowBegin, hv_LineColumnBegin, out hv_LineRowBegin_Real, out hv_LineColumnBegin_Real);
                HOperatorSet.AffineTransPixel(hv_HomMat2DPix, hv_LineRowEnd, hv_LineColumnEnd, out hv_LineRowEnd_Real, out hv_LineColumnEnd_Real);

                //清除测量模型
                ho_Contours.Dispose();
                HOperatorSet.ClearMetrologyModel(hv_MetrologyHandle);
                return;
            }
            catch (Exception)
            {
                return;
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// 获取逆变后的实例
        /// </summary>
        /// <returns></returns>
        public override BaseShape GetShapeInvert()
        {
            base.GetShapeInvert();
            HOperatorSet.AffineTransPixel(hv_HomMat2DInvert, hv_Row, hv_Column, out hv_Row, out hv_Column);
            HTuple h1, h2, hv_phi, h4, h5, h6;

            HOperatorSet.HomMat2dToAffinePar(hv_HomMat2DInvert, out h1, out h2, out hv_phi, out h4, out h5, out h6);
            hv_Phi += hv_phi;
            return(this);
        }
Ejemplo n.º 9
0
        public override BaseShape GetShapePositioned()                                                 //获取定位后的实例
        {
            Rectangle2 rectangle2 = new Rectangle2(hv_Row, hv_Column, hv_Phi, hv_Length1, hv_Length2); //要返回的对象

            GetHomMat2D();
            HOperatorSet.AffineTransPixel(hv_HomMat2DTranslat_H, rectangle2.hv_Row, rectangle2.hv_Column, out rectangle2.hv_Row, out rectangle2.hv_Column);

            HOperatorSet.AffineTransPixel(hv_HomMat2DTranslate_VL, rectangle2.hv_Row, rectangle2.hv_Column, out rectangle2.hv_Row, out rectangle2.hv_Column);

            return(rectangle2);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// 获取定位后的实例
        /// </summary>
        /// <returns></returns>
        public override BaseShape GetShapePositioned()
        {
            Circle circle = new Circle(hv_Row, hv_Column, hv_Radius);

            GetHomMat2D();

            HOperatorSet.AffineTransPixel(hv_HomMat2DTranslat_H, circle.hv_Row, circle.hv_Column, out circle.hv_Row, out circle.hv_Column);   //水平

            HOperatorSet.AffineTransPixel(hv_HomMat2DTranslate_VL, circle.hv_Row, circle.hv_Column, out circle.hv_Row, out circle.hv_Column); //垂直

            return(circle);
        }
Ejemplo n.º 11
0
        public XYUPoint GetAffineTransPointAffterMatch(double VisionPointOnModleImgX, double VisionPointOnModleImgY, XYUPoint NowVisionDstModlePoint, VisionControl visionControl = null)
        {
            HOperatorSet.VectorAngleToRigid(visionShapParam.ModlePoint.y, visionShapParam.ModlePoint.x, visionShapParam.ModlePoint.u,
                                            NowVisionDstModlePoint.y, NowVisionDstModlePoint.x, NowVisionDstModlePoint.u, out HTuple hom2d);

            HOperatorSet.AffineTransPixel(hom2d, VisionPointOnModleImgY, VisionPointOnModleImgX, out HTuple rowTrans, out HTuple colTrans);
            if (visionControl != null && visionControl.isOpen())
            {
                HOperatorSet.SetColor(visionControl.GetHalconWindow(), "blue");
                HOperatorSet.DispCross(visionControl.GetHalconWindow(), rowTrans, colTrans, 80, 0);
            }
            XYUPoint NowResultPoint = new XYUPoint(colTrans[0].D, rowTrans[0].D, 0);

            return(NowResultPoint);
        }
Ejemplo n.º 12
0
        public override BaseShape GetShapePositioned()                      //获取定位后的实例
        {
            Line line = new Line(hv_Column1, hv_Row1, hv_Column2, hv_Row2); //要返回的对象

            GetHomMat2D();

            HOperatorSet.AffineTransPixel(hv_HomMat2DTranslat_H, line.hv_Row1, line.hv_Column1, out line.hv_Row1, out line.hv_Column1);   //水平

            HOperatorSet.AffineTransPixel(hv_HomMat2DTranslate_VL, line.hv_Row1, line.hv_Column1, out line.hv_Row1, out line.hv_Column1); //垂直左

            HOperatorSet.AffineTransPixel(hv_HomMat2DTranslate_VR, line.hv_Row2, line.hv_Column2, out line.hv_Row2, out line.hv_Column2); //垂直右

            line.AxByC0.GetAxByC(line);
            return(line);//返回对象
        }
Ejemplo n.º 13
0
        /// <summary>
        /// 获取对应Laser点和Pin的 现况下的位置
        /// </summary>
        /// <param name="OldVisoionModlePos">模板视觉坐标位置</param>
        /// <param name="NowVisionModlePos">现在匹配模板视觉坐标位置</param>
        /// <param name="OldSnapModlePos">模板拍照机械位置</param>
        /// <param name="OldPinMachinePos">开始设置的Pin机械位置</param>
        /// <param name=""></param>
        /// <returns></returns>

        public XYUPoint GetDispOrLaserPoint2(XYUPoint OldVisoionModlePos, XYUPoint NowVisionModlePos, XYUPoint OldSnapModlePos, XYUPoint OldPinMachinePos, XYUPoint NowSnapMchinePos)
        {
            HOperatorSet.VectorAngleToRigid(OldVisoionModlePos.x, OldVisoionModlePos.y, OldVisoionModlePos.u, NowVisionModlePos.x, NowVisionModlePos.y, NowVisionModlePos.u, out HTuple hom2d);

            HTuple   vx, vy;
            XYUPoint machineXY = new XYUPoint(OldSnapModlePos.x - OldPinMachinePos.x, OldSnapModlePos.y - OldPinMachinePos.y, 0);

            HOperatorSet.AffineTransPoint2d(m_Hom2Drtu, machineXY.x, machineXY.y, out vx, out vy);

            HTuple qvx, qvy;

            HOperatorSet.AffineTransPixel(hom2d, vx, vy, out qvx, out qvy);

            XYUPoint NowPinMachinePoint = GetDstPonit(new XYUPoint(qvx, qvy, 0), NowSnapMchinePos);


            return(NowPinMachinePoint);
        }
Ejemplo n.º 14
0
        public bool CreateLineModel(HTuple hv_HomMat2D)
        {
            try
            {
                HOperatorSet.ClearMetrologyModel(hv_MetrologyHandle);
                HOperatorSet.CreateMetrologyModel(out hv_MetrologyHandle);
                if (ho_Image == null)
                {
                    return(false);
                }

                HOperatorSet.GetImageSize(ho_Image, out hv_Width, out hv_Height);

                if (hv_Row1.Length < 1)
                {
                    return(false);
                }

                HTuple mhv_Row1;
                HTuple mhv_Column1;
                HTuple mhv_Row2;
                HTuple mhv_Column2;

                HOperatorSet.AffineTransPixel(hv_HomMat2D, hv_Row1, hv_Column1, out mhv_Row1, out mhv_Column1);
                HOperatorSet.AffineTransPixel(hv_HomMat2D, hv_Row2, hv_Column2, out mhv_Row2, out mhv_Column2);

                HOperatorSet.AddMetrologyObjectLineMeasure(hv_MetrologyHandle, mhv_Row1, mhv_Column1, mhv_Row2, mhv_Column2,
                                                           hv_MeasureLength1, hv_MeasureLength2, hv_MeasureSigma, hv_MeasureThreshold,
                                                           hv_GenParamName, hv_GenParamValue, out hv_Index);

                errorFlag = false;
                return(true);
            }
            catch (Exception exc)
            {
                errorFlag = true;
                return(false);
            }
        }
Ejemplo n.º 15
0
 public static bool affineTransPixel(HTuple initialRow, HTuple initialCol, HTuple checkRow, HTuple checkCol, HTuple checkPhi, out HTuple tansRow, out HTuple transCol)
 {
     try
     {
         HTuple hv_HomMat2D       = new HTuple();
         HTuple homMat2DTranslate = new HTuple();
         HTuple homMat2DRotate    = new HTuple();
         hv_HomMat2D.Dispose();
         homMat2DTranslate.Dispose();
         homMat2DRotate.Dispose();
         HOperatorSet.HomMat2dIdentity(out hv_HomMat2D);
         HOperatorSet.HomMat2dTranslate(hv_HomMat2D, checkRow, checkCol, out homMat2DTranslate);
         HOperatorSet.HomMat2dRotate(homMat2DTranslate, checkPhi, checkRow, checkCol, out homMat2DRotate);
         HOperatorSet.AffineTransPixel(homMat2DRotate, initialRow, initialCol, out tansRow, out transCol);
         return(true);
     }
     catch (Exception)
     {
         tansRow  = -1;
         transCol = -1;
         return(false);
     }
 }
        /// <summary>
        /// 测量所有碳点
        /// </summary>
        /// <param name="image"></param>
        /// <param name="row"></param>
        /// <param name="column"></param>
        /// <param name="radian"></param>
        public void MeasureAll(HObject image, double row, double column, double radian)
        {
            HObject contour;

            ExtractContourXld(image, out contour);


            foreach (var mea in MeasureList)
            {
                mea.ClearResult();

                HTuple rowTrans, columnTrans;
                HOperatorSet.AffineTransPixel(mea.PosHomMat2d, row, column, out rowTrans, out columnTrans);

                HTuple homMat2D;
                HOperatorSet.HomMat2dIdentity(out homMat2D);
                HOperatorSet.HomMat2dRotate(homMat2D, radian - mea.ModelRadian, row, column, out homMat2D);
                HOperatorSet.AffineTransPixel(homMat2D, rowTrans, columnTrans, out rowTrans, out columnTrans);

                mea.Gen(rowTrans, columnTrans, radian);
                mea.MeasurePos(image, contour);
                mea.Close();
            }
        }
Ejemplo n.º 17
0
            public void MeasurePinCount(HObject image, double row, double column, double radian, out HObject region, out HObject contour)
            {
                //仿射变换测量位置
                //HTuple rowTrans, columnTrans;
                //HOperatorSet.AffineTransPixel(PosHomMat2d, row, column, out rowTrans, out columnTrans);

                HOperatorSet.GenEmptyObj(out contour);
                HOperatorSet.GenRectangle2ContourXld(out region, row, column, radian + PosRadianDiff, Width / 2, Height / 2);

                //生成水平方向测量矩形
                HOperatorSet.GenMeasureRectangle2(row, column, radian + PosRadianDiff, Width / 2, Height / 2,
                                                  ImageWidth, ImageHeight, Interpolation, out Handle1);

                //测量边缘对
                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();

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

                if (intraDistance.Length > 0)
                {
                    HTuple minMea = 0, maxMea = 0;
                    HOperatorSet.TupleMin(intraDistance, out minMea);
                    HOperatorSet.TupleMax(intraDistance, out maxMea);

                    if (LimiteDiameterMin <= 0)
                    {
                        LimiteDiameterMin = minMea - 5;
                    }

                    if (LimiteDiameterMax <= 0)
                    {
                        LimiteDiameterMax = maxMea * 1.5;
                    }
                }

                //测量出来的针脚数量
                CountPinMea = 0;

                //显示
                for (int j = 0; j < intraDistance.Length; j++)
                {
                    if (intraDistance[j] < LimiteDiameterMin || intraDistance[j] > LimiteDiameterMax)
                    {
                        continue;
                    }

                    CountPinMea++;

                    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);
                }

                //关闭测量矩形
                HOperatorSet.CloseMeasure(Handle1);
            }
        private void btnDrawCalib_Click(object sender, EventArgs e)
        {
            if (vision.imgSrc == null || !vision.imgSrc.IsInitialized())
            {
                return;
            }

            groupBox1.Enabled = false;
            visionControl1.Focus();
            visionControl1.MouseMode = VisionControl.WindowMouseMode.Select;
            HOperatorSet.SetColor(visionControl1.GetHalconWindow(), "red");

            var v = vision as ProcessSideMea;

            v.CloseNeedle();
            visionControl1.DisplayResults();

            HObject rect;
            HTuple  row, column, radian, length1, length2, imageWidth, imageHeight, measureHandle;

            HOperatorSet.DrawRectangle2(visionControl1.GetHalconWindow(),
                                        out row, out column, out radian, out length1, out length2);

            HOperatorSet.GetImageSize(vision.imgSrc, out imageWidth, out imageHeight);

            HOperatorSet.GenMeasureRectangle2(row, column, radian, length1, length2, imageWidth, imageHeight, "nearest_neighbor", out measureHandle);
            HOperatorSet.GenRectangle2(out rect, row, column, radian, length1, length2);
            HOperatorSet.GenContourRegionXld(rect, out rect, "border");

            for (int i = 0; i <= 5; i++)
            {
                HTuple threshold = v.Threshold - i * 2;
                HTuple rowEdge, columnEdge, amplitude, distance;
                HOperatorSet.MeasurePos(vision.imgSrc, measureHandle, v.Sigma, threshold, "all", "first", out rowEdge, out columnEdge, out amplitude, out distance);

                if (rowEdge.Length > 0)
                {
                    int index = -1;
                    if (dgvCalib.SelectedCells.Count > 0)
                    {
                        index = dgvCalib.SelectedCells[0].RowIndex;
                    }

                    if (index < 0)
                    {
                        break;
                    }

                    dgvCalib.Rows[index].Cells[2].Value = columnEdge.D;
                    dgvCalib.Rows[index].Cells[3].Value = rowEdge.D;

                    HTuple homMat2D, rowTrans1, colTrans1, rowTrans2, colTrans2;
                    HOperatorSet.HomMat2dIdentity(out homMat2D);
                    HOperatorSet.HomMat2dRotate(homMat2D, radian, rowEdge, columnEdge, out homMat2D);
                    HOperatorSet.AffineTransPixel(homMat2D, rowEdge - length2, columnEdge, out rowTrans1, out colTrans1);
                    HOperatorSet.AffineTransPixel(homMat2D, rowEdge + length2, columnEdge, out rowTrans2, out colTrans2);

                    v.Lines?.Dispose();
                    HOperatorSet.GenContourPolygonXld(out v.Lines,
                                                      new HTuple(rowTrans1, rowTrans2), new HTuple(colTrans1, colTrans2));
                }
            }

            HOperatorSet.CloseMeasure(measureHandle);
            visionControl1.DisplayResults();

            visionControl1.MouseMode = VisionControl.WindowMouseMode.Move;
            groupBox1.Enabled        = true;
        }
        public override bool ProcessImage(VisionControl ctl)
        {
            try
            {
                //清理数据
                foreach (var mea in MeasureMgr.GetInstance().MeasureList)
                {
                    mea.ClearResult();
                }

                ctl.clearObj();
                ctl.DisplayResults();

                //保存图像
                //string imageName = $"{DateTime.Now:HHmmss}.tiff";

                //if (AutoForm._autoForm.Param.IsSaveImageAll)
                //{
                //    //保存原图
                //    string path = $@"{ProductMgr.GetInstance().ProductPath}Images\Robot\{DateTime.Now:yyMMdd}\Source\";
                //    if (!System.IO.Directory.Exists(path))
                //    {
                //        System.IO.Directory.CreateDirectory(path);
                //    }
                //    string fileName = $"{path}{imageName}";
                //    HDevelopExport.WriteImage(imgSrc, fileName);
                //}

                //图像预处理
                HObject image;
                if (ProductMgr.GetInstance().Param.PlatformRegion != null)
                {
                    HOperatorSet.ReduceDomain(imgSrc, ProductMgr.GetInstance().Param.PlatformRegion, out image);

                    //if (ProductMgr.GetInstance().Param.IsPerprocess)
                    //{
                    //    image = HDevelopExport.Preprocess(image, ProductMgr.GetInstance().Param.Emphasize, false);
                    //}
                }
                else
                {
                    image = imgSrc;
                }

                //查找模板
                HTuple row, column, angle, scale, score;
                bool   result = HDevelopExport.FindScaleShapeModel(image, out row, out column, out angle, out scale, out score);

                //显示轮廓
                HDevelopExport.dev_display_shape_matching_results(ctl.GetHalconWindow(),
                                                                  ProductMgr.GetInstance().Param.ModelID, "blue", row, column, angle, scale, scale, 0);

                if (result && ProductMgr.GetInstance().Param.IsSecondPos)
                {
                    HTuple transRow, transColumn, transRadian;
                    result = HDevelopExport.FindPinCenter(imgSrc, row, column, angle, out transRow, out transColumn, out transRadian);

                    if (result)
                    {
                        row    = transRow;
                        column = transColumn;
                        angle  = transRadian;
                    }

                    //ctl.DisplayResults();
                }

                if (!result)
                {
                    Log.Show("查找模板失败");
                    return(false);
                }

                //*************相对位置**************
                //HTuple relRow, relColumn;

                //relRow = PlatformCalibData.MarkRow - row;
                //relColumn = PlatformCalibData.MarkColumn - column;

                //SendData.X = PlatformCalibData.PixelToMm(relColumn);
                //SendData.Y = PlatformCalibData.PixelToMm(relRow);

                //用矩阵获得Mark点的世界坐标和模板的世界坐标,求差值
                HTuple colMark, rowMark, rowTrans, colTrans;
                HOperatorSet.AffineTransPixel(PlatformCalibData.HomMat2D, PlatformCalibData.MarkColumn, PlatformCalibData.MarkRow, out colMark, out rowMark);
                HOperatorSet.AffineTransPixel(PlatformCalibData.HomMat2D, column, row, out colTrans, out rowTrans);
                SendData.X = colMark - colTrans;
                SendData.Y = rowMark - rowTrans;

                Log.Show($"目标位置:X:{SendData.X:F2},Y:{SendData.Y:F2}");

                //***********************测量****************************
                MeasureMgr.GetInstance().MeasureAll(image, row, column, angle);

                //显示数据
                int hasCount = 0, meaCount = 0;
                for (int i = 0; i < MeasureMgr.GetInstance().MeasureList.Count; i++)
                {
                    var mea = MeasureMgr.GetInstance().MeasureList[i];

                    hasCount += mea.PinCount;
                    meaCount += mea.CountOK + mea.CountAreaNG + mea.CountPosNG;

                    //发送的数据
                    SendData.CountAreaNG += mea.CountAreaNG;
                    SendData.CountPosNG  += mea.CountPosNG;

                    if (mea.DiameterMax.Length > 0)
                    {
                        //显示和保存数据
                        Data.Show(i, mea.DiameterMax.ToDArr(), mea.DisLeft.ToDArr(), mea.DisRight.ToDArr(), mea.DisTop.ToDArr());
                    }
                }

                ctl.AddToStack(ProductMgr.GetInstance().Param.ModelContours);
                ctl.AddToStack(ProductMgr.GetInstance().Param.ModelOriginContours);
                ctl.AddToStack(ProductMgr.GetInstance().Param.MarkContours);

                ctl.DisplayResults();

                //显示数据到窗口
                HTuple degree;
                HOperatorSet.TupleDeg(angle, out degree);
                Log.Show($"查找模板:row:{row.D:F2},column:{column.D:F2},degree:{degree.D:F2},分数:{score.D:F2}");

                HDevelopExport.disp_message(ctl.GetHalconWindow(), $"位置:{row.D:F2},{column.D:F2},{degree.D:F2}", "window", 10, -1, "green", "false");
                HDevelopExport.disp_message(ctl.GetHalconWindow(), $"分数:{score.D:F2}", "window", 30, -1, "green", "false");

                HDevelopExport.disp_message(ctl.GetHalconWindow(), $"X:{SendData.X:F2},Y:{SendData.Y:F2}", "window", 150, -1, "green", "false");
                HDevelopExport.disp_message(ctl.GetHalconWindow(), $"{hasCount}-{meaCount}", "window", 170, -1, "green", "false");

                if (SendData.CountAreaNG > 0)
                {
                    HDevelopExport.disp_message(ctl.GetHalconWindow(), $"面积NG:{SendData.CountAreaNG}", "window", 190, -1, "red", "false");
                }

                if (SendData.CountPosNG > 0)
                {
                    HDevelopExport.disp_message(ctl.GetHalconWindow(), $"位置NG:{SendData.CountPosNG}", "window", 210, -1, "magenta", "false");
                }

                //显示日志
                Log.Show($"面积NG:{SendData.CountAreaNG},位置NG:{SendData.CountPosNG}");

                //保存窗口图像和原图
                result = result && SendData.CountAreaNG == 0 && SendData.CountPosNG == 0;
                if (AutoForm._autoForm.Param.IsSaveImageAll)
                {
                    SaveImage(ctl.GetHalconWindow(), result);
                }
                else
                {
                    if (AutoForm._autoForm.Param.IsSaveImageNG && !result)
                    {
                        SaveImage(ctl.GetHalconWindow(), result);
                    }
                }

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
        public override bool ProcessImage(VisionControl ctl)
        {
            try
            {
                ctl.clearObj();
                ctl.DisplayResults();

                //保存图像
                //string imageName = $"{DateTime.Now:HHmmss}.tiff";

                //if (AutoForm._autoForm.Param.IsSaveImageAll)
                //{
                //    //保存原图
                //    string path = $@"{ProductMgr.GetInstance().ProductPath}Images\Platform\{DateTime.Now:yyMMdd}\Source\";
                //    if (!System.IO.Directory.Exists(path))
                //    {
                //        System.IO.Directory.CreateDirectory(path);
                //    }
                //    string fileName = $"{path}{imageName}";
                //    HDevelopExport.WriteImage(imgSrc, fileName);
                //}

                //图像预处理
                HObject image;

                if (ProductMgr.GetInstance().Param.PlatformRegion != null)
                {
                    HOperatorSet.ReduceDomain(imgSrc, ProductMgr.GetInstance().Param.PlatformRegion, out image);

                    //if (ProductMgr.GetInstance().Param.IsPerprocess)
                    //{
                    //    image = HDevelopExport.Preprocess(image, ProductMgr.GetInstance().Param.Emphasize, false);
                    //}
                }
                else
                {
                    image = imgSrc;
                }

                //查找模板
                HTuple row, column, angle, scale, score;
                bool   result = HDevelopExport.FindScaleShapeModel(image, out row, out column, out angle, out scale, out score);

                //显示轮廓
                HDevelopExport.dev_display_shape_matching_results(ctl.GetHalconWindow(),
                                                                  ProductMgr.GetInstance().Param.ModelID, "blue", row, column, angle, scale, scale, 0);

                /*
                 * //二次定位
                 * if (result && ProductMgr.GetInstance().Param.IsSecondPos)
                 * {
                 *  HTuple transRow, transColumn, transRadian;
                 *  result = HDevelopExport.FindPinCenter(imgSrc, row, column, angle, out transRow, out transColumn, out transRadian);
                 *
                 *  if (result)
                 *  {
                 *      row = transRow;
                 *      column = transColumn;
                 *      angle = transRadian;
                 *  }
                 *
                 *  //ctl.DisplayResults();
                 * }
                 */

                if (!result)
                {
                    Log.Show("查找模板失败");
                }
                else
                {
                    //弧度差
                    HTuple relRow, relColumn, relRadian, rowTrans, colTrans;
                    //relRadian = PlatformCalibData.MarkRadian - angle;
                    relRadian = 0 - angle;

                    //旋转特征点
                    //HTuple homMat2D;
                    //HOperatorSet.HomMat2dIdentity(out homMat2D);
                    //HOperatorSet.HomMat2dRotate(homMat2D, relRadian, PlatformCalibData.CenterRow, PlatformCalibData.CenterColumn, out homMat2D);
                    //HOperatorSet.AffineTransPixel(homMat2D, row, column, out rowTrans, out colTrans);

                    //以平台Mark点为基准
                    //relRow = PlatformCalibData.MarkRow - rowTrans;
                    //relColumn = PlatformCalibData.MarkColumn - colTrans;

                    //没有旋转,直接计算X和Y方向的差值,下面的角度只用于显示
                    //relRow = PlatformCalibData.MarkRow - row;
                    //relColumn = PlatformCalibData.MarkColumn - column;

                    //弧度转角度
                    HTuple degree;
                    HOperatorSet.TupleDeg(relRadian, out degree);

                    //赋值给需要发送的数据
                    //SendData.X = PlatformCalibData.PixelToMm(relColumn);
                    //SendData.Y = PlatformCalibData.PixelToMm(relRow);
                    //SendData.Angle = degree;


                    //用矩阵获得Mark点的世界坐标和模板的世界坐标,求差值
                    HTuple colMark, rowMark;
                    HOperatorSet.AffineTransPixel(PlatformCalibData.HomMat2D, PlatformCalibData.MarkColumn, PlatformCalibData.MarkRow, out colMark, out rowMark);
                    HOperatorSet.AffineTransPixel(PlatformCalibData.HomMat2D, column, row, out colTrans, out rowTrans);
                    SendData.X = colMark - colTrans;
                    SendData.Y = rowMark - rowTrans;



                    ctl.AddToStack(ProductMgr.GetInstance().Param.ModelContours);
                    ctl.AddToStack(ProductMgr.GetInstance().Param.ModelOriginContours);
                    ctl.AddToStack(ProductMgr.GetInstance().Param.MarkContours);

                    ctl.DisplayResults();

                    //显示数据到窗口
                    HTuple deg;
                    HOperatorSet.TupleDeg(angle, out deg);
                    Log.Show($"查找模板:row:{row.D:F2},column:{column.D:F2},degree:{deg.D:F2},分数:{score.D:F2}");

                    HDevelopExport.disp_message(ctl.GetHalconWindow(), $"位置:{row.D:F2},{column.D:F2},{degree.D:F2}", "window", 10, -1, "green", "false");
                    HDevelopExport.disp_message(ctl.GetHalconWindow(), $"分数:{score.D:F2}", "window", 30, -1, "green", "false");

                    HDevelopExport.disp_message(ctl.GetHalconWindow(), $"X:{SendData.X:F2},Y:{SendData.Y:F2},A:{SendData.Angle:F2}", "window", 150, -1, "green", "false");
                    Log.Show($"目标位置:X:{SendData.X:F2},Y:{SendData.Y:F2},A:{SendData.Angle:F2}");
                }

                //保存查找模板的窗口图片和原图
                if (AutoForm._autoForm.Param.IsSaveImageAll)
                {
                    SaveImage(ctl.GetHalconWindow(), result);
                }
                else
                {
                    if (AutoForm._autoForm.Param.IsSaveImageNG && !result)
                    {
                        SaveImage(ctl.GetHalconWindow(), result);
                    }
                }

                return(result);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Ejemplo n.º 21
0
            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;

                /*
                 * // Local iconic variables
                 *
                 * //HObject ho_Image, ho_ImageEmphasize, ho_ROI_0;
                 * //HObject ho_ImageReduced, ho_ImageScaled, ho_Regions, ho_Connection;
                 * //HObject ho_RegionOpening, ho_RegionClosing, ho_ObjectSelected;
                 * //HObject ho_RegionTrans, ho_ImageMean, ho_ImageResult;
                 *
                 * // Local control variables
                 *
                 * HTuple hv_Area = null, hv_Row = null, hv_Column = null;
                 * HTuple hv_Indices = null, hv_Inverted = null;
                 *
                 * HOperatorSet.ScaleImage(image, out ho_ImageScaled, 4.25, -425);
                 * HOperatorSet.Threshold(ho_ImageScaled, out ho_Regions, 100, 255);
                 * HOperatorSet.OpeningCircle(ho_Regions, out ho_RegionOpening, 3.5);
                 * HOperatorSet.ClosingCircle(ho_RegionOpening, out ho_RegionClosing, 19.5);
                 * HOperatorSet.Connection(ho_RegionClosing, out ho_Connection);
                 * HOperatorSet.AreaCenter(ho_Connection, out hv_Area, out hv_Row, out hv_Column);
                 * HOperatorSet.TupleSortIndex(hv_Area, out hv_Indices);
                 * HOperatorSet.TupleInverse(hv_Indices, out hv_Inverted);
                 * HOperatorSet.SelectObj(ho_Connection, out ho_ObjectSelected, (hv_Inverted.TupleSelect(0)) + 1);
                 * HOperatorSet.ShapeTrans(ho_ObjectSelected, out ho_RegionTrans, "rectangle2");
                 * HOperatorSet.MeanImage(ho_ImageScaled, out ho_ImageMean, 15, 15);
                 * HOperatorSet.PaintRegion(ho_RegionTrans, ho_ImageMean, out ho_ImageResult, 255, "fill");
                 */

                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);

                        //HOperatorSet.MeasurePos(ho_ImageResult, HandleLine, Sigma, threshold, "positive", "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);
            }
Ejemplo n.º 22
0
        public bool CreateLineModel(HTuple hv_HomMat2D)
        {
            try
            {
                HOperatorSet.ClearMetrologyModel(hv_MetrologyHandle);
                HOperatorSet.CreateMetrologyModel(out hv_MetrologyHandle);
                if (ho_Image == null)
                {
                    return(false);
                }

                HOperatorSet.GetImageSize(ho_Image, out hv_Width, out hv_Height);

                if (hv_Row1_Horizon.Length < 1)
                {
                    return(false);
                }

                if (hv_Row1_Vertical.Length < 1)
                {
                    return(false);
                }

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

                HTuple mhv_Row1_Horizon;  //水平线
                HTuple mhv_Column1_Horizon;
                HTuple mhv_Row2_Horizon;
                HTuple mhv_Column2_Horizon;

                HTuple mhv_Row1_Vertical;  //竖直线
                HTuple mhv_Column1_Vertical;
                HTuple mhv_Row2_Vertical;
                HTuple mhv_Column2_Vertical;

                HOperatorSet.AffineTransPixel(hv_HomMat2D, hv_Row1_Horizon, hv_Column1_Horizon, out mhv_Row1_Horizon, out mhv_Column1_Horizon);
                HOperatorSet.AffineTransPixel(hv_HomMat2D, hv_Row2_Horizon, hv_Column2_Horizon, out mhv_Row2_Horizon, out mhv_Column2_Horizon);
                HOperatorSet.AffineTransPixel(hv_HomMat2D, hv_Row1_Vertical, hv_Column1_Vertical, out mhv_Row1_Vertical, out mhv_Column1_Vertical);
                HOperatorSet.AffineTransPixel(hv_HomMat2D, hv_Row2_Vertical, hv_Column2_Vertical, out mhv_Row2_Vertical, out mhv_Column2_Vertical);

                HOperatorSet.TupleInsert(mhv_Row1_Horizon, 0, mhv_Row1_Vertical, out hv_Row1);
                HOperatorSet.TupleInsert(mhv_Column1_Horizon, 0, mhv_Column1_Vertical, out hv_Column1);
                HOperatorSet.TupleInsert(mhv_Row2_Horizon, 0, mhv_Row2_Vertical, out hv_Row2);
                HOperatorSet.TupleInsert(mhv_Column2_Horizon, 0, mhv_Column2_Vertical, out hv_Column2);

                HOperatorSet.AddMetrologyObjectLineMeasure(hv_MetrologyHandle, hv_Row1, hv_Column1, hv_Row2, hv_Column2,
                                                           hv_MeasureLength1, hv_MeasureLength2, hv_MeasureSigma, hv_MeasureThreshold,
                                                           hv_GenParamName, hv_GenParamValue, out hv_Index);

                errorFlag = false;
                return(true);
            }
            catch (Exception exc)
            {
                errorFlag = true;
                return(false);
            }
        }
            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;
                    }
                }
            }
Ejemplo n.º 24
0
        public override bool Process_image(HObject ho_Image, VisionControl visionControl)
        {
            if (ModeID == null)
            {
                MessageBox.Show(m_strStepName + ":模板不存在,请登录模板", "Err", MessageBoxButtons.OK, MessageBoxIcon.Error);
                _logger.Warn(m_strStepName + ":模板不存在,请登录模板");
                return(false);
            }
            if (ho_Image == null || !ho_Image.IsInitialized())
            {
                _logger.Warn(m_strStepName + ":匹配图片不存在,请读取或采集图片");
                MessageBox.Show(m_strStepName + ":匹配图片不存在,请读取或采集图片", "Err", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }
            HObject ReduceImg = null;

            try
            {
                visionShapParam.ResultRow.Clear();
                visionShapParam.ResultCol.Clear();
                visionShapParam.ResultAngle.Clear();
                visionShapParam.OutPointInResultImg.Clear();
                HTuple hv_Row1 = null, hv_Column1 = null, hv_Row2 = null;
                HTuple hv_Column2 = null, hv_Row = null;
                HTuple hv_Column = null, hv_Angle = null, hv_ScaleR = null;
                HTuple hv_ScaleC = null, hv_Score = null;

                // HOperatorSet.SetSystem("border_shape_models", "true");
                if (RegionSearch != null && RegionSearch.IsInitialized())
                {
                    HOperatorSet.ReduceDomain(ho_Image, RegionSearch, out ReduceImg);
                }

                if (visionShapParam.ModeType.ToString() == "形状")
                {
                    if (ReduceImg != null && ReduceImg.IsInitialized())
                    {
                        HOperatorSet.FindScaledShapeModel(ReduceImg, ModeID,
                                                          (new HTuple(visionShapParam.AngleStart)).TupleRad(), (new HTuple(visionShapParam.AngleExtent)).TupleRad(),
                                                          visionShapParam.MinRowScale, visionShapParam.MaxRowScale, visionShapParam.dSorce, visionShapParam.nNum, visionShapParam.MaxOverlap, "least_squares", (new HTuple(visionShapParam.MatchPyamidLow)).TupleConcat(new HTuple(visionShapParam.MatchPyamidHigh)), 0.7,
                                                          out hv_Row, out hv_Column, out hv_Angle, out hv_ScaleR, out hv_Score);
                    }
                    else
                    {
                        HOperatorSet.FindScaledShapeModel(ho_Image, ModeID,
                                                          (new HTuple(visionShapParam.AngleStart)).TupleRad(), (new HTuple(visionShapParam.AngleExtent)).TupleRad(),
                                                          visionShapParam.MinRowScale, visionShapParam.MaxRowScale, visionShapParam.dSorce, visionShapParam.nNum, visionShapParam.MaxOverlap, "least_squares", (new HTuple(visionShapParam.MatchPyamidLow)).TupleConcat(new HTuple(visionShapParam.MatchPyamidHigh)), 0.9,
                                                          out hv_Row, out hv_Column, out hv_Angle, out hv_ScaleR, out hv_Score);
                    }
                }
                else
                {
                    if (ReduceImg != null && ReduceImg.IsInitialized())
                    {
                        HOperatorSet.FindNccModel(ReduceImg, ModeID, (new HTuple(visionShapParam.AngleStart)).TupleRad(), (new HTuple(visionShapParam.AngleExtent)).TupleRad(),
                                                  visionShapParam.dSorce, visionShapParam.nNum, visionShapParam.MaxOverlap, "true", 0, out hv_Row, out hv_Column, out hv_Angle, out hv_Score);
                    }
                    else
                    {
                        HOperatorSet.FindNccModel(ho_Image, ModeID, (new HTuple(visionShapParam.AngleStart)).TupleRad(), (new HTuple(visionShapParam.AngleExtent)).TupleRad(),
                                                  visionShapParam.dSorce, visionShapParam.nNum, visionShapParam.MaxOverlap, "true", 0, out hv_Row, out hv_Column, out hv_Angle, out hv_Score);
                    }
                }

                if (hv_Row.Length > 0)
                {
                    for (int i = 0; i < hv_Row.Length; i++)
                    {
                        visionShapParam.ResultRow.Add(hv_Row[i].D);
                        visionShapParam.ResultCol.Add(hv_Column[i].D);
                        visionShapParam.ResultAngle.Add(hv_Angle[i].D);
                        HOperatorSet.VectorAngleToRigid(visionShapParam.ModlePoint.y, visionShapParam.ModlePoint.x, visionShapParam.ModlePoint.u,
                                                        hv_Row[i].D, hv_Column[i].D, hv_Angle[i].D, out HTuple hom2d);
                        if (visionShapParam.bSetOutPoint)
                        {
                            HOperatorSet.VectorAngleToRigid(visionShapParam.ModlePoint.y, visionShapParam.ModlePoint.x, visionShapParam.ModlePoint.u,
                                                            hv_Row[i].D, hv_Column[i].D, hv_Angle[i].D, out hom2d);

                            HOperatorSet.AffineTransPixel(hom2d, visionShapParam.OutPointInModleImage.y, visionShapParam.OutPointInModleImage.x, out HTuple rowTrans, out HTuple colTrans);
                            if (visionControl != null && visionControl.isOpen())
                            {
                                HOperatorSet.SetColor(visionControl.GetHalconWindow(), "blue");
                                HOperatorSet.DispCross(visionControl.GetHalconWindow(), rowTrans, colTrans, 80, 0);
                            }

                            visionShapParam.OutPointInResultImg.Add(new Point2d(colTrans.D, rowTrans.D));
                        }
                        else
                        {
                            if (visionControl != null && visionControl.isOpen())
                            {
                                HOperatorSet.DispCross(visionControl.GetHalconWindow(), hv_Row[i].D, hv_Column[i].D, 20, 0);
                            }
                        }
                        int indexsel = 0;
                        shapeparamResults?.Clear();
                        HTuple     rowTransUser = 0; HTuple colTransUser = 0;
                        shapeparam shapeparamInstance;
                        foreach (var temp in shapeslist)
                        {
                            shapeparamInstance = temp.Clone();

                            switch (temp.shapeType)
                            {
                            case ShapeType.点:

                                HOperatorSet.AffineTransPixel(hom2d,
                                                              ((UsrShapePoint)temp.usrshape).Y,
                                                              ((UsrShapePoint)temp.usrshape).X,
                                                              out rowTransUser, out colTransUser);
                                ((UsrShapePoint)shapeparamInstance.usrshape).X = colTransUser[0].D;
                                ((UsrShapePoint)shapeparamInstance.usrshape).Y = rowTransUser[0].D;

                                shapeparamResults.Add(shapeparamInstance);
                                break;

                            case ShapeType.圆形:

                                ((UsrShapeCircle)shapeparamInstance.usrshape).CircleRadius = ((UsrShapeCircle)temp.usrshape).CircleRadius;
                                HOperatorSet.AffineTransPixel(hom2d,
                                                              ((UsrShapeCircle)temp.usrshape).CircleCenterY,
                                                              ((UsrShapeCircle)temp.usrshape).CircleCenterX,
                                                              out rowTransUser, out colTransUser);
                                ((UsrShapeCircle)shapeparamInstance.usrshape).CircleCenterX = colTransUser[0].D;
                                ((UsrShapeCircle)shapeparamInstance.usrshape).CircleCenterY = rowTransUser[0].D;
                                ((UsrShapeCircle)shapeparamInstance.usrshape).CircleRadius  = ((UsrShapeCircle)temp.usrshape).CircleRadius;
                                shapeparamResults.Add(shapeparamInstance);
                                try
                                {
                                    HOperatorSet.DispCircle(visionControl.GetHalconWindow(), ((UsrShapeCircle)shapeparamInstance.usrshape).CircleCenterY,
                                                            ((UsrShapeCircle)shapeparamInstance.usrshape).CircleCenterX, ((UsrShapeCircle)shapeparamInstance.usrshape).CircleRadius);

                                    //  HOperatorSet.DispObj(rectobj, visionControl.GetHalconWindow());
                                }
                                catch (Exception e)
                                {
                                }
                                break;

                            case ShapeType.仿射矩形:

                                ((UsrShapeRect2)shapeparamInstance.usrshape).Len1 = ((UsrShapeRect2)temp.usrshape).Len1;
                                ((UsrShapeRect2)shapeparamInstance.usrshape).Len2 = ((UsrShapeRect2)temp.usrshape).Len2;
                                ((UsrShapeRect2)shapeparamInstance.usrshape).Phi  = ((UsrShapeRect2)temp.usrshape).Phi + hv_Angle[i].D;
                                HOperatorSet.AffineTransPixel(hom2d,
                                                              ((UsrShapeRect2)temp.usrshape).CenterY,
                                                              ((UsrShapeRect2)temp.usrshape).CenterX,
                                                              out rowTransUser, out colTransUser);
                                ((UsrShapeRect2)shapeparamInstance.usrshape).CenterX = colTransUser[0].D;
                                ((UsrShapeRect2)shapeparamInstance.usrshape).CenterY = rowTransUser[0].D;
                                shapeparamResults.Add(shapeparamInstance);
                                try
                                {
                                    HOperatorSet.DispRectangle2(visionControl.GetHalconWindow(), ((UsrShapeRect2)shapeparamInstance.usrshape).CenterY,
                                                                ((UsrShapeRect2)shapeparamInstance.usrshape).CenterX, ((UsrShapeRect2)shapeparamInstance.usrshape).Phi,
                                                                ((UsrShapeRect2)shapeparamInstance.usrshape).Len1,
                                                                ((UsrShapeRect2)shapeparamInstance.usrshape).Len2
                                                                );
                                    //  HOperatorSet.DispObj(rectobj, visionControl.GetHalconWindow());
                                }
                                catch (Exception e)
                                {
                                }
                                break;

                            case ShapeType.矩形:

                                HOperatorSet.AffineTransPixel(hom2d,
                                                              ((UsrShapeRect)temp.usrshape).Y1,
                                                              ((UsrShapeRect)temp.usrshape).X1,
                                                              out rowTransUser, out colTransUser);
                                ((UsrShapeRect)shapeparamInstance.usrshape).X1 = colTransUser[0].D;
                                ((UsrShapeRect)shapeparamInstance.usrshape).Y1 = rowTransUser[0].D;
                                HOperatorSet.AffineTransPixel(hom2d,
                                                              ((UsrShapeRect)temp.usrshape).Y2,
                                                              ((UsrShapeRect)temp.usrshape).X2,
                                                              out rowTransUser, out colTransUser);
                                ((UsrShapeRect)shapeparamInstance.usrshape).X2 = colTransUser[0].D;
                                ((UsrShapeRect)shapeparamInstance.usrshape).Y2 = rowTransUser[0].D;
                                shapeparamResults.Add(shapeparamInstance);
                                try
                                {
                                    //   HOperatorSet.GenRectangle1(out HObject rectobj, ((UsrShapeRect)shapeparamInstance.usrshape).Y1,
                                    // ((UsrShapeRect)shapeparamInstance.usrshape).X1,

                                    //((UsrShapeRect)shapeparamInstance.usrshape).Y2,
                                    //       ((UsrShapeRect)shapeparamInstance.usrshape).X2);
                                    //   HOperatorSet.DispObj(rectobj, visionControl.GetHalconWindow());
                                    if (((UsrShapeRect)shapeparamInstance.usrshape).Y2 > ((UsrShapeRect)shapeparamInstance.usrshape).Y1)
                                    {
                                        HOperatorSet.DispRectangle1(visionControl.GetHalconWindow(),
                                                                    ((UsrShapeRect)shapeparamInstance.usrshape).Y1,
                                                                    ((UsrShapeRect)shapeparamInstance.usrshape).X1, ((UsrShapeRect)shapeparamInstance.usrshape).Y2,
                                                                    ((UsrShapeRect)shapeparamInstance.usrshape).X2
                                                                    );
                                        // HOperatorSet.DispObj(rectobj, visionControl.GetHalconWindow());
                                    }
                                    else
                                    {
                                        HOperatorSet.DispRectangle1(visionControl.GetHalconWindow(), ((UsrShapeRect)shapeparamInstance.usrshape).Y2,
                                                                    ((UsrShapeRect)shapeparamInstance.usrshape).X2,
                                                                    ((UsrShapeRect)shapeparamInstance.usrshape).Y1,
                                                                    ((UsrShapeRect)shapeparamInstance.usrshape).X1);
                                        //  HOperatorSet.DispObj(rectobj, visionControl.GetHalconWindow());
                                    }
                                    //   HOperatorSet.DispRectangle1(visionControl.GetHalconWindow(),
                                    //((UsrShapeRect)shapeparamInstance.usrshape).Y1,
                                    // ((UsrShapeRect)shapeparamInstance.usrshape).X1,

                                    //((UsrShapeRect)shapeparamInstance.usrshape).Y2,
                                    //       ((UsrShapeRect)shapeparamInstance.usrshape).X2
                                    //);
                                }
                                catch (Exception e)
                                {
                                }

                                break;
                            }
                        }
                    }
                    Save();
                    if (visionControl != null && visionControl.isOpen())
                    {
                        HOperatorSet.SetColor(visionControl.GetHalconWindow(), "green");
                    }
                    if (RegionSearch != null && RegionSearch.IsInitialized() && visionControl != null && visionControl.isOpen())
                    {
                        HOperatorSet.DispObj(RegionSearch, visionControl.GetHalconWindow());
                    }
                    if (visionControl != null && visionControl.isOpen())
                    {
                        HalconExternFunExport.dev_display_shape_matching_results(ModeID, visionControl.GetHalconWindow(), "green", hv_Row, hv_Column, hv_Angle, 1, 1, 0);
                        for (int i = 0; i < hv_Row.Length; i++)
                        {
                            HTuple hTuple = string.Format("x:{0},y:{1},u:{2},score{3}", hv_Column[i].D, hv_Row[i].D, hv_Angle[i].D / Math.PI * 180, hv_Score[i].D);
                            string strmsg = string.Format("x:{0},y:{1},u:{2},score{3},Numlevels", hv_Column[i].D.ToString("F2"), hv_Row[i].D.ToString("F2"), (hv_Angle[i].D / Math.PI * 180).ToString("F2"), hv_Score[i].D.ToString("F2"), visionShapParam.MatchPyamidHigh);
                            HalconExternFunExport.disp_message(visionControl.GetHalconWindow(), strmsg, "window", 0 + i * 20, 100, "green", "false");
                        }
                    }
                }
                else
                {
                    if (visionControl != null && visionControl.isOpen())
                    {
                        HOperatorSet.SetColor(visionControl.GetHalconWindow(), "red");
                    }
                    if (RegionSearch != null && RegionSearch.IsInitialized() && visionControl != null && visionControl.isOpen())
                    {
                        HOperatorSet.DispObj(RegionSearch, visionControl.GetHalconWindow());
                    }
                    if (visionControl != null && visionControl.isOpen())
                    {
                        HalconExternFunExport.disp_message(visionControl.GetHalconWindow(), "没有找到", "window", 100, 100, "red", "false");
                    }

                    return(false);
                }
            }
            catch (HalconException e)
            {
                _logger.Warn(m_strStepName + ": 寻找模板失败:" + e.Message);
                MessageBox.Show(m_strStepName + ": 寻找模板失败:" + e.Message, "Err", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }
            finally
            {
                ReduceImg?.Dispose();
                GC.Collect();
            }

            return(true);
        }
Ejemplo n.º 25
0
        public static bool InspectPinPos(St_InspectPinParam InspectPinParamIn, HObject ImgIn, out HTuple OffSetRows, out HTuple OffSetCols, out HTuple OffSetDist, out HObject PinContour, out HObject ErrorContour)
        {
            //1.0获得最新图片PIN针的中心坐标
            OffSetRows   = new HTuple();
            OffSetCols   = new HTuple();
            OffSetDist   = new HTuple();
            ErrorContour = new HObject();
            PinContour   = new HObject();
            #region //定义参数
            if (InspectPinParamIn.Elements.Count() == 0 || InspectPinParamIn.Elements == null)
            {
                return(false);
            }
            double  Element       = InspectPinParamIn.Elements[0];
            double  DetectHight   = InspectPinParamIn.DetectHeights[0];
            double  DtetectWidth  = InspectPinParamIn.DetectWidths[0];
            double  LineRow1      = InspectPinParamIn.Row1s[0];
            double  LineCol1      = InspectPinParamIn.Col1s[0];
            double  LineRow2      = InspectPinParamIn.Row2s[0];
            double  LineCol2      = InspectPinParamIn.Col2s[0];
            HObject DetectRegions = new HObject();
            HObject RoiContour    = new HObject();
            double  DnThreshold   = InspectPinParamIn.DnThresholds[0];
            double  UpThreshold   = InspectPinParamIn.UpThresholds[0];
            double  MinArea       = InspectPinParamIn.MinAreas[0];
            double  MaxArea       = InspectPinParamIn.MaxAreas[0];
            #endregion

            HTuple PinRows = new HTuple(), PinCols = new HTuple();
            for (int i = 0; i < InspectPinParamIn.Elements.Count(); i++)
            {
                #region 参数赋值
                Element      = InspectPinParamIn.Elements[i];
                DetectHight  = InspectPinParamIn.DetectHeights[i];
                DtetectWidth = InspectPinParamIn.DetectWidths[i];
                LineRow1     = InspectPinParamIn.Row1s[i];
                LineCol1     = InspectPinParamIn.Col1s[i];
                LineRow2     = InspectPinParamIn.Row2s[i];
                LineCol2     = InspectPinParamIn.Col2s[i];
                DnThreshold  = InspectPinParamIn.DnThresholds[i];
                UpThreshold  = InspectPinParamIn.UpThresholds[i];
                MinArea      = InspectPinParamIn.MinAreas[i];
                MaxArea      = InspectPinParamIn.MaxAreas[i];
                #endregion
                //1.1 生成单行Pin针ROI
                MyVisionBase.gen_rake_ROI1(ImgIn, out DetectRegions, out RoiContour, Element, DetectHight,
                                           DtetectWidth, LineRow1, LineCol1, LineRow2, LineCol2);
                HObject ReduceImg;
                HTuple  area = new HTuple(), row = new HTuple(), col = new HTuple();
                HObject CircleObj = new HObject();
                HOperatorSet.GenCircle(out CircleObj, 10, 10, 5);
                #region 找出每行Pin针的中心坐标
                for (int j = 0; j < DetectRegions.CountObj(); j++) //计算每根针的中心
                {
                    HObject RegionI = new HObject();
                    HOperatorSet.CopyObj(DetectRegions, out RegionI, j + 1, 1);
                    HOperatorSet.ReduceDomain(ImgIn, RegionI, out ReduceImg); RegionI.Dispose();                      //获取目标区域的图像
                    HObject ThrdRegion;
                    HOperatorSet.Threshold(ReduceImg, out ThrdRegion, DnThreshold, UpThreshold); ReduceImg.Dispose(); //阈值分割
                    HObject ExpandRegion = new HObject();
                    HOperatorSet.ExpandRegion(ThrdRegion, CircleObj, out ExpandRegion, 3, "image");                   //膨胀
                    ThrdRegion.Dispose();;
                    HObject ConnectRegion;
                    HOperatorSet.Connection(ExpandRegion, out ConnectRegion); ExpandRegion.Dispose();                                    //链接
                    HObject SelectRegion = new HObject();
                    HOperatorSet.SelectShape(ConnectRegion, out SelectRegion, "area", "and", MinArea, MaxArea); ConnectRegion.Dispose(); //挑出目标区域
                    HTuple areaI, RowI, ColI;
                    HOperatorSet.AreaCenter(SelectRegion, out areaI, out RowI, out ColI);                                                //获取Pin针中心坐标
                    if (RowI.Length > 0)
                    {
                        HTuple MaxValue = areaI.TupleMax();
                        int    MaxIndex = areaI.TupleFind(MaxValue);
                        row[j] = RowI[MaxIndex].D;
                        col[j] = ColI[MaxIndex].D;
                    }
                    else
                    {
                        row[j] = 0;
                        col[j] = 0;
                    }
                }
                #endregion
                PinRows = PinRows.TupleConcat(row);
                PinCols = PinCols.TupleConcat(col);
                CircleObj.Dispose();
            }
            HTuple TeachPinRows = new HTuple(), TeachPinCols = new HTuple();
            for (int i = 0; i < InspectPinParamIn.Elements.Count(); i++)
            {
                HTuple row0 = new HTuple(), col0 = new HTuple();
                MyVisionBase.ListToHTuple(InspectPinParamIn.ListRows[i], out row0);
                MyVisionBase.ListToHTuple(InspectPinParamIn.ListCols[i], out col0);
                TeachPinRows = TeachPinRows.TupleConcat(row0);
                TeachPinCols = TeachPinCols.TupleConcat(col0);
            }
            HTuple HomMat = new HTuple();
            HOperatorSet.VectorToHomMat2d(TeachPinCols, TeachPinRows, PinCols, PinRows, out HomMat);           //计算平移矩阵
            HTuple TargetRows = new HTuple(), TargetCols = new HTuple();
            HOperatorSet.AffineTransPixel(HomMat, TeachPinCols, TeachPinRows, out TargetCols, out TargetRows); //平移示教点的坐标
            if (TargetRows.Length != TeachPinRows.Length)
            {
                return(false);
            }
            HTuple OffSetRows0 = new HTuple(), OffSetCols0 = new HTuple(), OffSetDist0 = new HTuple();
            OffSetCols0 = PinCols - TargetCols;
            OffSetRows0 = PinRows - TargetRows;
            HOperatorSet.DistancePp(TargetRows, TargetCols, PinRows, PinCols, out OffSetDist0); //计算出偏移量
            HTuple Max       = OffSetDist0.TupleMax();
            HTuple MaxIndex0 = OffSetDist0.TupleFind(Max);

            HOperatorSet.GenCircleContourXld(out ErrorContour, PinRows[MaxIndex0[0].I], PinCols[MaxIndex0[0].I], 50, 0, Math.PI * 2, "positive", 1.0);

            HOperatorSet.GenCrossContourXld(out PinContour, PinRows, PinCols, 50, 0);


            OffSetRows = OffSetRows0;
            OffSetCols = OffSetCols0;
            OffSetDist = OffSetDist0;
            return(true);
        }
Ejemplo n.º 26
0
        public void Run()
        {
            if (inputImage == null)
            {
                FormFindLine.Instance.TextBoxMessageDisp("图像为空", System.Drawing.Color.Red);
                toolRunStatu = ToolRunStatu.Not_Input_Image;
                return;
            }
            try
            {
                UpdateImage();
                if (inputPose != null)
                {
                    HTuple Row   = inputPose.X - templatePose.X;
                    HTuple Col   = inputPose.Y - templatePose.Y;
                    HTuple angle = inputPose.U - templatePose.U;

                    HTuple _homMat2D;
                    HOperatorSet.HomMat2dIdentity(out _homMat2D);
                    HOperatorSet.HomMat2dRotate(_homMat2D, (HTuple)(angle), (HTuple)templatePose.X, (HTuple)templatePose.Y, out _homMat2D);
                    HOperatorSet.HomMat2dTranslate(_homMat2D, (HTuple)(Row), (HTuple)(Col), out _homMat2D);

                    //对预期线的起始点做放射变换
                    HOperatorSet.AffineTransPixel(_homMat2D, (HTuple)expectLineStartRow, (HTuple)expectLineStartCol, out newExpectLineStartRow, out newExpectLineStartCol);
                    HOperatorSet.AffineTransPixel(_homMat2D, (HTuple)expectLineEndRow, (HTuple)expectLineEndCol, out newExpectLineEndRow, out newExpectLineEndCol);
                }
                else
                {
                    newExpectLineStartRow = expectLineStartRow;
                    newExpectLineStartCol = expectLineStartCol;
                    newExpectLineEndRow   = expectLineEndRow;
                    newExpectLineEndCol   = expectLineEndCol;
                }

                HTuple handleID;
                HOperatorSet.CreateMetrologyModel(out handleID);
                HTuple width, height;
                HOperatorSet.GetImageSize(inputImage, out width, out height);
                HOperatorSet.SetMetrologyModelImageSize(handleID, width[0], height[0]);
                HTuple index;
                HOperatorSet.AddMetrologyObjectLineMeasure(handleID, newExpectLineStartRow, newExpectLineStartCol, newExpectLineEndRow, newExpectLineEndCol, new HTuple(50), new HTuple(20), new HTuple(1), new HTuple(30), new HTuple(), new HTuple(), out index);

                //参数在这里设置
                HOperatorSet.SetMetrologyObjectParam(handleID, new HTuple("all"), new HTuple("measure_transition"), new HTuple(polarity));
                HOperatorSet.SetMetrologyObjectParam(handleID, new HTuple("all"), new HTuple("num_measures"), new HTuple(cliperNum));
                HOperatorSet.SetMetrologyObjectParam(handleID, new HTuple("all"), new HTuple("measure_length1"), new HTuple(length));
                HOperatorSet.SetMetrologyObjectParam(handleID, new HTuple("all"), new HTuple("measure_length2"), new HTuple(weidth));
                HOperatorSet.SetMetrologyObjectParam(handleID, new HTuple("all"), new HTuple("measure_threshold"), new HTuple(threshold));
                HOperatorSet.SetMetrologyObjectParam(handleID, new HTuple("all"), new HTuple("measure_select"), new HTuple(edgeSelect));
                HOperatorSet.SetMetrologyObjectParam(handleID, new HTuple("all"), new HTuple("measure_sigma"), new HTuple(sigma));
                HOperatorSet.SetMetrologyObjectParam(handleID, new HTuple("all"), new HTuple("min_score"), new HTuple(minScore));
                HOperatorSet.ApplyMetrologyModel(inputImage, handleID);

                //显示所有卡尺
                HTuple pointRow, pointCol;
                HOperatorSet.GetMetrologyObjectMeasures(out contours, handleID, new HTuple("all"), new HTuple("all"), out pointRow, out pointCol);
                HOperatorSet.SetColor(FormFindLine.Instance.myHwindow.hWindowControl.HalconWindow, new HTuple("blue"));
                HOperatorSet.DispObj(contours, FormFindLine.Instance.myHwindow.hWindowControl.HalconWindow);
                FormFindLine.Instance.myHwindow.DispObj(contours, "blue");

                //显示指示找线方向的箭头
                HTuple arrowAngle;
                HOperatorSet.AngleLx(newExpectLineStartRow, newExpectLineStartCol, newExpectLineEndRow, newExpectLineEndCol, out arrowAngle);
                #region 测试箭头


                #endregion
                arrowAngle = arrowAngle + Math.PI / 2;
                arrowAngle = arrowAngle.TupleDeg();
                HTuple row = (newExpectLineStartRow + newExpectLineEndRow) / 2;
                HTuple column = (newExpectLineStartCol + newExpectLineEndCol) / 2;
                double drow, dcolumn;
                double arrowLength = length + 100;
                if (0 <= arrowAngle && arrowAngle <= 90)
                {
                    drow    = Math.Abs(arrowLength * Math.Sin(((HTuple)arrowAngle).TupleRad()));
                    dcolumn = Math.Abs(arrowLength * Math.Cos(((HTuple)arrowAngle).TupleRad()));
                    HOperatorSet.DispArrow(FormFindLine.Instance.myHwindow.hWindowControl.HalconWindow, row, column, row - drow, column + dcolumn, 5.0);
                }
                else if (arrowAngle > 90 && arrowAngle <= 180)
                {
                    drow    = arrowLength * Math.Sin(((HTuple)(180 - arrowAngle)).TupleRad());
                    dcolumn = arrowLength * Math.Cos(((HTuple)(180 - arrowAngle)).TupleRad());
                    HOperatorSet.DispArrow(FormFindLine.Instance.myHwindow.hWindowControl.HalconWindow, row, column, row - drow, column - dcolumn, 5.0);
                }
                else if (arrowAngle < 0 && arrowAngle >= -90)
                {
                    drow    = arrowLength * Math.Sin(((HTuple)arrowAngle * -1).TupleRad());
                    dcolumn = arrowLength * Math.Cos(((HTuple)arrowAngle * -1).TupleRad());
                    HOperatorSet.DispArrow(FormFindLine.Instance.myHwindow.hWindowControl.HalconWindow, row, column, row + drow, column + dcolumn, 5.0);
                }
                else if (arrowAngle < -90 && arrowAngle >= -180)
                {
                    drow    = Math.Abs(arrowLength * Math.Sin(((HTuple)arrowAngle + 180).TupleRad()));
                    dcolumn = Math.Abs(arrowLength * Math.Cos(((HTuple)arrowAngle + 180).TupleRad()));
                    HOperatorSet.DispArrow(FormFindLine.Instance.myHwindow.hWindowControl.HalconWindow, row, column, row + drow, column - dcolumn, 5.0);
                }

                //把点显示出来
                HObject cross;
                HOperatorSet.GenCrossContourXld(out cross, pointRow, pointCol, new HTuple(12), new HTuple(0));
                HOperatorSet.SetColor(FormFindLine.Instance.myHwindow.hWindowControl.HalconWindow, new HTuple("orange"));
                HOperatorSet.DispObj(cross, FormFindLine.Instance.myHwindow.hWindowControl.HalconWindow);
                FormFindLine.Instance.myHwindow.DispObj(cross, "orange");

                //得到所找到的线
                HTuple  parameter;
                HObject line;
                HOperatorSet.GetMetrologyObjectResult(handleID, new HTuple("all"), new HTuple("all"), new HTuple("result_type"), new HTuple("all_param"), out parameter);
                HOperatorSet.GetMetrologyObjectResultContour(out line, handleID, new HTuple("all"), new HTuple("all"), new HTuple(1.5));

                if (parameter.Length >= 4)
                {
                    ResultLineStartRow = parameter[0];
                    ResultLineStartCol = parameter[1];
                    ResultLineEndRow   = parameter[2];
                    ResultLineEndCol   = parameter[3];
                    Point start = new Point()
                    {
                        Row = ResultLineStartRow, Col = ResultLineStartCol
                    };
                    Point end = new Point()
                    {
                        Row = ResultLineEndRow, Col = ResultLineEndCol
                    };
                    resultLine = new Line()
                    {
                        StartPoint = start, EndPoint = end
                    };

                    //显示找到的线
                    HOperatorSet.SetColor(FormFindLine.Instance.myHwindow.hWindowControl.HalconWindow, new HTuple("green"));
                    // HOperatorSet.DispObj(line, GetWindowHandle(jobName));
                    FormFindLine.Instance.myHwindow.hWindowControl.HalconWindow.SetLineWidth(2);
                    FormFindLine.Instance.myHwindow.DispObj(line, "green");
                }
                HOperatorSet.AngleLx(ResultLineStartRow, ResultLineStartCol, ResultLineEndRow, ResultLineEndCol, out _angle);
                HOperatorSet.ClearMetrologyModel(handleID);

                FormFindLine.Instance.tbx_resultStartRow.Text = ResultLineStartRow.ToString();
                FormFindLine.Instance.tbx_resultStartCol.Text = ResultLineEndCol.ToString();
                FormFindLine.Instance.tbx_resultEndRow.Text   = ResultLineEndRow.ToString();
                FormFindLine.Instance.tbx_resultEndCol.Text   = ResultLineEndCol.ToString();
                FormFindLine.Instance.TextBoxMessageDisp("运行成功", System.Drawing.Color.Green);
                toolRunStatu = ToolRunStatu.Succeed;
            }
            catch (Exception ex)
            {
                FormFindLine.Instance.TextBoxMessageDisp("工具运行异常" + ex.Message, System.Drawing.Color.Red);
            }
        }
            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;
                }
            }
Ejemplo n.º 28
0
        public bool FindLine(HTuple hv_HomMat2D, HTuple hv_HomMat2DPix)
        {
            if (ho_Image == null)
            {
                errorFlag = true;
                return(false);
            }

            if (hv_Model != 0)
            {
                //HTuple hv_Width;
                //HTuple hv_Height;
                //HOperatorSet.GetImageSize(ho_Image, out hv_Width, out hv_Height);
                //for (int i = 0; i < hv_Height; i++)
                //{

                //    for (int j = 0; j < hv_Width; j++)
                //    {
                //        HTuple hv_Grayval;
                //        HOperatorSet.GetGrayval(ho_Image, i, j, out hv_Grayval);
                //        if (hv_Grayval <= hv_RegionMax && hv_Grayval >= hv_RegionMin)
                //        {
                //            HOperatorSet.SetGrayval(ho_Image, i, j, 255);
                //        }
                //    }
                //}

                HObject ho_Region;

                HOperatorSet.Threshold(ho_Image, out ho_Region, hv_RegionMin, hv_RegionMax);

                HOperatorSet.ReduceDomain(ho_Image, ho_Region, out ho_Image);
                //string Path = AppDomain.CurrentDomain.BaseDirectory + @".//Parameters//test"+ DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss_ffff");
                //HOperatorSet.WriteImage(ho_Image,"bmp",0, Path);
            }

            if (!CreateLineModel(hv_HomMat2D))
            {
                errorFlag = true;
                return(false);
            }

            try
            {
                HOperatorSet.ApplyMetrologyModel(ho_Image, hv_MetrologyHandle);

                HOperatorSet.GetMetrologyObjectResult(hv_MetrologyHandle, "all", "all", "result_type", "row_begin", out hv_LineRowBegin);
                HOperatorSet.GetMetrologyObjectResult(hv_MetrologyHandle, "all", "all", "result_type", "column_begin", out hv_LineColumnBegin);
                HOperatorSet.GetMetrologyObjectResult(hv_MetrologyHandle, "all", "all", "result_type", "row_end", out hv_LineRowEnd);
                HOperatorSet.GetMetrologyObjectResult(hv_MetrologyHandle, "all", "all", "result_type", "column_end", out hv_LineColumnEnd);

                if (hv_LineRowBegin.Length != 1)
                {
                    errorFlag = true;
                    return(false);
                }

                HOperatorSet.AffineTransPixel(hv_HomMat2DPix, hv_LineRowBegin, hv_LineColumnBegin, out hv_LineRowBegin_Real, out hv_LineColumnBegin_Real);
                HOperatorSet.AffineTransPixel(hv_HomMat2DPix, hv_LineRowEnd, hv_LineColumnEnd, out hv_LineRowEnd_Real, out hv_LineColumnEnd_Real);

                errorFlag = false;
                return(true);
            }
            catch (Exception exc)
            {
                errorFlag = true;
                return(false);
            }
        }
            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);
            }
Ejemplo n.º 30
0
        public void Run(SoftwareRunState softwareRunState)
        {
            HTuple HMeasureHandle = new HTuple();
            HTuple resultRow, resultCol;

            if (inputImage == null)
            {
                if (softwareRunState == SoftwareRunState.Debug)
                {
                    FormCaliper.Instance.TextBoxMessageDisp("图像为空", System.Drawing.Color.Red);
                }
                toolRunStatu = ToolRunStatu.Not_Input_Image;
                return;
            }
            try
            {
                UpdateImage();
                if (inputPose != null)
                {
                    HTuple Row   = inputPose.X - templatePose.X;
                    HTuple Col   = inputPose.Y - templatePose.Y;
                    HTuple angle = inputPose.U - templatePose.U;

                    HTuple _homMat2D;
                    HOperatorSet.HomMat2dIdentity(out _homMat2D);
                    HOperatorSet.HomMat2dRotate(_homMat2D, (HTuple)(angle), (HTuple)templatePose.X, (HTuple)templatePose.Y, out _homMat2D);
                    HOperatorSet.HomMat2dTranslate(_homMat2D, (HTuple)(Row), (HTuple)(Col), out _homMat2D);

                    //对预期线的起始点做放射变换
                    HOperatorSet.AffineTransPixel(_homMat2D, (HTuple)expectRecStartRow, (HTuple)expectRecStartColumn, out newExpectRecStartRow, out newExpectRecStartColumn);
                }
                else
                {
                    newExpectRecStartRow    = expectRecStartRow;
                    newExpectRecStartColumn = expectRecStartColumn;
                }
                HTuple width, height, AmplitudeThreshold, distance;
                HOperatorSet.GetImageSize(inputImage, out width, out height);
                HOperatorSet.GenMeasureRectangle2(expectRecStartRow, expectRecStartColumn, expectAngle, length1, length2, width, height, "nearest_neighbor", out HMeasureHandle);
                HOperatorSet.MeasurePos(inputImage, HMeasureHandle, sigma, threshold, polarity, edgeSelect, out resultRow, out resultCol, out AmplitudeThreshold, out distance);
                if (resultRow.Length != 0)
                {
                    ResulttRow = resultRow;
                    ResultCol  = resultCol;
                }

                //把点显示出来
                HOperatorSet.GenCrossContourXld(out crossDisp, ResulttRow, ResultCol, new HTuple(60), new HTuple(0));
                if (softwareRunState == SoftwareRunState.Debug)
                {
                    DispMainWindow(FormCaliper.Instance.myHwindow);
                    FormCaliper.Instance.tbx_resultStartRow.Text = ResulttRow.ToString();
                    FormCaliper.Instance.tbx_resultStartCol.Text = ResultCol.ToString();
                    FormCaliper.Instance.TextBoxMessageDisp("运行成功", System.Drawing.Color.Green);
                }
                // 参数传递
                ParamsTrans();
                toolRunStatu = ToolRunStatu.Succeed;
            }
            catch (Exception ex)
            {
                toolRunStatu = ToolRunStatu.Not_Succeed;
                if (softwareRunState == SoftwareRunState.Debug)
                {
                    FormCaliper.Instance.TextBoxMessageDisp("工具运行异常" + ex.Message, System.Drawing.Color.Red);
                }
            }
            finally
            {
                //homMat2DArrow.Dispose();
                //arrow.Dispose();
                //arrowTrans.Dispose();
            }
        }