public void GetCalibrationPlateMarkViewModelTest(string testCaseDir)
        {
            //assign
            var calc = new CalibImageCalculator();
            var caseDirInfo = new DirectoryInfo(testCaseDir);
            var descFile = caseDirInfo.GetFiles("caltab.descr").SingleOrDefault().FullName;

            var plateParamPath = caseDirInfo.GetFiles("calibParam.xml").SingleOrDefault().FullName;
            var startCamParamPath = caseDirInfo.GetFiles("startCamParam.dat").SingleOrDefault().FullName;
            CalibrationPlateParam plateParam;
            using (FileStream fs = new FileStream(plateParamPath, FileMode.Open))
            {
                XmlSerializer sr = new XmlSerializer(typeof(CalibrationPlateParam));
                plateParam = (CalibrationPlateParam)sr.Deserialize(fs);
            }

            HTuple startCamParam;
            HOperatorSet.ReadCamPar(startCamParamPath, out startCamParam);

            //act
            foreach (FileInfo imgInfo in caseDirInfo.EnumerateFiles(@"calibImages\*.tiff"))
            {
                var img = new HImage(imgInfo.FullName);
                var model = calc.GetCalibrationPlateMarkViewModel(descFile, img, plateParam, startCamParam);

                //assert
                Assert.True(model.Valid);
            }
        }
