/*******************************************************************/

        private void mouseMoved(object sender, HalconDotNet.HMouseEventArgs e)
        {
            double motionX, motionY;
            double posX, posY;
            double zoomZone;

            if (!mousePressed)
                return;

            if (roiManager != null && (roiManager.activeROIidx != -1) && (dispROI == MODE_INCLUDE_ROI))
            {
                roiManager.mouseMoveAction(e.X, e.Y);
            }
            else if (stateView == MODE_VIEW_MOVE)
            {
                motionX = ((e.X - startX));
                motionY = ((e.Y - startY));

                if (((int)motionX != 0) || ((int)motionY != 0))
                {
                    moveImage(motionX, motionY);
                    startX = e.X - motionX;
                    startY = e.Y - motionY;
                }
            }
            else if (stateView == MODE_VIEW_ZOOMWINDOW)
            {
                HSystem.SetSystem("flush_graphic", "false");
                ZoomWindow.ClearWindow();

                posX = ((e.X - ImgCol1) / (ImgCol2 - ImgCol1)) * viewPort.Width;
                posY = ((e.Y - ImgRow1) / (ImgRow2 - ImgRow1)) * viewPort.Height;
                zoomZone = (zoomWndSize / 2) * zoomWndFactor * zoomAddOn;

                ZoomWindow.SetWindowExtents((int)posY - (zoomWndSize / 2),
                                            (int)posX - (zoomWndSize / 2),
                                            zoomWndSize, zoomWndSize);
                ZoomWindow.SetPart((int)(e.Y - zoomZone), (int)(e.X - zoomZone),
                                   (int)(e.Y + zoomZone), (int)(e.X + zoomZone));
                repaint(ZoomWindow);

                HSystem.SetSystem("flush_graphic", "true");
                ZoomWindow.DispLine(-100.0, -100.0, -100.0, -100.0);
            }
        }
Exemple #2
0
        void ShowObject(HWindow window)
        {
            if (window.IsInitialized() == false)
            {
                return;
            }
            //关闭显示刷新
            HSystem.SetSystem("flush_graphic", "false");
            //窗体图像清空
            window.ClearWindow();
            mGC.stateOfSettings.Clear();
            try
            {
                //HTuple showStart;
                //HOperatorSet.CountSeconds(out showStart);

                int count1 = 0;
                foreach (var item in HObjList)
                {
                    if (ResultShow == ResultShow.原图 && count1 > 0)
                    {
                        break;
                    }
                    if (item.HObj != null && item.HObj.IsInitialized())
                    {
                        mGC.ApplyContext(window, item.gContext);
                        window.DispObj(item.HObj);
                    }
                    else if (item.Message != null && isShowMessage)
                    {
                        //item.Message.DispMessage(window, "image", ((double)imageWidth / (double)(viewPort.Width)) / ZoomWndFactor);
                        double sizeTmp = item.Message.CahangeDisplayFontSize(window, (1.0) / ZoomWndFactor, currentTextSize);
                        currentTextSize = sizeTmp;
                        item.Message.DispMessage(window, "image");
                    }
                    count1++;
                }
                //HTuple showEnd;
                //HOperatorSet.CountSeconds(out showEnd);
                //double timeShow = (showEnd - showStart) * 1000.0;
                //Util.Notify(string.Format("内部显示图像用时{0:f2}ms", timeShow));
            }
            catch (Exception)
            {; }
        }
Exemple #3
0
 private void Start()
 {
     Config.ActData     = new ActionSystem("Action");
     Config.GraphicData = new GraphicSystem("Graphic");
     Config.SoundData   = new SoundSystem("Sound");
     Config.GameData    = new GameConfigSystem("Game");
     Config.HData       = new HSystem("H");
     this.xmlCtrl       = new Control("config", "system.xml", "System", new Illusion.Elements.Xml.Data[5]
     {
         (Illusion.Elements.Xml.Data)Config.ActData,
         (Illusion.Elements.Xml.Data)Config.GraphicData,
         (Illusion.Elements.Xml.Data)Config.SoundData,
         (Illusion.Elements.Xml.Data)Config.GameData,
         (Illusion.Elements.Xml.Data)Config.HData
     });
     this.Load();
     Config.initialized = true;
 }
        private void CoreOnNewImage(HImage[] hImage, Guid tmpSessionId)
        {
            lock (OnNewImageLock)
            {
                double startTime = HSystem.CountSeconds();

                HImage[] rotateImage = new HImage[hImage.Length];

                Parallel.For(0, Properties.Settings.Default.NumeroCamereTappo, i =>
                {
                    if (lastGrabImg[i] != null)
                    {
                        lastGrabImg[i].Dispose();
                    }
                    // |MP 25-1-19
                    if (null != hImage[i])
                    {
                        lastGrabImg[i] = hImage[i].CopyImage();

                        HImage rotateImage_ = hImage[i].RotateImage(new HTuple(rotazione[i]), "constant");
                        rotateImage[i]      = rotateImage_.MirrorImage("column");
                        rotateImage_.Dispose();

                        hImage[i].Dispose();
                    }
                    hImage[i] = null;
                });

                cts = new CancellationTokenSource(Properties.Settings.Default.TimeoutAlgoritmo);

                ArrayList[]       iconicVarList;
                ElaborateResult[] result;
                ElaborateImage(rotateImage, cts, out iconicVarList, out result);
                double tAnalisi = HSystem.CountSeconds();
                tAnalisi = (tAnalisi - startTime) * 1000.0;

                for (int i = 0; i < result.Length; i++)
                {
                    result[i].ElapsedTime = tAnalisi;
                }

                RaiseNewImageToDisplayEvent(iconicVarList, result);
            }
        }
Exemple #5
0
        /// <summary>
        /// Repaints the HALCON window 'window'
        /// </summary>
        public void repaint(HalconDotNet.HWindow window)
        {
            int h = imageHeight;

            if (window.IsInitialized() == false || viewPort.HalconID.ToInt32() == -1 || viewPort.ImagePart.Width <= 1 || viewPort.ImagePart.Height <= 1)
            {
                return;
            }
            int          count = HObjList.Count;
            HObjectEntry entry;

            HSystem.SetSystem("flush_graphic", "false");
            window.ClearWindow();
            mGC.stateOfSettings.Clear();

            for (int i = 0; i < count; i++)
            {
                entry = ((HObjectEntry)HObjList[i]);
                mGC.applyContext(window, entry.gContext);
                window.DispObj(entry.HObj);
            }

            addInfoDelegate();

            if (roiManager != null && (dispROI == MODE_INCLUDE_ROI))
            {
                roiManager.paintData(window);
            }

            HSystem.SetSystem("flush_graphic", "true");

            window.SetColor("black");
            window.DispLine(-100.0, -100.0, -101.0, -101.0);

            for (int i = 0; i < HMsgList.Count; i++)
            {
                if (HMsgList[i].Size != 0)
                {
                    set_display_font(viewPort.HalconID, HMsgList[i].Size, HMsgList[i].Font, HMsgList[i].Bold, HMsgList[i].Slant);
                }
                window.DispText(HMsgList[i].HMsg, HMsgList[i].coordSystem, HMsgList[i].row, HMsgList[i].column, HMsgList[i].color, HMsgList[i].genParamName, HMsgList[i].genParamValue);
            }
        }
        /// <summary>
        /// Repaints the HALCON window 'window'
        /// </summary>
        public void repaintUsingFlushGraphic(HalconDotNet.HWindow window)
        {
            int          count = HObjList.Count;
            HObjectEntry entry;

            if (window != null)
            {
                HSystem.SetSystem("flush_graphic", "false");
                window.ClearWindow();
                // check the boundatries of the image part
                if ((ImgRow2 > ImgRow1) && (ImgCol2 > ImgCol1))
                {
                    window.SetPart((int)ImgRow1, (int)ImgCol1, (int)ImgRow2, (int)ImgCol2);
                }
                // set the image part to window size
                else
                {
                    window.SetPart(0, 0, windowHeight - 1, windowWidth - 1);
                }
                mGC.stateOfSettings.Clear();

                for (int i = 0; i < count; i++)
                {
                    entry = ((HObjectEntry)HObjList[i]);
                    if (entry != null)
                    {
                        mGC.applyContext(window, entry.gContext);
                        window.DispObj(entry.HObj);
                    }
                }

                addInfoDelegate();

                if (roiManager != null && (dispROI == MODE_INCLUDE_ROI))
                {
                    roiManager.paintData(window);
                }

                HSystem.SetSystem("flush_graphic", "true");

                window.DispLine(-1000.0, -1000.0, -1001.0, -1001.0);
            }
        }
        /// <summary>
        /// 重置放大鏡視窗
        /// </summary>
        /// <param name="e"></param>
        private void resetZoomWindow(HalconDotNet.HMouseEventArgs e)
        {
            HSystem.SetSystem("flush_graphic", "false");
            ZoomWindow.ClearWindow();
            double posX     = ((e.X - ImgCol1) / (ImgCol2 - ImgCol1)) * _viewPort.Width;
            double posY     = ((e.Y - ImgRow1) / (ImgRow2 - ImgRow1)) * _viewPort.Height;
            double zoomZone = (zoomWndSize / 2) * zoomWndFactor * zoomAddOn;

            ZoomWindow.SetWindowExtents((int)posY - (zoomWndSize / 2),
                                        (int)posX - (zoomWndSize / 2),
                                        zoomWndSize, zoomWndSize);
            ZoomWindow.SetPart((int)(e.Y - zoomZone), (int)(e.X - zoomZone),
                               (int)(e.Y + zoomZone), (int)(e.X + zoomZone));

            repaint(ZoomWindow);

            HSystem.SetSystem("flush_graphic", "true");
            ZoomWindow.DispLine(-100.0, -100.0, -100.0, -100.0);
        }
Exemple #8
0
        /// <summary>


        /// </summary>
        public void repaint(HalconDotNet.HWindow window)
        {
            int          count = HObjList.Count;
            HObjectEntry entry;

            HSystem.SetSystem("flush_graphic", "false");
            window.ClearWindow();
            mGC.stateOfSettings.Clear();

            for (int i = 0; i < count; i++)
            {
                try
                {
                    if (i == HObjList.Count && HObjList.Count > 0)
                    {
                        break;
                    }
                    if (i > HObjList.Count)
                    {
                        break;
                    }
                    entry = ((HObjectEntry)HObjList[i]);
                    mGC.applyContext(window, entry.gContext);
                    window.DispObj(entry.HObj);
                }
                catch (Exception)
                {
                }
            }

            addInfoDelegate();

            if (roiManager != null && (dispROI == MODE_INCLUDE_ROI))
            {
                roiManager.paintData(window);
            }

            HSystem.SetSystem("flush_graphic", "true");

            window.SetColor("black");
            window.DispLine(-100.0, -100.0, -101.0, -101.0);
        }
        private void ExecProceduresForm_Load(object sender, System.EventArgs e)
        {
            // path of external procedures
            string halconExamples = HSystem.GetSystem("example_dir");
            string ProcedurePath  = halconExamples + @"\hdevengine\procedures";

            ProgramPathString = halconExamples +
                                @"\hdevengine\hdevelop\fin_detection.hdev";
            if (!HalconAPI.isWindows)
            {
                // Unix-based systems (Mono)
                ProcedurePath     = ProcedurePath.Replace('\\', '/');
                ProgramPathString = ProgramPathString.Replace('\\', '/');
            }
            MyEngine.SetProcedurePath(ProcedurePath);
            // disable buttons
            InitAcqBtn.Enabled          = false;
            ProcessImageBtn.Enabled     = false;
            VisualizeDetailsBtn.Enabled = false;
        }
Exemple #10
0
        /// <summary>
        /// Repaints the HALCON window 'window'
        /// </summary>
        public void repaint(HalconDotNet.HWindow window)
        {
            try
            {
                int          count = HObjImageList.Count;
                HObjectEntry entry;

                HSystem.SetSystem("flush_graphic", "false");
                window.ClearWindow();
                mGC.stateOfSettings.Clear();

                //显示图片
                for (int i = 0; i < count; i++)
                {
                    entry = ((HObjectEntry)HObjImageList[i]);
                    mGC.applyContext(window, entry.gContext);
                    window.DispObj(entry.HObj);
                }

                //显示region
                showHObjectList();


                addInfoDelegate();

                if (roiManager != null && (dispROI == MODE_INCLUDE_ROI))
                {
                    roiManager.paintData(window);
                }


                HSystem.SetSystem("flush_graphic", "true");

                //注释了下面语句,会导致窗口无法实现缩放和拖动
                window.SetColor("black");
                window.DispLine(-100.0, -100.0, -101.0, -101.0);
            }
            catch (Exception)
            {
            }
        }
Exemple #11
0
        //3-手绘
        private void buttonModelByHand_Click(object sender, EventArgs e)
        {
            try
            {
                HTuple htNumber;
                try
                {
                    m_hoModelEdgesTemp.Dispose();
                }
                catch
                {
                }

                isDraw = true;
                HOperatorSet.GenEmptyObj(out m_hoModelEdgesTemp);
                HOperatorSet.CountObj(m_hoModedImage, out htNumber);
                HSystem.SetSystem("flush_graphic", "false");
                HOperatorSet.ClearWindow(m_htWindowHandle);
                HSystem.SetSystem("flush_graphic", "true");
                HOperatorSet.DispObj(m_hoModedImage, m_htWindowHandle);
                HOperatorSet.DispObj(m_hoModelEdges, m_htWindowHandle);
                if (0 != htNumber.I)
                {
                    m_hoModelEdgesTemp.Dispose();
                    HOperatorSet.SetColor(m_htWindowHandle, "red");
                    HOperatorSet.SetLineWidth(m_htWindowHandle, 3);
                    HObject region = null;
                    HOperatorSet.DrawRegion(out region, m_htWindowHandle);
                    HObject reduceImage = null;
                    HOperatorSet.ReduceDomain(m_hoModedImage, region, out reduceImage);
                    HOperatorSet.EdgesSubPix(reduceImage, out m_hoModelEdgesTemp, "canny", 1, 20, 70);
                    HOperatorSet.DispObj(m_hoModelEdgesTemp, m_htWindowHandle);
                }
                isDraw = false;
            }
            catch (HalconException ex)
            {
                MessageBox.Show("手绘出现异常,异常信息:" + ex.GetErrorMessage());
            }
        }
Exemple #12
0
        /// <summary>
        /// Repaints the HALCON window 'window'
        /// </summary>
        public void repaint(HalconDotNet.HWindow window)
        {
            int          count = HObjList.Count;
            HObjectEntry entry;

            HSystem.SetSystem("flush_graphic", "false");
            window.ClearWindow();
            mGC.stateOfSettings.Clear();

            for (int i = 0; i < count; i++)
            {
                entry = ((HObjectEntry)HObjList[i]);
                mGC.applyContext(window, entry.gContext);
                window.DispObj(entry.HObj);
            }

            if (this.Image != null)
            {
                window.DispImage(this.Image);
            }

            foreach (var region in this.HRegionList)
            {
                window.SetColored(12);
                window.SetDraw("fill");
                window.DispRegion(region);
            }

            addInfoDelegate();

            if (roiManager != null && (dispROI == MODE_INCLUDE_ROI))
            {
                roiManager.paintData(window);
            }

            HSystem.SetSystem("flush_graphic", "true");

            window.SetColor("black");
            window.DispLine(-100.0, -100.0, -101.0, -101.0);
        }