Пример #2
0
        //public static void Halcon_Inspect(string image, double row, double column, double radius, out byte[] imageAffinTrans,
        //    out byte[] selectedRegions, int ModelID, double rstd, double cstd,
        //    double VmodleR, double VmodleG, double VmodleB, double minarea)
        //{
        //}
        public static void Main()
        {
            Bitmap bitmap = new Bitmap(@"C:\Users\yuczhang\Downloads\deco\deco\MANUAL_20100514143231_0_0000_R.bmp");
            Rectangle rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
            BitmapData bmData = bitmap.LockBits(rect, ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format8bppIndexed);
            IntPtr pBitmap = bmData.Scan0;
            //pPixels = pBitmap;

            HImage hImage = new HImage();
            hImage.GenImage1("byte", bitmap.Width, bitmap.Height, pBitmap);

            bitmap.UnlockBits(bmData);

            HObject circle = null;
            HOperatorSet.GenEmptyObj(out circle);
            HTuple ModelID;
            HTuple rstd;
            HTuple cstd;
            HTuple VmodleR, VmodleG, VmodleB;

            GenerateFuctions.Normal_Train_Init(hImage, out circle, 27.6, 48.7, 239.1, 338.3, 139, 186.6, 85.1,
                out ModelID, out  rstd, out cstd, out VmodleR, out VmodleG, out VmodleB);
            IntPtr p = IntPtr.Zero;
            IntPtr q = IntPtr.Zero;
            int width = 0;
            int height = 0;
            Halcon_Train(@"C:\Users\yuczhang\Downloads\deco\deco\MANUAL_20100514143231_0_0000_R.bmp", 27.6, 48.7, 239.1, 338.3, 139, 186.6, 85.1,
            @"C:\Users\yuczhang\Downloads\deco\deco\", out p, out width, out height, out q);
            Bitmap bmp = new Bitmap(width, height, width, PixelFormat.Format8bppIndexed, p);
            bmp.Save("f:\a.bmp");
        }
Пример #3
0
 public void Initialize(HImage image, HTuple modelRow, HTuple modelColumn, HTuple modelAngle)
 {
     ho_Image = image;
     hv_AllModelRow = new HTuple(modelRow);
     hv_AllModelColumn = new HTuple(modelColumn);
     hv_AllModelAngle = new HTuple(modelAngle);
 }
        private void Init()
        {
            String fileName = "patras";
            HImage image;

            try
            {
                image   = new HImage(fileName);
            }
            catch(HOperatorException)
            {
                MessageBox.Show("Problem occured while reading file!",
                                "SmartWindow1",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Information);
                return;
            }

            hWndControl.addIconicVar(image);
            hWndControl.repaint();

            hWndControl.setGUICompRangeX( new int[]{ XTrackBar.Minimum,
                       							     XTrackBar.Maximum},
                                                     XTrackBar.Value );
            hWndControl.setGUICompRangeY( new int[]{ YTrackBar.Minimum,
                       							     YTrackBar.Maximum},
                                                     YTrackBar.Maximum-YTrackBar.Value);
        }
Пример #5
0
        public MeasureResult Action()
        {
            #region 輸出結果
            DistanceResult mResult = null;
            #endregion

            var fMidLine = new SDMS_FirstFingerMidLine();
            var image = new HImage(ho_Image);
            fMidLine.Initialize(image, hv_AllModelRow, hv_AllModelColumn, hv_AllModelAngle);
            var fMidLineModel = fMidLine.GetMidLine() as IMeasureGeoModel;

            var sMidLine = new SecondFingerMidLine();
            sMidLine.Initialize(image, hv_AllModelRow, hv_AllModelColumn, hv_AllModelAngle);
            var sMidLineModel = sMidLine.GetMidLine() as IMeasureGeoModel;

            var distance = DistanceHelper.LineToLine(fMidLineModel, sMidLineModel);

            mResult = new DistanceResult()
            {
                FirstRowBegin = fMidLineModel.Row1,
                FirstColBegin = fMidLineModel.Col1,
                FirstRowEnd = fMidLineModel.Row2,
                FirstColEnd = fMidLineModel.Col2,
                SecondRowBegin = sMidLineModel.Row1,
                SecondColBegin = sMidLineModel.Col1,
                SecondRowEnd = sMidLineModel.Row2,
                SecondColEnd = sMidLineModel.Col2,
                Angle = hv_AllModelAngle,
                Direction = LineDirection.Horizontal,
                Distance = distance,
            };
            return mResult;
        }
Пример #6
0
        public void SaveMacroPlanTest(string imagepath)
        {
            //assign
            var shapemodelpath = "filepath";
            var note = "note";
            var exportUnit = "mm";
            var image = new HImage(imagepath);

            var imageBinData = new Binary(ImageConventer.ConvertHalconImageToByteArray(image, false));

            var matchingParam = new MatchingParam();

            var matchingParamByteArray = ModelSerializer.DoSerialize(matchingParam);

            var matchingParamBinData = new Binary(matchingParamByteArray);

            BindingList<GeoDataGridViewModel> a = new BindingList<GeoDataGridViewModel>();
            a.Add(new GeoDataGridViewModel() { RecordID = "aaa" });

            var measureBinData = ModelSerializer.DoSerialize(a);
            //BindingList a;

            var ma = new MeasureAssistant();
            var maParam = ma.GetMeasureAssistantParam();
            var maParamBin = ModelSerializer.DoSerialize(maParam);

            LightChannel upper = new LightChannel() { Channel = "00", Intensity = 100, OnOff = LightSwitch.On };

            LightChannel bottom = new LightChannel() { Channel = "01", Intensity = 200, OnOff = LightSwitch.OFF };
            //act
            var success = SDMSRepo.SaveMacroPlan("Test", Guid.NewGuid().ToString(), shapemodelpath, note, imageBinData, exportUnit, matchingParamBinData, measureBinData, maParamBin, upper, bottom, new ShapeViewModel() { }, "system", "");

            //assert
            Assert.True(success);
        }
Пример #7
0
        // Procedures
        // Local procedures
        public static void Halcon_Train(string bitmap_train_init, double row1, double column1,
            double row2, double column2, double row, double column, double radius, string train_bitmaps,
            out IntPtr minimum, out int min_width, out int min_height, out IntPtr maximum)
        {
            HTuple ModelID = null;
            HTuple rstd = null, cstd = null;
            HTuple VmodleR = null,VmodleG = null,VmodleB = null;

            //GenerateFuctions.Normal_Train_Init();
            Bitmap bitmap = new Bitmap(bitmap_train_init);
            Rectangle rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
            BitmapData bmData = bitmap.LockBits(rect, ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format8bppIndexed);
            IntPtr pBitmap = bmData.Scan0;
            //pPixels = pBitmap;

            HImage hImage = new HImage();
            hImage.GenImage1("byte", bitmap.Width, bitmap.Height, pBitmap);

            bitmap.UnlockBits(bmData);
            bitmap.Dispose();
            HObject circle = null;
            HOperatorSet.GenEmptyObj(out circle);

            GenerateFuctions.Normal_Train_Init(hImage, out circle, row1, column1, row2, column2, row, column, radius,
                out ModelID, out  rstd, out cstd, out VmodleR, out VmodleG, out VmodleB);
            string[] bitmapFiles = Directory.GetFiles(train_bitmaps);

            foreach(string picture in bitmapFiles)
            {
                Bitmap pic = new Bitmap(picture);
                Rectangle rec = new Rectangle(0, 0, pic.Width, pic.Height);
                BitmapData picData = pic.LockBits(rec, ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format8bppIndexed);
                IntPtr pPic = picData.Scan0;

                HImage image = new HImage();
                image.GenImage1("byte", pic.Width, pic.Height, pPic);
                GenerateFuctions.Normal_Train(image, circle, ModelID, rstd, cstd, VmodleR, VmodleG, VmodleB);
            }
            HObject h_min = null, h_max = null;
            HOperatorSet.GenEmptyObj(out h_min);
            HOperatorSet.GenEmptyObj(out h_max);
            GenerateFuctions.Normal_Finish_Init(out h_min, out h_max, VmodleR, VmodleG, VmodleB);
            HImage min = h_min as HImage;
            HImage max = h_max as HImage;
            string type = string.Empty;
            int width = 0, height = 0;
            minimum = min.GetImagePointer1(out type, out min_width, out min_height);
            maximum = max.GetImagePointer1(out type, out width, out height);
        }
        public void TestMergeTailImage(string sImagePath, string tImagePath, double expectedWidth, double expectedHeight)
        {
            //assign
            var sImage = new HImage(sImagePath);
            var tImage = new HImage(tImagePath);

            //act
            var mergedImage = ImageAssociate.MergeTailImage(sImage, tImage, MergeDirection.Vertical);

            //assert
            HTuple width, height;
            mergedImage.GetImageSize(out width, out height);
            Assert.Equal(expectedWidth, width.D);
            Assert.Equal(expectedHeight, height.D);
        }
Пример #9
0
        public override HMessage ActorTask(HMessage obj)
        {
            if (obj != null)
            {
                obj.Dispose();
            }
            HMessage msg = new HMessage();
            HImage   img = grabber.GrabImageAsync(-1);

            msg.SetMessageObj(img, "image");
            if (SlowMotion == true)
            {
                HOperatorSet.WaitSeconds(0.2);
            }
            return(msg);
        }
        public void Close()
        {
            if (resultXLDCont != null && resultXLDCont.IsInitialized())
            {
                resultXLDCont.Dispose();
            }
            resultXLDCont = null;

            refImage         = null;
            createShapeModel = null;
            if (SearchRegion != null && SearchRegion.IsInitialized())
            {
                SearchRegion.Dispose();
            }
            SearchRegion = null;
        }
Пример #11
0
 /// <summary>
 /// 設置picturebox圖片
 /// </summary>
 /// <param name="bmp"></param>
 public void ShowHimage(HImage himage)
 {
     try
     {
         HObject hoimage = himage;
         CurrentImg = new HImage(hoimage);
         mView.addIconicVar(himage);
         resetWindow(himage);
         repaint(mHoDisplay, himage);
         if (m_eveShowHimage != null)
         {
             m_eveShowHimage(himage);
         }
     }
     catch { }
 }
Пример #12
0
        public HImage Process(HImage image)
        {
            var enhancedImage = image.EnhanceEdgeArea4(
                MeanMaskWidth,
                MeanMaskHeight,
                FirstMinGray,
                FirstMaxGray,
                Order,
                EmpMaskWidth,
                EmpMaskHeight,
                EmpMaskFactor,
                LastMinGray,
                LastMaxGray);

            return(enhancedImage);
        }
Пример #13
0
        /// <summary>
        ///   Access the features which correspond to a character.
        ///   Instance represents: ID of the desired OCR-classifier.
        /// </summary>
        /// <param name="character">Characters to be trained.</param>
        /// <returns>Feature vector.</returns>
        public HTuple OcrGetFeatures(HImage character)
        {
            IntPtr proc = HalconAPI.PreCall(727);

            this.Store(proc, 0);
            HalconAPI.Store(proc, 1, (HObjectBase)character);
            HalconAPI.InitOCT(proc, 0);
            int    err = HalconAPI.CallProcedure(proc);
            HTuple tuple;
            int    procResult = HTuple.LoadNew(proc, 0, HTupleType.DOUBLE, err, out tuple);

            HalconAPI.PostCall(proc, procResult);
            GC.KeepAlive((object)this);
            GC.KeepAlive((object)character);
            return(tuple);
        }
        /// <summary>
        /// Compute the model image and the model contour for the applied ROI.
        /// </summary>
        public void setModelROI(HRegion roi)
        {
            mROIModel        = roi;
            PyramidROIs      = null;
            createNewModelID = true;

            if (mROIModel == null)
            {
                mImage = null;
                return;
            }

            mImage = oImage.ReduceDomain(mROIModel);

            deterimineParamsAndInspectShapeModel();
        }
Пример #15
0
        /// <summary>
        ///   Classify a byte image using a look-up table.
        ///   Instance represents: Handle of the LUT classifier.
        /// </summary>
        /// <param name="image">Input image.</param>
        /// <returns>Segmented classes.</returns>
        public HRegion ClassifyImageClassLut(HImage image)
        {
            IntPtr proc = HalconAPI.PreCall(428);

            this.Store(proc, 0);
            HalconAPI.Store(proc, 1, (HObjectBase)image);
            HalconAPI.InitOCT(proc, 1);
            int     err = HalconAPI.CallProcedure(proc);
            HRegion hregion;
            int     procResult = HRegion.LoadNew(proc, 1, err, out hregion);

            HalconAPI.PostCall(proc, procResult);
            GC.KeepAlive((object)this);
            GC.KeepAlive((object)image);
            return(hregion);
        }
        public static HRegion GetRegionByGrayAndArea(this HImage image,
                                                     int medianRadius,
                                                     int empWidth, int empHeight, double empFactor,
                                                     int thresholdMinGray, int thresholdMaxGray,
                                                     int areaMin, int areaMax,
                                                     double closingRadius, double dilationRadius)
        {
            HObject foundRegionObject;

            HDevelopExport.Singletone.GetRegionByGrayAndArea(image, out foundRegionObject, medianRadius,
                                                             empWidth, empHeight, empFactor, thresholdMinGray, thresholdMaxGray, areaMin,
                                                             areaMax,
                                                             closingRadius, dilationRadius);

            return(new HRegion(foundRegionObject));
        }
Пример #17
0
        public static IList <SurfaceResult> SearchSurfaces(this ISurfaceInspector inspector,
                                                           HImage image, IList <SurfaceDefinition> definitions)
        {
            var csrs = new SurfaceResultCollection();

            int index = 0;

            foreach (var definition in definitions)
            {
                var csr = inspector.SearchSurface(image, definition);
                csr.Index = index;
                csrs.Add(csr);
                index++;
            }
            return(csrs);
        }
Пример #18
0
        public static HImage Calibrate(this HImage orignalHImage,
                                       string cameraParams,
                                       string cameraPose,
                                       Interpolation interpolation)
        {
            HObject hCalibImage;
            HTuple  lengthPerPixelX, lengthPerPixelY;

            HDevelopExport.Singletone.Calibrate(orignalHImage, out hCalibImage, cameraParams, cameraPose,
                                                interpolation.ToHalconString(),
                                                out lengthPerPixelX, out lengthPerPixelY);

            var hi = new HImage(hCalibImage);

            return(hi);
        }
Пример #19
0
        public static IList <RegionDefectResult> SearchDefects(this IDefectInspector inspector,
                                                               HImage image, IList <DefectDefinition> definitions,
                                                               IList <SurfaceResult> surfaceResults)
        {
            var csrs = new List <RegionDefectResult>();

//            int index = 0;
            foreach (var definition in definitions)
            {
                var csr = inspector.SearchDefects(image, definition, surfaceResults);
//                csr.Index = index;
                csrs.AddRange(csr);
//                index++;
            }
            return(csrs);
        }
Пример #20
0
        /// <summary>
        /// Writes the new image to graphic window
        /// </summary>
        public void UpdateImage(object sender, HImage newimage)
        {
            // display the new received image
            // lock with act, because the grabbing thread
            // can overwrite the image
            lock (someEventLock)
            {
                HImage image = newimage;
                hDisplayControl1.Image = image;
            }

            if (hDisplayControl1 != null)
            {
                hDisplayControl1.Invalidate();
            }
        }
Пример #21
0
        public HImage Process(HImage image)
        {
            var domain       = image.GetDomain();
            var domainWidth  = domain.GetWidth();
            var domainHeight = domain.GetHeight();

            var maskWidth  = MaskWidth == 0 ? domainWidth : MaskWidth;
            var maskHeight = MaskHeight == 0 ? domainHeight : MaskHeight;

//            var swMeanImage = new NotifyStopwatch("MeanFilter.MeanImage");
            HImage enhancedImage = image.MeanImage(maskWidth, maskHeight);

//            swMeanImage.Dispose();

            return(enhancedImage);
        }
Пример #22
0
        /// <summary>
        ///   Extract a gray value profile perpendicular to a rectangle or annular arc.
        ///   Instance represents: Measure object handle.
        /// </summary>
        /// <param name="image">Input image.</param>
        /// <returns>Gray value profile.</returns>
        public HTuple MeasureProjection(HImage image)
        {
            IntPtr proc = HalconAPI.PreCall(828);

            this.Store(proc, 0);
            HalconAPI.Store(proc, 1, (HObjectBase)image);
            HalconAPI.InitOCT(proc, 0);
            int    err = HalconAPI.CallProcedure(proc);
            HTuple tuple;
            int    procResult = HTuple.LoadNew(proc, 0, HTupleType.DOUBLE, err, out tuple);

            HalconAPI.PostCall(proc, procResult);
            GC.KeepAlive((object)this);
            GC.KeepAlive((object)image);
            return(tuple);
        }
Пример #23
0
        public static HImage ToHImage(this BitmapSource bitmapSource)
        {
            var stride = bitmapSource.PixelWidth;

            int    bufferSize = stride * bitmapSource.PixelHeight;
            IntPtr bufferPtr  = Marshal.AllocHGlobal(bufferSize);

            bitmapSource.CopyPixels(Int32Rect.Empty, bufferPtr, bufferSize, bitmapSource.PixelWidth);


            var hImage = new HImage("byte", bitmapSource.PixelWidth, bitmapSource.PixelHeight, bufferPtr);

            Marshal.FreeHGlobal(bufferPtr);

            return(hImage);
        }
Пример #24
0
        /// <summary>
        ///   Reconstruct surface from calibrated multi-view stereo images.
        ///   Instance represents: Handle of the stereo model.
        /// </summary>
        /// <param name="images">An image array acquired by the camera setup associated with the stereo model.</param>
        /// <returns>Handle to the resulting surface.</returns>
        public HObjectModel3D ReconstructSurfaceStereo(HImage images)
        {
            IntPtr proc = HalconAPI.PreCall(521);

            this.Store(proc, 0);
            HalconAPI.Store(proc, 1, (HObjectBase)images);
            HalconAPI.InitOCT(proc, 0);
            int            err = HalconAPI.CallProcedure(proc);
            HObjectModel3D hobjectModel3D;
            int            procResult = HObjectModel3D.LoadNew(proc, 0, err, out hobjectModel3D);

            HalconAPI.PostCall(proc, procResult);
            GC.KeepAlive((object)this);
            GC.KeepAlive((object)images);
            return(hobjectModel3D);
        }
        public void TestMergeTailImage(string sImagePath, string tImagePath, double expectedWidth, double expectedHeight)
        {
            //assign
            var sImage = new HImage(sImagePath);
            var tImage = new HImage(tImagePath);

            //act
            var mergedImage = ImageAssociate.MergeTailImage(sImage, tImage, MergeDirection.Vertical);

            //assert
            HTuple width, height;

            mergedImage.GetImageSize(out width, out height);
            Assert.Equal(expectedWidth, width.D);
            Assert.Equal(expectedHeight, height.D);
        }
Пример #26
0
        public void GetImage1()
        {
            //cam1ProcedureCall.Execute();
            Image_1?.Dispose();
            Image_1 = Framegrabber1.GrabImage(); //拍照
            Image_2?.Dispose();
            Image_2 = Framegrabber2.GrabImage(); //拍照
            Image_3?.Dispose();
            Image_3 = Framegrabber3.GrabImage(); //拍照

            Image1?.Dispose();
            Image1 = Image_1.ConcatObj(Image_2).ConcatObj(Image_3).TileImages(3, "horizontal");

            GlobalVar.hWndCtrl.addIconicVar(Image1);
            GlobalVar.hWndCtrl.repaint();
        }
Пример #27
0
        private static void GocatorDevice_OnDataReceivedEvent(object sender, object e)
        {
            List <ushort[]> data = (List <ushort[]>)e;
            var             obj  = new Object();

            //Image<Gray, UInt16> image = EmguToWpfImage.ZValuesToDepthPng(data[0], gocatorDevice.mContext);
            Parallel.For(0, data.Count, (index) => {
                lock (obj)
                {
                    HImage image = HalconToWpf.ZValueToDepthImage(data[index], gocatorDevice.mContextTop);
                    image.WriteImage("png", 0, $@"C:\ImageData\Bottom\bottom_{index}.png");
                }
            });

            Console.WriteLine("Done");
        }
Пример #28
0
        /// <summary>
        ///   Train a classificator using a multi-channel image.
        ///   Instance represents: Handle of the classifier.
        /// </summary>
        /// <param name="foreground">Foreground pixels to be trained.</param>
        /// <param name="background">Background pixels to be trained (rejection class).</param>
        /// <param name="multiChannelImage">Multi-channel training image.</param>
        public void LearnNdimBox(HRegion foreground, HRegion background, HImage multiChannelImage)
        {
            IntPtr proc = HalconAPI.PreCall(438);

            this.Store(proc, 0);
            HalconAPI.Store(proc, 1, (HObjectBase)foreground);
            HalconAPI.Store(proc, 2, (HObjectBase)background);
            HalconAPI.Store(proc, 3, (HObjectBase)multiChannelImage);
            int procResult = HalconAPI.CallProcedure(proc);

            HalconAPI.PostCall(proc, procResult);
            GC.KeepAlive((object)this);
            GC.KeepAlive((object)foreground);
            GC.KeepAlive((object)background);
            GC.KeepAlive((object)multiChannelImage);
        }
Пример #29
0
 private void btn_GrabImageForTest_Click(object sender, EventArgs e)
 {
     if (testImage != null && testImage.IsInitialized())
     {
         testImage.Dispose();
     }
     testImage = tool.GetImage();
     if (testImage == null || !testImage.IsInitialized())
     {
         MessageBox.Show("获取图像失败", "请检查相机或重新获取图像", MessageBoxButtons.OK, MessageBoxIcon.Warning);
         return;
     }
     mView.ClearList();
     mView.AddIconicVar(testImage);
     mView.Repaint();
 }
Пример #30
0
        public Line TryFindLine(string name, HImage image, FindLineFeeding feeding, bool recordGraphics = true)
        {
            Line line = new Line();

            try
            {
                line = FindLine(image, feeding, recordGraphics);
            }
            catch (Exception e)
            {
                Debugger.Break();
                PromptUserInvoke($"Line {name} not found! {Environment.NewLine} {e.Message}");
            }

            return(line);
        }
Пример #31
0
        public HRegion Extract(HImage image)
        {
            var foundRegion = image.GetRegionByGrayAndArea(
                MedianRadius,
                EmpWidth,
                EmpHeight,
                EmpFactor,
                ThresholdMinGray,
                ThresholdMaxGray,
                AreaMin,
                AreaMax,
                ClosingRadius,
                DilationRadius);

            return(foundRegion);
        }
Пример #32
0
        void btnSave_Click(object sender, EventArgs e)
        {
            //hWindowControl2.ImagePart = new Rectangle((int)roi.Row1, (int)roi.Col1, (int)roi.Row2,(int) roi.Col2);
            // hWindowControl2.HalconWindow.DispObj(img);
            //roi.CreateModel(img, hWindowControl2.HalconWindow);
            image = HobjectToHimage(img);

            //HImage image=ig.ho_img as HImage;
            if (match == null)
            {
                match = new Match();
            }
            hWindowControl2.HalconWindow.ClearWindow();
            hWindowControl3.HalconWindow.ClearWindow();
            match.CreateModel(image, hWindowControl2.HalconWindow, hWindowControl3.HalconWindow, roi.Row1, roi.Col1, roi.Row2, roi.Col2, roi.RowMark, roi.ColMark);
        }
Пример #33
0
        /// <summary>
        ///   Classify pixels using hyper-cuboids.
        ///   Instance represents: Handle of the classifier.
        /// </summary>
        /// <param name="multiChannelImage">Multi channel input image.</param>
        /// <returns>Classification result.</returns>
        public HRegion ClassNdimBox(HImage multiChannelImage)
        {
            IntPtr proc = HalconAPI.PreCall(439);

            this.Store(proc, 0);
            HalconAPI.Store(proc, 1, (HObjectBase)multiChannelImage);
            HalconAPI.InitOCT(proc, 1);
            int     err = HalconAPI.CallProcedure(proc);
            HRegion hregion;
            int     procResult = HRegion.LoadNew(proc, 1, err, out hregion);

            HalconAPI.PostCall(proc, procResult);
            GC.KeepAlive((object)this);
            GC.KeepAlive((object)multiChannelImage);
            return(hregion);
        }
Пример #34
0
        /// <summary>
        ///   Train components and relations for the component-based matching.
        ///   Modified instance represents: Handle of the training result.
        /// </summary>
        /// <param name="modelImage">Input image from which the shape models of the initial components should be created.</param>
        /// <param name="initialComponents">Contour regions or enclosing regions of the initial components.</param>
        /// <param name="trainingImages">Training images that are used for training the model components.</param>
        /// <param name="contrastLow">Lower hysteresis threshold for the contrast of the initial components in the image. Default: "auto"</param>
        /// <param name="contrastHigh">Upper hysteresis threshold for the contrast of the initial components in the image. Default: "auto"</param>
        /// <param name="minSize">Minimum size of connected contour regions. Default: "auto"</param>
        /// <param name="minScore">Minimum score of the instances of the initial components to be found. Default: 0.5</param>
        /// <param name="searchRowTol">Search tolerance in row direction. Default: -1</param>
        /// <param name="searchColumnTol">Search tolerance in column direction. Default: -1</param>
        /// <param name="searchAngleTol">Angle search tolerance. Default: -1</param>
        /// <param name="trainingEmphasis">Decision whether the training emphasis should lie on a fast computation or on a high robustness. Default: "speed"</param>
        /// <param name="ambiguityCriterion">Criterion for solving ambiguous matches of the initial components in the training images. Default: "rigidity"</param>
        /// <param name="maxContourOverlap">Maximum contour overlap of the found initial components in a training image. Default: 0.2</param>
        /// <param name="clusterThreshold">Threshold for clustering the initial components. Default: 0.5</param>
        /// <returns>Contour regions of rigid model components.</returns>
        public HRegion TrainModelComponents(
            HImage modelImage,
            HRegion initialComponents,
            HImage trainingImages,
            int contrastLow,
            int contrastHigh,
            int minSize,
            double minScore,
            int searchRowTol,
            int searchColumnTol,
            double searchAngleTol,
            string trainingEmphasis,
            string ambiguityCriterion,
            double maxContourOverlap,
            double clusterThreshold)
        {
            this.Dispose();
            IntPtr proc = HalconAPI.PreCall(1017);

            HalconAPI.Store(proc, 1, (HObjectBase)modelImage);
            HalconAPI.Store(proc, 2, (HObjectBase)initialComponents);
            HalconAPI.Store(proc, 3, (HObjectBase)trainingImages);
            HalconAPI.StoreI(proc, 0, contrastLow);
            HalconAPI.StoreI(proc, 1, contrastHigh);
            HalconAPI.StoreI(proc, 2, minSize);
            HalconAPI.StoreD(proc, 3, minScore);
            HalconAPI.StoreI(proc, 4, searchRowTol);
            HalconAPI.StoreI(proc, 5, searchColumnTol);
            HalconAPI.StoreD(proc, 6, searchAngleTol);
            HalconAPI.StoreS(proc, 7, trainingEmphasis);
            HalconAPI.StoreS(proc, 8, ambiguityCriterion);
            HalconAPI.StoreD(proc, 9, maxContourOverlap);
            HalconAPI.StoreD(proc, 10, clusterThreshold);
            HalconAPI.InitOCT(proc, 0);
            HalconAPI.InitOCT(proc, 1);
            int     err1 = HalconAPI.CallProcedure(proc);
            int     err2 = this.Load(proc, 0, err1);
            HRegion hregion;
            int     procResult = HRegion.LoadNew(proc, 1, err2, out hregion);

            HalconAPI.PostCall(proc, procResult);
            GC.KeepAlive((object)this);
            GC.KeepAlive((object)modelImage);
            GC.KeepAlive((object)initialComponents);
            GC.KeepAlive((object)trainingImages);
            return(hregion);
        }
Пример #35
0
        private void SaveImage(IntPtr pData, ref MyCamera.MV_FRAME_OUT_INFO pFrameInfo, IntPtr pUser)
        {
            try
            {
                if (ignoreImage)
                {
                    return;
                }

                //HTuple startTime;
                if (Command != Command.Grab)
                {
                    HOperatorSet.CountSeconds(out startTime);
                }


                hPylonImage = new HImage();
                if (pFrameInfo.enPixelType == MyCamera.MvGvspPixelType.PixelType_Gvsp_Mono8)
                {
                    hPylonImage.GenImage1("byte", pFrameInfo.nWidth, pFrameInfo.nHeight, pData);
                }
                else if (pFrameInfo.enPixelType == MyCamera.MvGvspPixelType.PixelType_Gvsp_RGB8_Packed)
                {
                    hPylonImage.GenImageInterleaved(pData,
                                                    "rgb",
                                                    pFrameInfo.nWidth, pFrameInfo.nHeight,
                                                    -1, "byte",
                                                    pFrameInfo.nWidth, pFrameInfo.nHeight,
                                                    0, 0, -1, 0);
                }
                else
                {
                    Util.Notify(string.Format("相机{0}编码格式不正确,当前格式{1}", cameraIndex, pFrameInfo.enPixelType));
                }
                TrigerImageEvent();
            }
            catch (System.ArgumentException ex)
            {
                Util.WriteLog(this.GetType(), ex);
                Util.Notify(string.Format("相机{0}图像数据包丢失", cameraIndex));
            }
            catch (Exception ex)
            {
                Util.WriteLog(this.GetType(), ex);
                Util.Notify(string.Format("相机{0}图像数据返回出现异常", cameraIndex));
            }
        }
Пример #36
0
        private void ManageErrorImage(ArrayList iconicVarList, ElaborateResult result)
        {
            if (result.Success == false && Properties.Settings.Default.NumeroErrori > 0)
            {
                lock (lastErrorsLock)
                {
                    if (LastErrors.Count == Properties.Settings.Default.NumeroErrori)
                    {
                        LastErrors[Properties.Settings.Default.NumeroErrori - 1].Dispose();
                        LastErrors.RemoveAt(Properties.Settings.Default.NumeroErrori - 1);
                    }
                    Utilities.CacheErrorObject ceo = new Utilities.CacheErrorObject(iconicVarList, result);

                    if (Properties.Settings.Default.ErroriSuDisco)
                    {
                        //WriteErrorImageToDisk(ceo);
                        if (ceo != null && ceo.IconicVar != null && ceo.IconicVar.Count > 0 && ((Utilities.ObjectToDisplay)ceo.IconicVar[0]).IconicVar is HImage)
                        {
                            HImage img = (((Utilities.ObjectToDisplay)ceo.IconicVar[0]).IconicVar as HImage).CopyImage();

                            Action actionSave = () =>
                            {
                                try
                                {
                                    WriteErrorImageToDisk(img);
                                }
                                catch (Exception ex)
                                {
                                    ExceptionManager.AddException(ex);
                                }
                            };

                            if (this.taskWriteErrorImageToDisk == null)
                            {
                                this.taskWriteErrorImageToDisk = Task.Run(actionSave);
                            }
                            else
                            {
                                this.taskWriteErrorImageToDisk = this.taskWriteErrorImageToDisk.ContinueWith(k => actionSave());
                            }
                        }
                    }

                    LastErrors.Insert(0, ceo);
                }
            }
        }
        public bool LoadImage(Bitmap bitmap)
        {
            if (null == bitmap)
            {
                return(false);
            }

            try
            {
                _hSourceImage?.Dispose();
                Rectangle  rectangle  = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
                BitmapData bitmapData = bitmap.LockBits(rectangle, ImageLockMode.ReadOnly, bitmap.PixelFormat);

                switch (bitmap.PixelFormat)
                {
                case PixelFormat.Format8bppIndexed:
                    _hSourceImage = new HImage("byte", bitmap.Width, bitmap.Height, bitmapData.Scan0);
                    bitmap.UnlockBits(bitmapData);
                    break;

                case PixelFormat.Format24bppRgb:
                    _hSourceImage = new HImage();
                    _hSourceImage.GenImageInterleaved(bitmapData.Scan0, "rgb", bitmap.Width, bitmap.Height, -1,
                                                      "byte", 0, 0, 0, 0, -1, 0);
                    bitmap.UnlockBits(bitmapData);
                    break;

                default:
                    return(false);
                }

                _hWndCtrl.addIconicVar(_hSourceImage);

                //double scaleFactor;
                //Get1stScaleFactor(out scaleFactor);
                //_hWndCtrl.zoomImage(scaleFactor);
                _hWndCtrl.repaint();
                Focus();
            }
            catch (Exception exception)
            {
                _logger.Error("LoadImage error" + "\r\n   " + exception);
                return(false);
            }

            return(true);
        }
        public void SaveMacroPlanTest(string imagepath)
        {
            //assign
            var shapemodelpath = "filepath";
            var note           = "note";
            var exportUnit     = "mm";
            var image          = new HImage(imagepath);

            var imageBinData = new Binary(ImageConventer.ConvertHalconImageToByteArray(image, false));

            var matchingParam = new MatchingParam();

            var matchingParamByteArray = ModelSerializer.DoSerialize(matchingParam);

            var matchingParamBinData = new Binary(matchingParamByteArray);

            BindingList <GeoDataGridViewModel> a = new BindingList <GeoDataGridViewModel>();

            a.Add(new GeoDataGridViewModel()
            {
                RecordID = "aaa"
            });

            var measureBinData = ModelSerializer.DoSerialize(a);
            //BindingList a;

            var ma         = new MeasureAssistant();
            var maParam    = ma.GetMeasureAssistantParam();
            var maParamBin = ModelSerializer.DoSerialize(maParam);

            LightChannel upper = new LightChannel()
            {
                Channel = "00", Intensity = 100, OnOff = LightSwitch.On
            };

            LightChannel bottom = new LightChannel()
            {
                Channel = "01", Intensity = 200, OnOff = LightSwitch.OFF
            };
            //act
            var success = SDMSRepo.SaveMacroPlan("Test", Guid.NewGuid().ToString(), shapemodelpath, note, imageBinData, exportUnit, matchingParamBinData, measureBinData, maParamBin, upper, bottom, new ShapeViewModel()
            {
            }, "system", "");

            //assert
            Assert.True(success);
        }
Пример #39
0
 /// <summary>
 /// 二進位資料轉換為 HImage
 /// </summary>
 /// <param name="data"></param>
 /// <returns></returns>
 public static HImage BinaryToHImage(Binary data)
 {
     HImage img = null;
     try
     {
         var bmp = BinaryToImage(data);
         var fpath = ConfigurationHelper.GetTmpFilepath();
         bmp.Save(fpath);
         img = new HImage(fpath);
         File.Delete(fpath);
     }
     catch (Exception ex)
     {
         Hanbo.Log.LogManager.Error(ex);
     }
     return img;
 }
        /// <summary>
        /// 取得校正片校正資訊
        /// </summary>
        /// <param name="calibrationPlateDescriptionFile">校正片描述檔案</param>
        /// <param name="image">校正片影像</param>
        /// <param name="plateParam">校正片擷取參數</param>
        /// <param name="startCamerParam">鏡頭參數</param>
        /// <returns>校正片校正資訊模型</returns>
        public CalibrationPlateMarkViewModel GetCalibrationPlateMarkViewModel(string calibrationPlateDescriptionFile
            , HImage image
            , CalibrationPlateParam plateParam
            , HTuple startCamerParam)
        {
            var model = new CalibrationPlateMarkViewModel();
            try
            {
                //找到校正板的區域
                var calibRegion = image.FindCaltab(calibrationPlateDescriptionFile
                                , plateParam.GaussianFilterSize
                                , plateParam.MarkThreshold
                                , plateParam.MinMarkDiam);

                //取得校正片 Mark 的位置和角度
                HTuple markCenterCols;
                HPose estimatedStartPose;
                HTuple markCenterRows = image.FindMarksAndPose(calibRegion
                                                        , calibrationPlateDescriptionFile
                                                        , startCamerParam
                                                        , plateParam.StartThresh
                                                        , plateParam.DeltaThresh
                                                        , plateParam.MinThresh
                                                        , plateParam.Alpha
                                                        , plateParam.MinContourLength
                                                        , plateParam.MaxDiameterMarks
                                                        , out markCenterCols
                                                        , out estimatedStartPose);

                model.MarkCenterRows = new HTuple(markCenterRows);
                model.MarkCenterCols = new HTuple(markCenterCols);
                model.EstimatedMarkPose = new HTuple(estimatedStartPose);
                model.Valid = true;
                model.ErrorMessage = String.Empty;
            }
            catch (HOperatorException ex)
            {
                model.ErrorMessage = ex.Message;
                model.Valid = false;
            }
            return model;
        }
Пример #41
0
        /// <summary>
        /// 把 TailImage 與 Source Image 作合併
        /// </summary>
        /// <param name="sourceImage">原始影像</param>
        /// <param name="tailImage">要接在原始影像後的影像</param>
        /// <param name="direction">合併方向</param>
        /// <returns></returns>
        public static HImage MergeTailImage(HImage sourceImage, HImage tailImage, MergeDirection direction)
        {
            HImage resultImage;
            HObject mergedImage, images;
            HOperatorSet.GenEmptyObj(out mergedImage);
            HOperatorSet.GenEmptyObj(out images);

            try
            {
                HTuple sWidth, sHeight, tWidth, tHeight;
                sourceImage.GetImageSize(out sWidth, out sHeight);
                tailImage.GetImageSize(out tWidth, out tHeight);
                HOperatorSet.ConcatObj(sourceImage, tailImage, out images);

                //產生參數
                var param = genMergeParams(direction, sWidth, sHeight, tWidth, tHeight);

                //合併
                HOperatorSet.TileImagesOffset(images, out mergedImage
                    , param.offsetRow, param.offsetCol
                    , param.row1, param.col1, param.row2, param.col2
                    , param.width, param.height);

                resultImage = mergedImage as HImage;
                if (resultImage == null)
                {
                    var fpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), Guid.NewGuid().ToString());
                    HOperatorSet.WriteImage(mergedImage, "tiff", 0, fpath);
                    var fpathWithExtension = fpath + ".tif";
                    resultImage = new HImage(fpath);
                    if (File.Exists(fpathWithExtension))
                        File.Delete(fpathWithExtension);
                }
            }
            catch (HOperatorException ex)
            {
                logger.Error(ex);
                resultImage = null;
            }
            return resultImage;
        }
        /// <summary> 
        /// Defines the initial settings for the window 
        /// control. In the very beginning, the window control needs 
        /// to know the view mode of the application form to perform 
        /// the right behavior for incoming mouse events on the 
        /// HALCON window.
        /// </summary>
        private void InteractiveForm_Load(object sender, System.EventArgs e)
        {
            String fileName = "patras";
            HImage image;

            viewController = new HWndCtrl(viewPort);
            roiController  = new ROIController();
            viewController.useROIController(roiController);
            viewController.setViewState(HWndCtrl.MODE_VIEW_NONE);

            try
            {
                image   = new HImage(fileName);
            }
            catch(HOperatorException)
            {
                MessageBox.Show("Problem occured while reading file!",
                    "InteractROIForm",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Information);
                return;
            }

            viewController.addIconicVar(image);
            viewController.repaint();
        }
 private void _bgworker_DoWork(object sender, DoWorkEventArgs e)
 {
     var worker = sender as BackgroundWorker;
     try
     {
         if (GrabImageStart != null) GrabImageStart(sender, e);
         var i = 0;
         while (true)
         {
             if (worker.CancellationPending)
             {
                 e.Cancel = true;
                 break;
             }
             else
             {
                 _imageProvider.GrabImage();
                 var himage = new HImage(_imageProvider.Image);
                 worker.ReportProgress(i++, himage);
             }
         }
     }
     catch (Exception ex)
     {
         Hanbo.Log.LogManager.Error(ex);
         if (GrabImageException != null)
         {
             GrabImageException(ex);
         }
     }
 }
        /// <summary>
        /// Generates the iconic objects of the calibration results 
        /// for display
        /// </summary>
        public void UpdateResultVisualization()
        {
            HTuple refPose, correctedPose;
            double axisLen;
            HObject obj;

            if (!mCalibValid)
                return;

            mSimulatedImage.Dispose();

            mReferenceImage = ((CalibImage)CalibData[mReferenceIndex]).GetImage();
            refPose = getCalibratedPose(false);

            HOperatorSet.SimCaltab(out obj, new HTuple(mDescrFileName),
                                   mCameraParams, refPose, new HTuple(128),
                                   new HTuple(224), new HTuple(80), new HTuple(1));

            mSimulatedImage = new HImage(obj);

            correctedPose = getCalibratedPose(true);
            axisLen = ((CalibImage)CalibData[mReferenceIndex]).GetEstimatedPlateSize();

            procedure.get_3d_coord_system(mReferenceImage, out mReferenceWCS, mCameraParams,
                                          correctedPose, new HTuple(axisLen / 2));

            NotifyCalibObserver(CalibrationAssistant.UPDATE_CALIBRATION_RESULTS);
        }
        /* Constructor, in which all calibration parameters
         * and  auxiliary variables, flags and lists are initilized */
        public CalibrationAssistant()
        {
            //
            _imgQualityExaminer = new BackgroundWorker() { WorkerReportsProgress = true, WorkerSupportsCancellation = true };
            _imgQualityExaminer.DoWork += _imgQualityExaminer_DoWork;
            _imgQualityExaminer.ProgressChanged += _imgQualityExaminer_ProgressChanged;
            _imgQualityExaminer.RunWorkerCompleted += _imgQualityExaminer_RunWorkerCompleted;

            _addImagTasks = new List<string>();

            _imageTaskTimer = new System.Windows.Forms.Timer();
            _imageTaskTimer.Tick += _imageTaskTimer_Tick;

            CalibData = new ArrayList(15);
            mReferenceIndex = -1;
            mDescrFileName = "caltab_30mm.descr";
            mCalibValid = false;
            mCanCalib = true;
            mAtImgCoord = false;

            mReferenceImage = new HImage();
            mSimulatedImage = new HImage();

            mFilterSize = resetFilterSize;
            mMarkThresh = resetMarkThresh;
            mMinMarkDiam = resetMinMarkDiam;
            mInitThresh = resetInitThresh;
            mThreshDecr = resetThreshDecr;
            mMinThresh = resetMinThresh;
            mSmoothing = resetSmoothing;
            mMinContLength = resetMinContL;
            mMaxMarkDiam = resetMaxMarkDiam;

            mWarnLevel = 70;
            mImageTests = QUALITY_ISSUE_TEST_ALL;
            mSequenceTests = QUALITY_ISSUE_TEST_ALL;
            mSeqQualityList = new ArrayList(15);
            procedure = new QualityProcedures();

            mThickness = 630;       // micrometer
            mCameraType = CAMERA_TYP_AREA_SCAN_DIV;
            mCellWidth = 8300.0;    // nm
            mCellHeight = 8300.0;    // nm
            mFocalLength = 8000;      // micrometer
            isTelecentric = false;
            mKappa = 0.0;
            mK1 = 0.0;
            mK2 = 0.0;
            mK3 = 0.0;
            mP1 = 0.0;
            mP2 = 0.0;
            mMotionVx = 0.0;
            mMotionVy = 500.0;
            mMotionVz = 0.0;

            NotifyCalibObserver = new CalibDelegate(dummy);
        }
        private void Init()
        {
            String fileName = "particle";

            try
            {
                image   = new HImage(fileName);
            }
            catch(HOperatorException)
            {
                MessageBox.Show("Problem occured while reading file!",
                                "GraphicsStack",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Information);
                return;
            }

               	locked   = false;
            procList = new Hashtable(10);

            IconiclistBox.Enabled = true;
            performIPTask();
            IconiclistBox.SelectedIndex = 1;
            viewControl.repaint();
        }
        //===========
        private void start(BackgroundWorker worker)
        {
            /* Issue an acquisition start command. Because the trigger mode is enabled, issuing the start command
                   itself will not trigger any image acquisitions. Issuing the start command simply prepares the camera.
                   Once the camera is prepared it will acquire one image for every trigger it receives. */
            /* Trigger the first image. */
            //Pylon.DeviceExecuteCommandFeature(hDev, "TriggerSoftware");

            nGrabs = 0;                           /* Counts the number of images grabbed. */
            //while (true)
            //{
            int bufferIndex;              /* Index of the buffer. */
            long chunkWidth = _PEGX; /* data retrieved from the chunk parser */
            long chunkHeight = _PEGY; /* data retrieved from the chunk parser */

            /* Wait for the next buffer to be filled. Wait up to 1000 ms. */
            notifyError("Grab waiting!");
            isReady = Pylon.WaitObjectWait(_hWait, _timeout);

            if (!isReady)
            {
                //notifyError("Grab timeout occurred");
                //worker.CancelAsync();
                return;//break;
            }

            /* Since the wait operation was successful, the result of at least one grab
               operation is available. Retrieve it. */
            isReady = Pylon.StreamGrabberRetrieveResult(_hGrabber, out _grabResult);
            if (!isReady)
            {
                /* Oops. No grab result available? We should never have reached this point.
                   Since the wait operation above returned without a timeout, a grab result
                   should be available. */
                //notifyError("Failed to retrieve a grab result.");
                return;//break;
            }

            nGrabs++;
            //fpath = Path.Combine(fdir, nGrabs.ToString(@"D2"));
            /* Trigger the next image. Since we passed more than one buffer to the stream grabber,
               the triggered image will be grabbed while the image processing is performed.  */
            //Pylon.DeviceExecuteCommandFeature(hDev, "TriggerSoftware");

            /* Get the buffer index from the context information. */
            bufferIndex = (int)_grabResult.Context;

            /* Check to see if the image was grabbed successfully. */
            if (_grabResult.Status == EPylonGrabStatus.Grabbed)
            {
                /*  The grab is successful.  */
                PylonBuffer<Byte> buffer;        /* Reference to the buffer attached to the grab result. */

                /* Get the buffer from the dictionary. Since we also got the buffer index,
                   we could alternatively use an array, e.g. buffers[bufferIndex]. */
                if (!_buffers.TryGetValue(_grabResult.hBuffer, out buffer))
                {
                    /* Oops. No buffer available? We should never have reached this point. Since all buffers are
                       in the dictionary. */
                    //notifyError("Failed to find the buffer associated with the handle returned in grab result.");
                    return;//break;
                }
                // notifyRunningMessage(String.Format("Grabbed frame {0} into buffer {1}.", nGrabs, bufferIndex));

                //Save Image
                // notifyRunningMessage("SAVE Image");
                IntPtr pointer = buffer.Pointer;
                try
                {
                    /**/
                    var myBuf = buffer.Array;
                    notifyRunningMessage(String.Format("W: {0} H: {1}  Length: {2}", chunkWidth, chunkHeight, myBuf.Length));
                    if (myBuf.Length >= chunkHeight * chunkWidth)
                    {
                        /* Perform the image processing. */
                        //getMinMax(buffer.Array, chunkWidth, chunkHeight, out min, out max);
                        //notifyRunningMessage(String.Format("Min. gray value  = {0}, Max. gray value = {1}", min, max));

                        var hImag = new HImage("byte", (int)chunkWidth, (int)chunkHeight, pointer);
                        worker.ReportProgress(nGrabs, new HImage(hImag));
                    }
                    //HOperatorSet.WriteImage(hImag, "png", 0, fpath);
                }
                catch (Exception ex)
                {
                    // Console.WriteLine("SAVE Image Error : " + ex.Message);
                }
                /* Before requeueing the buffer, you should detach it from the chunk parser. */
                Pylon.ChunkParserDetachBuffer(_hChunkParser);  /* Now the chunk data in the buffer is no longer accessible. */
            }
        /// <summary>
        /// Load an HALCON image from the file filename and
        /// delete the list of measure handles created for the
        /// previous image setup
        /// </summary>
        /// <param name="filename">Location of image file</param>
        /// <returns>Flag depicting success of the load process</returns>
        public bool setImage(string filename)
        {
            string tmp;

            RemoveAllMeasureObjects();
            exceptionText = "";
            try
            {
                mImage = new HImage(filename);
                mImage.GetImagePointer1(out tmp, out mWidth, out mHeight);
            }
            catch (HOperatorException e)
            {
                mImage = null;
                exceptionText = e.Message;
                NotifyMeasureObserver(MeasureAssistant.ERR_READING_FILE);
                return false;
            }
            return true;
        }
        /*********************************************************************
         * Open and Close Device
         *********************************************************************/
        /// <summary>
        /// Initialize the connection to the image acquisition interface and 
        /// initialization of its image acquisition parameters
        /// </summary>
        public void OpenDevice()
        {
            InitIA();
            img = null;
            imCounter = 0;
            grabThread = null;

            try
            {
                if (this.IAName != "File")
                {
                    OpenFrameGrabber();
                }
                else
                {
                    OpenOfflineIADevice();
                }

                // Initialize acqHandle
                acqHandle = new HTuple(frameGrabber.Handle);

            }
            catch (HOperatorException exp)
            {
                acqHandle = null;
                throw exp;
            }

            // try to start asynchronous grab
            try
            {
                frameGrabber.GrabImageStart(-1.0);
            }
            catch (HOperatorException exc)
            {
                // Catch the error, if the device doesn't support
                // asynchronous mode: H_ERR_FGASYNC
                if (exc.GetErrorCode() == 5320)
                {
                    asyncGrabbing = false;
                }
                else
                {
                    throw exc;
                }
            }
        }
Пример #50
0
        public void Initialize(HImage image, HTuple modelRow, HTuple modelColumn, HTuple modelAngle)
        {
            ho_Image = image;
            hv_AllModelRow = new HTuple(modelRow);
            hv_AllModelColumn = new HTuple(modelColumn);
            hv_AllModelAngle = new HTuple(modelAngle);

            cAssistant = new MeasureAssistant(new ROIController());
        }
 /// <summary>
 /// 
 /// </summary>
 private void viewPort_HInitWindow(object sender, EventArgs e)
 {
     hImage = null;
     regionOfInterest = new HRegion();
 }
Пример #52
0
        /// <summary>
        /// Read dimensions of the image to adjust own window settings
        /// </summary>
        /// <param name="image">HALCON image</param>
        private void setImagePart(HImage image)
        {
            string s;
              int w,h;

              image.GetImagePointer1(out s, out w, out h);
              setImagePart(0, 0, h, w);
        }
Пример #53
0
		private void noitfyGrabImage(HImage image)
		{
			if (On_GrabImageChanged != null)
			{
				On_GrabImageChanged(_bgworker, new GrabImageEventArgs() { ViewModel = image });
			}
		}
Пример #54
0
 private HImage getRegionImage(HRegion region)
 {
     HImage regionImage = null;
     if (mMeasAssist.ApplyCalibration && mMeasAssist.IsCalibrationValid)
     {
         regionImage = mMeasAssist.mImage.ChangeRadialDistortionImage(region, mMeasAssist.CameraIn, _cameraOut);
     }
     else
     {
         HObject imageReduced;
         HOperatorSet.GenEmptyObj(out imageReduced);
         HOperatorSet.ReduceDomain(mMeasAssist.mImage, region, out imageReduced);
         regionImage = new HImage(imageReduced);
     }
     return regionImage;
 }
        public void OpenDevice(HTuple acqHandle)
        {
            InitIA();
            img = null;
            imCounter = 0;
            grabThread = null;
            using (frameGrabber = new HFramegrabber(acqHandle[0].IP))
            {
                // Initialize acqHandle
                acqHandle = new HTuple(frameGrabber.Handle);
            }

            // try to start asynchronous grab
            try
            {
                frameGrabber.GrabImageStart(-1.0);
            }
            catch (HOperatorException exc)
            {
                // Catch the error, if the device doesn't support
                // asynchronous mode: H_ERR_FGASYNC
                if (exc.GetErrorCode() == 5320)
                {
                    asyncGrabbing = false;
                }
                else
                {
                    throw exc;
                }
            }
        }
        /// <summary>
        /// Sets the variable mImage to the HImage provided 
        /// </summary>
        /// <param name="img">HALCON image instance</param>
        public void setImage(HImage img)
        {
            string tmp;

            RemoveAllMeasureObjects();
            mImage = img;

            if (mImage != null)
                mImage.GetImagePointer1(out tmp, out mWidth, out mHeight);
        }
        /// <summary>
        /// The method grabs new image and sents an event, if the 
        /// image is grabbed.
        /// </summary>
        public void GrabImage()
        {
            //GrabOn = true;

              if ((GrabOn) && (frameGrabber != null))
              {
              HImage copimg = null;

              HOperatorSet.CountSeconds(out startGrabTime);
              try
              {
                  if (asyncGrabbing)
                      img = frameGrabber.GrabImageAsync(-1);
                  else
                      img = frameGrabber.GrabImage();
                  HOperatorSet.CountSeconds(out endGrabTime);
              }
              catch (HOperatorException exc)
              {
                  HOperatorSet.CountSeconds(out endGrabTime);
                  timeGrab = (endGrabTime.D - startGrabTime.D) * 1000.0;

                  // If failed grabbing of an image,
                  // If Time Out Exception occured,
                  // then the image acquisition is interrupted
                  if ((exc.GetErrorCode() == 5306) ||
                      (exc.GetErrorCode() == 5322))
                      StopGrabThread();

                  // If the connection to device is lost,then the image
                  // acquisition is interrupted
                  if (exc.GetErrorCode() == 5335)
                  {
                      StopGrabThread();
                      CloseDevice();
                  }
                  throw exc;
              }

              timeGrab = (endGrabTime.D - startGrabTime.D) * 1000.0;

              if (timeGrab > 0)
                  frameRate = 1000.0 / timeGrab;
              else
                  frameRate = 0.0;

              lock (locker)
              {
                  if (img != null)
                  {
                      copimg = img;
                      imCounter = imCounter + 1;
                  }
              }

              if ((OnGrabbedImage != null))
                OnGrabbedImage(this, copimg);
              }
        }
 private void noitfyGrabImage(HImage hImage)
 {
     if (GrabImageChanged != null)
     {
         GrabImageChanged(_bgworker, new ProgressChangedEventArgs(0, hImage));
     }
 }
        /**************************************************************************/
        /* Setup the GUI for the SmartWindow application
         **************************************************************************/
        private void SmartWindowForm_Load(object sender, System.EventArgs e)
        {
            hWndControl = new HWndCtrl(viewPort);
            String fileName = "patras";
            HImage image;

            try
            {
                image   = new HImage(fileName);
            }
            catch(HOperatorException)
            {
                MessageBox.Show("Problem occured while reading file!",
                                "SmartWindow2",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Information);
                return;
            }

            hWndControl.addIconicVar(image);
            hWndControl.repaint();
        }
 private void measurePos(HImage imageReduced)
 {
     mHandle.MeasurePos(imageReduced,
                                   mMeasAssist.mSigma, mMeasAssist.mThresh,
                                   mMeasAssist.mTransition, mMeasAssist.mPosition,
                                   out mResult.rowEdge, out mResult.colEdge,
                                   out mResult.amplitude, out mResult.distance);
 }