Exemple #13
0
        /// <summary>
        /// Repaints the HALCON window 'window'
        /// </summary>
        private void repaint(HalconDotNet.HWindow window)
        {
            int count = HObjList.Count;

            if (count > 0)
            {
                HObjectEntry entry;
                HSystem.SetSystem("flush_graphic", "false");
                window.ClearWindow();
                mGC.stateOfSettings.Clear();
                for (int i = 0; i < count; i++)
                {
                    entry = ((HObjectEntry)HObjList[i]);
                    if (entry.colorShow.Length > 0)
                    {
                        window.SetColor(entry.colorShow);
                    }
                    mGC.applyContext(window, entry.gContext);
                    window.DispObj(entry.HObj);
                }
                if (roiManager != null)
                {
                    roiManager.paintData(window);
                }
                HSystem.SetSystem("flush_graphic", "true");
                window.DispLine(-100.0, -100.0, -101.0, -101.0);
            }
            count = StrList.Count;
            if (count > 0)
            {
                foreach (StringX strX in StrList)
                {
                    window.SetFont("-Consolas-" + strX.size.ToString() + "-*-" + (strX.bold ? "1" : "0") + "-*-*-" + (strX.slant ? "1" : "0") + "-");
                    window.SetColor(strX.color.Name.ToLower());
                    window.SetTposition(strX.row, strX.column);
                    window.WriteString(strX.str);
                }
            }
        }
Exemple #14
0
        /// <summary>
        /// Repaints the HALCON window 'window'
        /// </summary>
        public void repaint(HalconDotNet.HWindow window)
        {
            int h = imageHeight;

            if (window.IsInitialized() == false || viewPort.HalconID.ToInt32() == -1 || viewPort.ImagePart.Width <= 1 || viewPort.ImagePart.Height <= 1)
            {
                return;
            }
            int          count = HObjList.Count;
            HObjectEntry entry;

            HSystem.SetSystem("flush_graphic", "false");
            window.ClearWindow();
            mGC.stateOfSettings.Clear();

            for (int i = 0; i < count; i++)
            {
                entry = ((HObjectEntry)HObjList[i]);
                mGC.applyContext(window, entry.gContext);
                window.DispObj(entry.HObj);
            }

            addInfoDelegate();

            if (roiManager != null && (dispROI == MODE_INCLUDE_ROI))
            {
                roiManager.paintData(window);
            }

            HSystem.SetSystem("flush_graphic", "true");

            //window.SetColor("black");
            //window.DispLine(-100.0, -100.0, -101.0, -101.0);

            window.SetDraw("fill");
            //window.SetColored(12);
            window.SetColor("green");
        }
Exemple #15
0
        private void buttonFindModel_Click(object sender, EventArgs e)
        {
            HSystem.SetSystem("flush_graphic", "false");
            HOperatorSet.ClearWindow(m_htWindowHandle);
            HSystem.SetSystem("flush_graphic", "true");
            HOperatorSet.DispObj(m_hoModedImage, m_htWindowHandle);
            try
            {
                if (m_htModelID == null || m_htModelID.Length == 0)
                {
                    return;
                }
                HObject            image     = m_hoModedImage.Clone();
                Variable.CamReturn camreturn = new Variable.CamReturn();
                HalconHelper.FindShapeModel(image, null, m_htModelID, ref camreturn, m_htWindowHandle, 0.6, 1);
                tRX.Text          = camreturn.X.ToString();
                tRY.Text          = camreturn.Y.ToString();
                this.tRAngle.Text = camreturn.Angle.ToString();


                double offsetX = (double)this.nOffsetX.Value * camreturn.XScale;
                double offsetY = (double)this.nOffsetY.Value * camreturn.YScale;

                double       deg   = -camreturn.Angle / 180.0 * Math.PI;
                PointContour outPt = new PointContour();
                outPt.X = camreturn.X + offsetX;
                outPt.Y = camreturn.Y + offsetY;

                var PTRotated = this.PtRotateDown(outPt, new PointContour(camreturn.X, camreturn.Y), -camreturn.Angle);
                HOperatorSet.SetColor(this.m_htWindowHandle, "green");
                HOperatorSet.DispCross(this.m_htWindowHandle, PTRotated.Y, PTRotated.X, 24, deg);
            }
            catch (HalconException ex)
            {
                MessageBox.Show("查找模板失败,失败信息:" + ex.GetErrorMessage());
            }
        }
Exemple #16
0
        private void CoreOnNewImage(HImage[] hImage, Guid tmpSessionId)
        {
            //-----------------------------------------------
            lock (this.mIOManager.objectLock)
            {
                //this.mIOManager.SetOutput(numOutRis, false);
                //this.mIOManager.Write(); |MP
                this.mIOManager.SetOutput(numOutBusy, true);
                this.mIOManager.Write();
            }
            //-----------------------------------------------

            //Debug.WriteLine(DateTime.Now.Subtract(start).TotalMilliseconds);
            //start = DateTime.Now;

            lock (OnNewImageLock)
            {
                double startTime = HSystem.CountSeconds();

                HImage[] rotateImage = new HImage[hImage.Length];

                for (int i = 0; i < hImage.Length; i++)
                {
                    HImage rotateImage_ = hImage[i].RotateImage(new HTuple(rotazione[i]), "constant");
                    rotateImage[i] = rotateImage_.MirrorImage("column");
                    rotateImage_.Dispose();
                }

                cts = new CancellationTokenSource(Properties.Settings.Default.TimeoutAlgoritmo);

                ArrayList[]       iconicVarList;
                ElaborateResult[] result;

                ElaborateImage(rotateImage, cts, out iconicVarList, out result);

                //-----------------------------------------------
                lock (this.mIOManager.objectLock)
                {
                    this.mIOManager.SetOutput(numOutRis, result.Count(k => k.Success == true) == result.Length);
                    this.mIOManager.Write();
                    this.mIOManager.SetOutput(numOutBusy, false);
                    this.mIOManager.Write();
                }
                //-----------------------------------------------

                double tAnalisi = HSystem.CountSeconds();
                tAnalisi = (tAnalisi - startTime) * 1000.0;

                if (sessionId != tmpSessionId)
                {
                    //Sessione SCADUTA
                }
                else
                {
                    lock (lastResultLock)
                    {
                        lastResult = result;
                    }
                }

                EventHandler OnFineElaborazioneTmp = OnFineElaborazione;
                if (OnFineElaborazioneTmp != null)
                {
                    OnFineElaborazioneTmp(this, EventArgs.Empty);
                }

                if (result != null)
                {
                    for (int i = 0; i < result.Length; i++)
                    {
                        result[i].ElapsedTime = tAnalisi;
                        ManageErrorImage(iconicVarList[i], result[i]);
                    }
                }

                RaiseNewImageToDisplayEvent(iconicVarList, result);
            }
        }
Exemple #17
0
        /*******************************************************************/
        private void mouseMoved(object sender, HalconDotNet.HMouseEventArgs e)
        {
            double motionX, motionY;
            double posX, posY;
            double zoomZone;
            //if (viewPort.)
            int count = HObjList.Count;

            foreach (var item in HObjList)  //实时显示图片的灰度  灰度显示
            {
                HObjectEntry objNow = (HObjectEntry)item;
                if (objNow.HObj is HImage)
                {
                    try{
                        HObject myImg = new HObject();
                        if (!objNow.HObj.IsInitialized())
                        {
                            break;
                        }
                        //HOperatorSet.CopyObj(objNow.HObj, out myImg, 1, -1);
                        HTuple Gray = new HTuple();
                        HTuple Wid, Hei;
                        HOperatorSet.GetImageSize(objNow.HObj, out Wid, out Hei);
                        if (0 < e.Y && e.Y < Hei && 0 < e.X && e.X < Wid)
                        {
                            repaint(viewPort.HalconWindow);
                            HOperatorSet.GetGrayval(objNow.HObj, e.Y, e.X, out Gray);
                            double scale = (ImgRow2 - ImgRow1) / Hei.D;
                            //HOperatorSet.SetTposition(viewPort.HalconWindow, ImgRow2 - 400 * scale, ImgCol2 - 400 * scale);
                            HOperatorSet.SetTposition(viewPort.HalconWindow, e.Y + 20 * scale, e.X + 50 * scale);
                            HOperatorSet.SetColor(viewPort.HalconWindow, "red");
                            HOperatorSet.WriteString(viewPort.HalconWindow, "R:" + ((int)e.Y).ToString() + " " + "C:" +
                                                     ((int)e.X).ToString() + "  " + ((int)Gray[0].D).ToString());
                        }
                        //myImg.Dispose();
                        break;
                    }
                    catch {
                        break;
                    }
                }
            }
            if (!mousePressed)
            {
                return;
            }
            if (roiManager != null && (roiManager.activeROIidx != -1) && (dispROI == MODE_INCLUDE_ROI))
            {
                roiManager.mouseMoveAction(e.X, e.Y);
            }
            else if (stateView == MODE_VIEW_MOVE)              //平移视图
            {
                motionX = ((e.X - startX));
                motionY = ((e.Y - startY));

                if (((int)motionX != 0) || ((int)motionY != 0))
                {
                    moveImage(motionX, motionY);
                    startX = e.X - motionX;
                    startY = e.Y - motionY;
                }
            }
            else if (stateView == MODE_VIEW_ZOOMWINDOW)              //缩放视图
            {
                HSystem.SetSystem("flush_graphic", "false");
                ZoomWindow.ClearWindow();

                posX     = ((e.X - ImgCol1) / (ImgCol2 - ImgCol1)) * viewPort.Width;
                posY     = ((e.Y - ImgRow1) / (ImgRow2 - ImgRow1)) * viewPort.Height;
                zoomZone = (zoomWndSize / 2) * zoomWndFactor * zoomAddOn;

                ZoomWindow.SetWindowExtents((int)posY - (zoomWndSize / 2),
                                            (int)posX - (zoomWndSize / 2),
                                            zoomWndSize, zoomWndSize);
                ZoomWindow.SetPart((int)(e.Y - zoomZone), (int)(e.X - zoomZone),
                                   (int)(e.Y + zoomZone), (int)(e.X + zoomZone));
                repaint(ZoomWindow);

                HSystem.SetSystem("flush_graphic", "true");
                ZoomWindow.DispLine(-100.0, -100.0, -100.0, -100.0);
            }
        }
Exemple #18
0
        /// <summary>
        /// Repaints the HALCON window 'window'
        /// </summary>
        public void repaint(HalconDotNet.HWindow window)
        {
            lock (lockershow)
            {
                int count = HObjList.Count;
                //HObjectEntry entry;

                HSystem.SetSystem("flush_graphic", "false");
                window.ClearWindow();
                mGC.stateOfSettings.Clear();

                //for (int i = 0; i < count; i++)
                //{
                //    entry = ((HObjectEntry)HObjList[i]);
                //    mGC.applyContext(window, entry.gContext);
                //    window.DispObj(entry.HObj);
                //}
                if (entry != null)
                {
                    try
                    {
                        mGC.applyContext(window, entry.gContext);
                        window.DispObj(entry.HObj);
                    }
                    catch (Exception ex)
                    { }
                }
                addInfoDelegate();

                if (roiManager != null && (dispROI == MODE_INCLUDE_ROI))
                {
                    roiManager.paintData(window);
                }

                HSystem.SetSystem("flush_graphic", "true");

                if (myRect.Count != 0)
                {
                    window.SetColor("green");
                    window.SetLineWidth(2);
                    HObject ho_Rect = new HObject();

                    for (int i = 0; i < myRect.Count; i++)
                    {
                        if (myRect[i].isCircle)
                        {
                            window.SetColor("green");
                            window.SetLineWidth(2);
                            if (myRect[i].Found)
                            {
                                HOperatorSet.GenCircleContourXld(out ho_Rect, myRect[i].Y, myRect[i].X, myRect[i].Radius, 0, 6.28318, "positive", 1.0);
                                window.DispObj(ho_Rect);
                            }
                            //window.DispCircle(myRect[i].Y, myRect[i].X, myRect[i].Radius);
                            window.DispCross(myRect[i].Y, myRect[i].X, 50, 0);

                            disp_message(window, "X:" + myRect[i].X.ToString("F1") + ", Y:" + myRect[i].Y.ToString("F1") + ", Means:" + myRect[i].Means.ToString("F1"), "image", 100, 50, "green", "false");
                            disp_message(window, "Radius:" + myRect[i].Radius.ToString("F1") + ",Angle:" + Helper.GetDegreeFromRadian((float)myRect[i].Angle).ToString("F1"), "image", 300, 50, "green", "false");
                        }
                        else
                        {
                            window.SetColor("green");
                            window.SetLineWidth(2);
                            if (myRect[i].Found)
                            {
                                HOperatorSet.GenRectangle2ContourXld(out ho_Rect, myRect[i].Y, myRect[i].X, myRect[i].Angle, myRect[i].Width / 2, myRect[i].Height / 2);
                                window.DispObj(ho_Rect);
                            }
                            //if (myRect[i].Found)
                            //{
                            //window.SetColor("cyan");
                            //window.DispObj(myRect[i].rect_border);
                            //}
                            window.DispCross(myRect[i].Y, myRect[i].X, 50, 0);

                            disp_message(window, "X:" + myRect[i].X.ToString("F1") + ", Y:" + myRect[i].Y.ToString("F1") + ", Means:" + myRect[i].Means.ToString("F1"), "image", 100, 50, "green", "false");
                            disp_message(window, "Width:" + myRect[i].Width.ToString("F1") + ", Height:" + myRect[i].Height.ToString("F1"), "image", 300, 50, "green", "false");
                            //disp_message(window, "Means:" + myRect[i].Means.ToString("F1"), "image", 500, 50, "green", "false");
                        }
                    }

                    //for (int i = 0; i < myRect.Count; i++)
                    //    window.DispRectangle2(myRect[i].Y, myRect[i].X, myRect[i].Angle, myRect[i].Width / 2, myRect[i].Length / 2);
                }

                if (bShowCrossHair)
                {
                    window.SetColor("red");
                    window.SetLineWidth(2);
                    int winrow, winclom, winwidth, winHeight;
                    window.GetPart(out winrow, out winclom, out winwidth, out winHeight);
                    window.DispLine(winrow + (winwidth - winrow) / 2, (double)winclom, winrow + (winwidth - winrow) / 2, winHeight);
                    window.DispLine((double)winrow, winclom + (winHeight - winclom) / 2, winwidth, winclom + (winHeight - winclom) / 2);
                }

                if (IsDrawCross1)
                {
                    window.DispCross(200.0, 200.0, 40, 0);
                    //window.WriteString("标定1");
                }
                if (IsDrawCross2)
                {
                    //window.DispCross(200.0, 200.0, 2, 0);
                    window.DispCross(600.0, 600.0, 40, 0);
                    // window.WriteString("标定2");
                }
            }
        }
Exemple #19
0
        public HXLDCont FindShapeModel(HImage img,
                                       HShapeModel model,
                                       FindModelParameter findModelParameter,
                                       out HTuple row,
                                       out HTuple column,
                                       out HTuple angle,
                                       out HTuple scale,
                                       out HTuple score)
        {
            var t1 = HSystem.CountSeconds();

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

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

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

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

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

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

            var contoursAffinTrans = modelContours.AffineTransContourXld(homMat2D);

            return(contoursAffinTrans);
        }
Exemple #20
0
        /// <summary>
        /// Finds the model in the test image. If the model
        /// hasn't been created or needs to be recreated (due to
        /// user changes made to the GUI components),
        /// then the model is created first.
        /// </summary>

        public bool detectShapeModel()
        {
            string log = "detectShapeModel:";
            HTuple levels, rtmp;

            rtmp = new HTuple();
            double t2, t1;
            bool   isSuccess = false;

            if (mTestImage == null)
            {
                return(false);
            }

            //if(createNewModelID/* && !onExternalModelID*/)
            //    if(!createShapeModel())
            //        return false;

            try
            {
                tResult.isGrayModel = false;
                int secondLevel = parameterSet.mNumLevel - 2;
                secondLevel = secondLevel > 1 ? secondLevel : 1;
                levels      = new HTuple(new int[] { parameterSet.mNumLevel, secondLevel });
                t1          = HSystem.CountSeconds();
                mTestImage.FindShapeModel(ModelID,
                                          parameterSet.mStartingAngle,
                                          parameterSet.mAngleExtent,
                                          parameterSet.mMinScore,
                                          parameterSet.mNumMatches,
                                          parameterSet.mMaxOverlap,
                                          new HTuple(parameterSet.mSubpixel),
                                          levels,
                                          parameterSet.mGreediness,
                                          out tResult.mRow,
                                          out tResult.mCol,
                                          out tResult.mAngle,
                                          out tResult.mScore);

                tResult.mRow        = tResult.mRow / parameterSet.mImageSizeScale;
                tResult.mCol        = tResult.mCol / parameterSet.mImageSizeScale;
                tResult.mImageScale = parameterSet.mImageSizeScale;
                isSuccess           = tResult.mRow.Length > 0;
                if (!isSuccess && IsEnableGrayTemplate && GrayTemplate != null && GrayTemplate.IsInitialized())
                {
                    log += "ÐÎ×´Æ¥Åäʧ°Ü";
                    double row, col;
                    mTestImage.BestMatchMg(GrayTemplate, parameterSet.mMaxError, parameterSet.mSubpixel, parameterSet.mNumLevel, "all", out row, out col, out tResult.mError);
                    isSuccess = row > 0 && col > 0;
                    if (isSuccess)
                    {
                        log                += ",»Ò¶ÈÆ¥ÅäOK";
                        tResult.mRow        = row;
                        tResult.mCol        = col;
                        tResult.mAngle      = 0;
                        tResult.mScore      = 0.701;
                        tResult.isGrayModel = true;
                    }
                    else
                    {
                        tResult.mRow   = 0;
                        tResult.mCol   = 0;
                        tResult.mAngle = 0;
                        tResult.mScore = 0;
                        log           += ",»Ò¶ÈÆ¥ÅäNG,error=" + tResult.mError.ToString();
                    }

                    Logger.Pop(log);
                }
                t2 = HSystem.CountSeconds();
                //tResult.mAngle = 0;
                tResult.mTime     = 1000.0 * (t2 - t1);
                tResult.count     = tResult.mRow.Length;
                tResult.mScaleCol = tResult.mScaleRow;
            }
            catch (HOperatorException e)
            {
                if (!onTimer)
                {
                    exceptionText = e.Message;
                    NotifyParamObserver(MatchingParam.H_ERR_MESSAGE);
                }

                return(false);
            }

            NotifyIconObserver(MatchingAssistant.UPDATE_DETECTION_RESULT);
            return(isSuccess);
        }
        public void FindShapeModel(HImage Img, HWindow window, double row1, double col1, double row2, double col2, double rowMark, double colMark)
        {
            double    S1, S2;
            HTuple    RowCheck, ColumnCheck, AngleCheck, Score;
            HHomMat2D Matrix = new HHomMat2D();
            HRegion   ModelRegionTrans;
            HTuple    row1Check, col1Check;
            HTuple    row2Check, col2Check;
            HRegion   Rectangle1 = new HRegion();

            //HRegion           Rectangle2 = new HRegion();
            //HMeasure          Measure1, Measure2;
            //HTuple            RowEdgeFirst1, ColumnEdgeFirst1;
            //HTuple            AmplitudeFirst1, RowEdgeSecond1;
            //HTuple            ColumnEdgeSecond1, AmplitudeSecond1;
            //HTuple            IntraDistance1, InterDistance1;
            //HTuple            RowEdgeFirst2, ColumnEdgeFirst2;
            //HTuple            AmplitudeFirst2, RowEdgeSecond2;
            //HTuple            ColumnEdgeSecond2, AmplitudeSecond2;
            //HTuple            IntraDistance2, InterDistance2;
            //HTuple            MinDistance;
            //int               NumLeads;

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

            // Find the IC in the current image.
            S1 = HSystem.CountSeconds();
            ShapeModel.FindShapeModel(Img, 0,
                                      new HTuple(360).TupleRad().D,
                                      0.7, 1, 0.5, "least_squares",
                                      4, 0.9, out RowCheck, out ColumnCheck,
                                      out AngleCheck, out Score);
            S2 = HSystem.CountSeconds();
            if (RowCheck.Length == 1)
            {
                //MatchingScoreLabel.Text = "Score: " +
                //    String.Format("{0:F5}", Score.D);
                // Rotate the model for visualization purposes.
                //创建严格的仿射变换VectorAngleToRigid
                Matrix.VectorAngleToRigid(new HTuple((row1 + row2) / 2), new HTuple((col1 + col2) / 2), new HTuple(0.0),
                                          RowCheck - rowMark + rowOrg, ColumnCheck - colMark + colOrg, AngleCheck);
                //根据Matrix变换ModelRegion
                ModelRegionTrans = ModelRegion.AffineTransRegion(Matrix, "false");
                window.SetColor("red");
                window.SetDraw("margin");
                window.SetLineWidth(2);
                ModelRegionTrans.DispObj(window);
                // Compute the parameters of the measurement rectangles.
                Matrix.AffineTransPixel(new HTuple(row1), new HTuple(col1),
                                        out row1Check, out col1Check);
                Matrix.AffineTransPixel(new HTuple(row2), new HTuple(col2),
                                        out row2Check, out col2Check);
                Rectangle1.GenRectangle1(row1Check, col1Check, row2Check, col2Check);
                window.SetColor("green");
                window.SetDraw("margin");
                window.SetLineWidth(1);
                Rectangle1.DispObj(window);
                window.SetColor("gold");
                window.DispLine(RowCheck - 15, ColumnCheck, RowCheck + 15, ColumnCheck);
                window.DispLine(RowCheck, ColumnCheck - 15, RowCheck, ColumnCheck + 45);


                // For visualization purposes, generate the two rectangles as
                // regions and display them.
                //Rectangle1.GenRectangle2(Rect1RowCheck.D, Rect1ColCheck.D,
                //    RectPhi + AngleCheck.D,
                //    RectLength1, RectLength2);
                //Rectangle2.GenRectangle2(Rect2RowCheck.D, Rect2ColCheck.D,
                //    RectPhi + AngleCheck.D,
                //    RectLength1, RectLength2);
                //window.SetColor("blue");
                //window.SetDraw("margin");
                //Rectangle1.DispObj(window);
                //Rectangle2.DispObj(window);
            }
            //MatchingTimeLabel.Text = "Time: " +
            //    String.Format("{0,4:F1}", (S2 - S1)*1000) + "ms";
            //MatchingScoreLabel.Text = "Score: ";
            //{
            //    MatchingScoreLabel.Text = "Score: " +
            //        String.Format("{0:F5}", Score.D);
            //    // Rotate the model for visualization purposes.
            //    Matrix.VectorAngleToRigid(new HTuple(Row), new HTuple(Column), new HTuple(0.0),
            //        RowCheck, ColumnCheck, AngleCheck);

            //    ModelRegionTrans = ModelRegion.AffineTransRegion(Matrix, "false");
            //window.SetColor("green");
            //window.SetDraw("fill");
            ////ModelRegionTrans.DispObj(window);
        }
Exemple #22
0
        public void FindModel()
        {
            OutputResult.Reset();

            HImage img = InputImg;

            if (!img.IsInitialized())
            {
                return;
            }

            if (SearchRegion == null || !SearchRegion.IsInitialized())
            {
                SearchRegion = img.GetDomain();
            }

            if (createNewModelID)
            {
                if (!CreateModel())
                {
                    return;
                }
            }

            if (!shapeModel.IsInitialized())
            {
                throw new Exception("无创建的模板");
            }

            if (!img.IsInitialized())
            {
                throw new Exception("图片无效");
            }

            HRegion domain          = img.GetDomain();
            HRegion differentdomain = domain.Difference(SearchRegion);
            HImage  searchImg       = img.PaintRegion(differentdomain, 0.0, "fill");
            HImage  cropImg         = searchImg.ReduceDomain(SearchRegion);

            domain.Dispose();
            differentdomain.Dispose();

            try
            {
                double t1, t2;
                t1 = HSystem.CountSeconds();
                HOperatorSet.FindScaledShapeModel(cropImg, shapeModel, shapeParam.mStartingAngle, shapeParam.mAngleExtent, shapeParam.mMinScale, shapeParam.mMaxScale,
                                                  shapeParam.mMinScore, shapeParam.mNumMatches, shapeParam.mMaxOverlap, shapeParam.mSubpixel, 0, shapeParam.mGreediness,
                                                  out OutputResult.Row, out OutputResult.Col, out OutputResult.Angle, out OutputResult.Scale, out OutputResult.Score);

                OutputResult.TemplateHand = shapeModel;
                t2 = HSystem.CountSeconds();
                OutputResult.Time  = 1000.0 * (t2 - t1);
                OutputResult.Count = OutputResult.Row.Length;
            }
            catch (HOperatorException ex)
            {
                if (ex.GetErrorCode() != 9400)
                {
                    throw ex;
                }
            }

            searchImg.Dispose();
            cropImg.Dispose();
        }
        private void StartBtn_Click(object sender, System.EventArgs e)
        {
            Framegrabber = new HFramegrabber();
            // read images and process them
            try
            {
                //Framegrabber.OpenFramegrabber("DirectShow", 1, 1, 0, 0, 0, 0, "default", 8, "rgb", -1, "false", "default", "[0] USB2.0 HD UVC WebCam", 0, -1);


                Framegrabber.OpenFramegrabber("GigEVision", 0, 0, 0, 0, 0, 0, "default", -1, "default", -1,
                                              "false", "default", "003053231ec3_basler_aca250014gm", 0, -1);
                Framegrabber.SetFramegrabberParam("AcquisitionMode", "SingleFrame");
                HImage  Image = new HImage();
                HRegion CirclesRegion;

                int shot;
                shot = Int32.Parse(shotComboBox.SelectedItem + "");

                // execute procedure
                ProcCall.SetInputCtrlParamTuple("shot", shot);
                ProcCall.Execute();
                // get output parameters from procedure call
                CirclesRegion = ProcCall.GetOutputIconicParamRegion("RegionOfInterest");
                //LightCheck = ProcCall.GetOutputIconicParamRegion("RegionOfInterest");



                StartBtn.Enabled     = false;
                shotComboBox.Enabled = false;
                Savebtn.Enabled      = true;
                StopBtn.Enabled      = true;
                while (true)
                {
                    if (!StopBtn.Enabled)
                    {
                        StartBtn.Enabled = true;
                        StopBtn.Enabled  = false;
                        Framegrabber.Dispose();
                        Image.Dispose();
                        return;
                    }
                    //Framegrabber.GrabImageStart(-1);
                    Image = Framegrabber.GrabImageAsync(-1);

                    // display results
                    Image.DispObj(Window);
                    Window.SetColor("red");
                    Window.DispObj(CirclesRegion);
                    Window.SetPart(0, 0, -2, -2);

                    HSystem.WaitSeconds(0.108);
                }
            }
            catch (HOperatorException Ex)
            {
                MessageBox.Show(Ex.Message, "HALCON Exception");
            }
            catch (HDevEngineException Ex)
            {
                MessageBox.Show(Ex.Message, "HDevEngine Exception");
            }

            Framegrabber.Dispose();
        }
Exemple #24
0
 void HSettings_ReloadSettings()
 {
     HSystem.RebuildSystemPath();
 }
        private void Action()
        {
            double    S1, S2;
            HTuple    RowCheck, ColumnCheck, AngleCheck, Score;
            HHomMat2D Matrix = new HHomMat2D();
            HRegion   ModelRegionTrans;
            HTuple    Rect1RowCheck, Rect1ColCheck;
            HTuple    Rect2RowCheck, Rect2ColCheck;
            HRegion   Rectangle1 = new HRegion();
            HRegion   Rectangle2 = new HRegion();
            HMeasure  Measure1, Measure2;
            HTuple    RowEdgeFirst1, ColumnEdgeFirst1;
            HTuple    AmplitudeFirst1, RowEdgeSecond1;
            HTuple    ColumnEdgeSecond1, AmplitudeSecond1;
            HTuple    IntraDistance1, InterDistance1;
            HTuple    RowEdgeFirst2, ColumnEdgeFirst2;
            HTuple    AmplitudeFirst2, RowEdgeSecond2;
            HTuple    ColumnEdgeSecond2, AmplitudeSecond2;
            HTuple    IntraDistance2, InterDistance2;
            HTuple    MinDistance;
            int       NumLeads;

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

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

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

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

                // For visualization purposes, generate the two rectangles as
                // regions and display them.
                Rectangle1.GenRectangle2(Rect1RowCheck.D, Rect1ColCheck.D,
                                         RectPhi + AngleCheck.D,
                                         RectLength1, RectLength2);
                Rectangle2.GenRectangle2(Rect2RowCheck.D, Rect2ColCheck.D,
                                         RectPhi + AngleCheck.D,
                                         RectLength1, RectLength2);
                Window.SetColor("blue");
                Window.SetDraw("margin");
                Rectangle1.DispObj(Window);
                Rectangle2.DispObj(Window);
                // Do the actual measurements.
                S1       = HSystem.CountSeconds();
                Measure1 = new HMeasure(Rect1RowCheck.D, Rect1ColCheck.D,
                                        RectPhi + AngleCheck.D,
                                        RectLength1, RectLength2,
                                        ImgWidth, ImgHeight, "bilinear");
                Measure2 = new HMeasure(Rect2RowCheck.D, Rect2ColCheck.D,
                                        RectPhi + AngleCheck.D,
                                        RectLength1, RectLength2,
                                        ImgWidth, ImgHeight, "bilinear");
                Measure1.MeasurePairs(Img, 2, 90,
                                      "positive", "all",
                                      out RowEdgeFirst1,
                                      out ColumnEdgeFirst1,
                                      out AmplitudeFirst1,
                                      out RowEdgeSecond1,
                                      out ColumnEdgeSecond1,
                                      out AmplitudeSecond1,
                                      out IntraDistance1,
                                      out InterDistance1);
                Measure2.MeasurePairs(Img, 2, 90,
                                      "positive", "all",
                                      out RowEdgeFirst2,
                                      out ColumnEdgeFirst2,
                                      out AmplitudeFirst2,
                                      out RowEdgeSecond2,
                                      out ColumnEdgeSecond2,
                                      out AmplitudeSecond2,
                                      out IntraDistance2,
                                      out InterDistance2);
                S2 = HSystem.CountSeconds();
                MeasureTimeLabel.Text = "Time: " +
                                        String.Format("{0,5:F1}", (S2 - S1) * 1000) + "ms";
                Window.SetColor("red");
                Window.DispLine(RowEdgeFirst1 - RectLength2 * Math.Cos(AngleCheck),
                                ColumnEdgeFirst1 - RectLength2 * Math.Sin(AngleCheck),
                                RowEdgeFirst1 + RectLength2 * Math.Cos(AngleCheck),
                                ColumnEdgeFirst1 + RectLength2 * Math.Sin(AngleCheck));
                Window.DispLine(RowEdgeSecond1 - RectLength2 * Math.Cos(AngleCheck),
                                ColumnEdgeSecond1 - RectLength2 * Math.Sin(AngleCheck),
                                RowEdgeSecond1 + RectLength2 * Math.Cos(AngleCheck),
                                ColumnEdgeSecond1 + RectLength2 * Math.Sin(AngleCheck));
                Window.DispLine(RowEdgeFirst2 - RectLength2 * Math.Cos(AngleCheck),
                                ColumnEdgeFirst2 - RectLength2 * Math.Sin(AngleCheck),
                                RowEdgeFirst2 + RectLength2 * Math.Cos(AngleCheck),
                                ColumnEdgeFirst2 + RectLength2 * Math.Sin(AngleCheck));
                Window.DispLine(RowEdgeSecond2 - RectLength2 * Math.Cos(AngleCheck),
                                ColumnEdgeSecond2 - RectLength2 * Math.Sin(AngleCheck),
                                RowEdgeSecond2 + RectLength2 * Math.Cos(AngleCheck),
                                ColumnEdgeSecond2 + RectLength2 * Math.Sin(AngleCheck));
                NumLeads             = IntraDistance1.Length + IntraDistance2.Length;
                MeasureNumLabel.Text = "Number of leads: " +
                                       String.Format("{0:D2}", NumLeads);
                MinDistance           = InterDistance1.TupleConcat(InterDistance2).TupleMin();
                MeasureDistLabel.Text = "Minimum lead distance: " +
                                        String.Format("{0:F3}", MinDistance.D);
                HSystem.SetSystem("flush_graphic", "true");
                // Force the graphics window update by displaying an offscreen pixel
                Window.DispLine(-1.0, -1.0, -1.0, -1.0);
            }
        }
        /// <summary>
        /// Repaints the HALCON window 'window'
        /// </summary>
        public void repaint(HalconDotNet.HWindow window)
        {
            try
            {
                int          count = HObjList.Count;
                HObjectEntry entry;

                HSystem.SetSystem("flush_graphic", "false");
                window.ClearWindow();
                mGC.stateOfSettings.Clear();

                for (int i = 0; i < count; i++)
                {
                    entry = ((HObjectEntry)HObjList[i]);
                    mGC.applyContext(window, entry.gContext);
                    window.DispObj(entry.HObj);
                }

                addInfoDelegate();

                if (_roiManager != null && (_dispROI == MODE_INCLUDE_ROI))
                {
                    _roiManager.paintData(window);
                }


                var prevScaleC = (double)((ImgCol2 - ImgCol1) / imageWidth);
                foreach (var wViewModel in WriteStringList)
                {
                    window.SetColor("red");
                    HOperatorSet.SetTposition(window, wViewModel.Row, wViewModel.Col);
                    HOperatorSet.WriteString(window, wViewModel.Text);
                }
                //Display Arrow
                var arrowSize = 5 * prevScaleC;
                arrowSize = (arrowSize < 2) ? 2 : arrowSize;
                foreach (var arrowModel in ArrowList)
                {
                    HOperatorSet.DispArrow(window, arrowModel.CenterY, arrowModel.CenterX, arrowModel.FirstArrowY, arrowModel.FirstArrowX, arrowSize);
                    HOperatorSet.DispArrow(window, arrowModel.CenterY, arrowModel.CenterX, arrowModel.SecArrowY, arrowModel.SecArrowX, arrowSize);
                }

                //畫格線
                if (ShowGrid)
                {
                    drawGridLines(window);
                }
                HSystem.SetSystem("flush_graphic", "true");

                window.SetColor(this.RepaintWindowColor);
                window.DispLine(-100.0, -100.0, -101.0, -101.0);
            }
            catch (HOperatorException ex)
            {
                var errorNumber = ex.GetErrorNumber();

                /*
                 * 5106 發生情境為
                 * 1。開啟擷取影像後,未斷線就關閉 MDI 視窗
                 */
                if (errorNumber != 5106 && errorNumber != 5100)
                {
                    Hanbo.Log.LogManager.Error(ex);
                }
            }
        }
        private void hWindowControl1_HMouseWheel(object sender, HMouseEventArgs e)
        {
            if (_ho_Image.IsInitialized())
            {
                double mposition_row = 0, mposition_col = 0;
                int    button_state;
                //HWindow hv_window = hWindowControl1.HalconWindow;

                try
                {
                    hWindowControl1.HalconWindow.GetMpositionSubPix(out mposition_row, out mposition_col, out button_state);
                    hWindowControl1.HalconWindow.GetPart(out current_beginRow, out current_beginCol, out current_endRow, out current_endCol);
                }
                catch (Exception ex)
                {
                    StatusMessage.Text = ex.Message;
                }

                if (e.Delta > 0)                 // 放大图像
                {
                    zoom_beginRow = (int)(current_beginRow + (mposition_row - current_beginRow) * 0.300d);
                    zoom_beginCol = (int)(current_beginCol + (mposition_col - current_beginCol) * 0.300d);
                    zoom_endRow   = (int)(current_endRow - (current_endRow - mposition_row) * 0.300d);
                    zoom_endCol   = (int)(current_endCol - (current_endCol - mposition_col) * 0.300d);
                }
                else                // 缩小图像
                {
                    zoom_beginRow = (int)(mposition_row - (mposition_row - current_beginRow) / 0.700d);
                    zoom_beginCol = (int)(mposition_col - (mposition_col - current_beginCol) / 0.700d);
                    zoom_endRow   = (int)(mposition_row + (current_endRow - mposition_row) / 0.700d);
                    zoom_endCol   = (int)(mposition_col + (current_endCol - mposition_col) / 0.700d);
                }

                try
                {
                    int hw_width, hw_height;
                    hw_width  = hWindowControl1.Size.Width;
                    hw_height = hWindowControl1.Size.Height;

                    HTuple width, height;
                    HOperatorSet.GetImageSize(_ho_Image, out width, out height);

                    bool _isOutOfArea  = true;
                    bool _isOutOfSize  = true;
                    bool _isOutOfPixel = true; //避免像素过大

                    _isOutOfArea  = zoom_beginRow >= (int)height || zoom_endRow <= 0 || zoom_beginCol >= (int)width || zoom_endCol < 0;
                    _isOutOfSize  = (zoom_endRow - zoom_beginRow) > (int)height * 20 || (zoom_endCol - zoom_beginCol) > (int)width * 20;
                    _isOutOfPixel = hw_height / (zoom_endRow - zoom_beginRow) > 500 || hw_width / (zoom_endCol - zoom_beginCol) > 500;

                    if (_isOutOfArea || _isOutOfSize)
                    {
                        HOperatorSet.SetPart(hWindowControl1.HalconWindow, 0, 0, height - 1, width - 1);
                        hWindowControl1.HalconWindow.DispObj(_ho_Image);
                    }
                    else if (!_isOutOfPixel)
                    {
                        HSystem.SetSystem("flush_graphic", "false");//防止图片频闪
                        hWindowControl1.HalconWindow.ClearWindow();
                        zoom_endCol = zoom_beginCol + (zoom_endRow - zoom_beginRow) * hw_width / hw_height;
                        hWindowControl1.HalconWindow.SetPart(zoom_beginRow, zoom_beginCol, zoom_endRow, zoom_endCol);
                        HSystem.SetSystem("flush_graphic", "true");//防止图片频闪
                        hWindowControl1.HalconWindow.DispObj(_ho_Image);

                        if (Repaint != null)
                        {
                            Repaint(hWindowControl1.HalconWindow);
                        }

                        if (this.RepaintingROI != null)
                        {
                            this.RepaintingROI(null, null);
                        }
                    }
                }
                catch (Exception ex)
                {
                    DispImageFit();
                    StatusMessage.Text = ex.Message;
                }
            }
        }
Exemple #28
0
        private void hWindowControl2_HMouseMove(object sender, HMouseEventArgs e)
        {
            HTuple x = 0, y = 0, z = 0;

            x = e.X;
            y = e.Y;

            if (mainForm.ho_MainImagePositiveB != null && mainForm.ImageHeightPositiveB != null)
            {
                try
                {
                    HOperatorSet.GetGrayval(mainForm.ho_MainImagePositiveB, y, x, out z);
                }
                catch
                {
                    if (x > 4096)
                    {
                        x = 4096;
                    }
                    if (y > mainForm.ImageHeightPositiveB)
                    {
                        y = mainForm.ImageHeightPositiveB;
                    }
                }

                lblPointInfoRowB.Text       = y.TupleInt().ToString();
                lblPointInfoColumnB.Text    = x.TupleInt().ToString();
                lblPointInfoGrayValueB.Text = z.ToString();
            }


            if (!bl_IsMoveB)
            {
                return;
            }
            try
            {
                HTuple row, col;
                GetPosB(out row, out col);

                dbl_PositionB[2] = col;
                dbl_PositionB[3] = row;

                double[] vecB = { dbl_PositionB[2] - dbl_PositionB[0], dbl_PositionB[3] - dbl_PositionB[1] };
                hv_c1B = hv_c1B - vecB[0];
                hv_c2B = hv_c2B - vecB[0];
                hv_r1B = hv_r1B - vecB[1];
                hv_r2B = hv_r2B - vecB[1];
                HOperatorSet.SetPart(hWindowIDTwo, hv_r1B, hv_c1B, hv_r2B, hv_c2B);

                //清除halconWindow窗口 ,避免闪屏
                HSystem.SetSystem("flush_graphic", "false");
                HOperatorSet.ClearWindow(hWindowIDTwo);
                HSystem.SetSystem("flush_graphic", "true");

#if CPlusPlus
                ShowImage(DE.htup_WindowHandle, DE.bl_showdefect);
#else
                HOperatorSet.DispObj(mainForm.ho_MainImagePositiveB, hWindowIDTwo);
#endif
            }
            catch { }
        }
        private void hWindowControl1_HMouseMove(object sender, HMouseEventArgs e)
        {
            if (_ho_Image.IsInitialized())
            {
                try
                {
                    int    button_state;
                    double positionX, positionY;

                    hWindowControl1.HalconWindow.GetMpositionSubPix(out positionY, out positionX, out button_state);//得到亚像素组成 取得坐标,及鼠标的状态

                    switch (button_state)
                    {
                    case 0:
                        this.Cursor = System.Windows.Forms.Cursors.Default;    //显示鼠标类型为手型

                        #region  显示像素
                        string str_value;
                        string str_position;
                        bool   _isXOut = true, _isYOut = true;
                        HTuple channel_count;                                                               //元素
                        HOperatorSet.CountChannels(_ho_Image, out channel_count);                           //计算图片的通道
                        str_position = String.Format("X: {0:0000.0}, Y: {1:0000.0}", positionX, positionY); //把坐标转成字符
                        HTuple width, height;
                        HOperatorSet.GetImageSize(_ho_Image, out width, out height);
                        _isXOut = (positionX < 0 || positionX >= (double)width);    //判断是否超出范围,超出为1
                        _isYOut = (positionY < 0 || positionY >= (double)height);   //判断是否超出范围,超出为1

                        if (!_isXOut && !_isYOut)
                        {
                            if ((int)channel_count == 1)
                            {
                                HTuple grayval;
                                HOperatorSet.GetGrayval(_ho_Image, (HTuple)positionY, (HTuple)positionX, out grayval);
                                str_value = String.Format("灰度值: {0:000.0}", (double)grayval);    //显示出去
                            }
                            else
                            {
                                if ((int)channel_count == 3)
                                {
                                    str_value = "";
                                    HTuple  grayValRed, grayValGreen, grayValBlue;
                                    HObject _RedChannel, _GreenChannel, _BlueChannel;
                                    HOperatorSet.GenEmptyObj(out _RedChannel);
                                    HOperatorSet.GenEmptyObj(out _GreenChannel);
                                    HOperatorSet.GenEmptyObj(out _BlueChannel);
                                    HOperatorSet.AccessChannel(_ho_Image, out _RedChannel, 1);
                                    HOperatorSet.AccessChannel(_ho_Image, out _GreenChannel, 2);
                                    HOperatorSet.AccessChannel(_ho_Image, out _BlueChannel, 3);

                                    HOperatorSet.GetGrayval(_RedChannel, (HTuple)positionY, (HTuple)positionX, out grayValRed);
                                    HOperatorSet.GetGrayval(_GreenChannel, (HTuple)positionY, (HTuple)positionX, out grayValGreen);
                                    HOperatorSet.GetGrayval(_BlueChannel, (HTuple)positionY, (HTuple)positionX, out grayValBlue);

                                    _RedChannel.Dispose();
                                    _GreenChannel.Dispose();
                                    _BlueChannel.Dispose();

                                    str_value = String.Format("Val: ({0:000.0}, {1:000.0}, {2:000.0})", (double)grayValRed, (double)grayValGreen, (double)grayValBlue);    //显示3个通道的灰度值
                                }
                                else
                                {
                                    str_value = "";
                                }
                            }
                            StatusMessage.Text = str_position + "    " + str_value;
                        }
                        #endregion

                        break;

                    case 1:
                        this.Cursor = System.Windows.Forms.Cursors.Hand;    //显示鼠标类型为手型

                        switch (_roiStatus)
                        {
                        case ROIStatus.ChioceROI:
                            #region  拉动ROI

                            _roiControl.setROISelectedPoint(positionX, positionY);

                            if (this.ROIPointMoveEvent != null)
                            {
                                this.ROIPointMoveEvent();
                            }

                            #endregion
                            break;

                        case ROIStatus.NoChioceROI:
                            #region  拉动图片
                            HSystem.SetSystem("flush_graphic", "false");                  //防止图片频闪
                            hWindowControl1.HalconWindow.ClearWindow();                   //清空窗体类容
                            hWindowControl1.HalconWindow.SetPaint(new HTuple("default")); //设置显示默认
                            //              保持图像显示比例

                            zoom_beginRow -= (int)(positionY - _start_positionY);
                            zoom_beginCol -= (int)(positionX - _start_positionX);
                            zoom_endRow   -= (int)(positionY - _start_positionY);
                            #region  无用代码
                            //if (zoom_endRow == zoom_beginRow)
                            //{
                            //    //HOperatorSet.GetImageSize(_ho_Image);
                            //    zoom_endRow = 2000;
                            //}
                            #endregion
                            zoom_endCol -= (int)(positionX - _start_positionX);


                            if ((zoom_endCol == zoom_beginCol) || (zoom_endRow == zoom_beginRow))
                            {
                                HTuple w, h;
                                HOperatorSet.GetImageSize(_ho_Image, out w, out h);
                                zoom_endCol = (int)w;
                                zoom_endRow = (int)h;
                            }
                            hWindowControl1.HalconWindow.SetPart(zoom_beginRow, zoom_beginCol, zoom_endRow, zoom_endCol);
                            // hWindowControl1.HalconWindow.DispObj(_ho_Image);//显示图片
                            HSystem.SetSystem("flush_graphic", "true");
                            #endregion
                            break;
                        }

                        #region  重新刷新图片
                        this._halconWindow1.DispObj(this.Ho_Image);
                        if (this.RepaintingROI != null)
                        {
                            this.RepaintingROI(null, null);
                        }
                        #endregion

                        break;
                    }
                }
                catch (Exception ex)
                {
                    StatusMessage.Text = ex.Message;
                }
            }
        }
Exemple #30
0
 void HSettings_Loaded()
 {
     HSystem.RebuildSystemPath();
 }