Пример #1
0
        public ICreateCoordinate SetImage(HImage image)
        {
            var dir      = typeof(Ex).Assembly.GetAssemblyDirectoryPath();
            var cacheDir = Path.Combine(dir, "CacheImages");

            if (Directory.Exists(cacheDir))
            {
                foreach (var file in Directory.GetFiles(cacheDir))
                {
                    File.Delete(file);
                }
            }

            if (!Directory.Exists(cacheDir))
            {
                Directory.CreateDirectory(cacheDir);
            }

            _inspectionResult = new InspectionResult();

            if (_image != null)
            {
                _image.Dispose();
            }
            _image = image;

            return(this);
        }
Пример #2
0
        public void SetModelImage()
        {
            if (ModelImg != null)
            {
                ModelImg.Dispose();
            }
            ModelImg = new HImage(InputImg);

            if (SearchRegion != null)
            {
                SearchRegion.Dispose();
                SearchRegion = null;
            }

            if (ModelRegion != null)
            {
                ModelRegion.Dispose();
                ModelRegion = null;
            }

            if (nCCModel != null)
            {
                nCCModel.Dispose();
                nCCModel = null;
            }
        }
Пример #3
0
        public void CloseCamera()
        {
            if (Device != null)
            {
                Device.ImageGrabbedEvt -= Device_ImageGrabbedEvt;
                if (cameraCtrls.Contains(this))
                {
                    lock (cameraCtrls)
                    {
                        cameraCtrls.Remove(this);
                    }
                }
                if (!_showExit && cameraCtrls.Count == 0)
                {
                    _showExit = true;
                    _showThread.Join();
                    _showThread = null;
                }

                lock (locker)
                {
                    if (himage != null)
                    {
                        himage.Dispose();
                    }
                }
            }
        }
Пример #4
0
        public bool CreateShapeModelAct(HImage modelImage)
        {
            if (modelImage == null || !modelImage.IsInitialized())
            {
                return(false);
            }
            this.modelImage = modelImage;

            if (modelRegion == null || !modelRegion.IsInitialized())
            {
                return(false);
            }
            try
            {
                HImage ROIImage = new HImage();
                ROIImage.GenEmptyObj();
                ROIImage = modelImage.ReduceDomain(modelRegion);
                HImage temp = ROIImage.GaussFilter(7);
                ROIImage.Dispose();
                ROIImage    = temp;
                hShapeModel = ROIImage.CreateScaledShapeModel(
                    new HTuple(numLevels),
                    angleStart, angleExtent, new HTuple(angleStep),
                    scaleMin, scaleMax, new HTuple(scaleStep),
                    new HTuple(optimization).TupleConcat("no_pregeneration"),
                    metric,
                    ((new HTuple(contrastLow)).TupleConcat(contrastHigh)).TupleConcat(minLength),
                    new HTuple(minContrast));



                ROIImage.Dispose();
                double row, col;
                modelRegion.AreaCenter(out row, out col);
                refCoordinates   = new HTuple(row, col, 0);
                createNewModelID = false;
                //初始化modelContours
                if (modelXLDCont == null)
                {
                    modelXLDCont = new HXLDCont();
                }
                if (modelXLDCont != null && modelXLDCont.IsInitialized())
                {
                    modelXLDCont.Dispose();
                }
                modelXLDCont = hShapeModel.GetShapeModelContours(1);
            }
            catch
            {
                hShapeModel      = null;
                createNewModelID = true;
                return(false);
            }

            return(true);
        }
Пример #5
0
 public void SetModelImage()
 {
     if (ModelRegion == null || !ModelRegion.IsInitialized())
     {
         return;
     }
     if (ModelImg != null)
     {
         ModelImg.Dispose();
     }
     ModelImg = new HImage(InputImg);
 }
 /// <summary>
 /// 拍摄一张图片
 /// </summary>
 /// <returns></returns>
 public bool GrabImage(int medianRadius, bool isMirror)
 {
     try
     {
         if (Connected)
         {
             //CurrentImage?.Dispose();
             HImage image = EnhancedImage(Framegrabber.GrabImage());
             if (medianRadius > 0)
             {
                 HObject medianedImage;
                 HOperatorSet.MedianImage(image, out medianedImage, "circle", medianRadius, "mirrored");
                 image.Dispose();
                 if (isMirror)
                 {
                     HObject imageMirror;
                     HOperatorSet.MirrorImage(medianedImage, out imageMirror, "column");
                     CurrentImage = new HImage(imageMirror);
                 }
                 else
                 {
                     CurrentImage = new HImage(medianedImage);
                 }
             }
             else
             {
                 if (isMirror)
                 {
                     HObject imageMirror;
                     HOperatorSet.MirrorImage(image, out imageMirror, "column");
                     image.Dispose();
                     CurrentImage = new HImage(imageMirror);
                 }
                 else
                 {
                     CurrentImage = image;
                 }
             }
             return(true);
         }
         else
         {
             return(false);
         }
     }
     catch
     {
         Connected = false;
         return(false);
     }
 }
Пример #7
0
        public void GetImage2()
        {
            Image_1?.Dispose();
            Image_1 = Framegrabber1.GrabImage(); //拍照
            Image_2?.Dispose();
            Image_2 = Framegrabber2.GrabImage(); //拍照
            Image_3?.Dispose();
            Image_3 = Framegrabber3.GrabImage(); //拍照

            Image2?.Dispose();
            Image2 = Image_1.ConcatObj(Image_2).ConcatObj(Image_3).TileImages(3, "horizontal");
            GlobalVar.hWndCtrl.addIconicVar(Image2);
            GlobalVar.hWndCtrl.repaint();
        }
Пример #8
0
 protected void TrigerImageEvent()
 {
     //帧率统计增加
     fps.IncreaseFrameNum();
     if (hPylonImage != null && hPylonImage.IsInitialized())
     {
         HImage imgTmp = RotateImage(hPylonImage);
         hPylonImage.Dispose();  //这样hPylonImage.IsInitialized()才能为true;
         hPylonImage = imgTmp;
         //imageResetEvent.Set();
         if (!isGrabberManual)
         {
             imageResetEvent.Set();
             TrigerImageEvent(this, new ImageEventArgs(Command, hPylonImage, cameraIndex, settingIndex, new HTuple(startTime.D)));
         }
         else
         {
             imageResetEvent.Set();
         }
     }
     else
     {
         Util.Notify(string.Format("相机{0}图像数据为空", cameraIndex));
     }
 }
Пример #9
0
 public override HImage GetImage()
 {
     if (image != null)
     {
         image.Dispose();
         image = null;
     }
     if (!GrabOne())
     {
         WriteErrorLog($"{this.Info.UserID}触发拍照失败");
         return(null);
     }
     timer.Start();
     while (image == null)
     {
         if (timer.TimeUp(0.5))
         {
             WriteErrorLog($"{this.Info.UserID}等待图像超时");
             break;
         }
         else
         {
             System.Threading.Thread.Sleep(10);
             continue;
         }
     }
     return(image);
 }
Пример #10
0
        public HImage Process(HImage image)
        {
            var domain          = image.GetDomain();
            var fullDomainImage = image.FullDomain();
            var fullDomain      = fullDomainImage.GetDomain();

            //
            var expandImage     = image.ExpandDomainGray(ExpansionRange);
            var expandFullImage = expandImage.FullDomain();
//            expandFullImage.WriteImage("tiff", 0, "D:\\test-0-expandFullImage.tif");

            //
            var holeRegion = fullDomain.Difference(domain);

            HImage paintedImage = expandFullImage;

            for (int i = 0; i < Items.Count; i++)
            {
                var imageFilter  = Items[i];
                var reducedImage = image.ChangeDomain(holeRegion);
                var meanedImage  = imageFilter.Process(reducedImage);
//                meanedImage.WriteImage("tiff", 0, "D:\\test-1-meanedImage_" + i + ".tif");

                var paintedImage2 = meanedImage.PaintGray(paintedImage);
                paintedImage.Dispose();
                paintedImage = paintedImage2;
//                paintedImage.WriteImage("tiff", 0, "D:\\test-2-paintedImage_" + i + ".tif");
            }

            return(paintedImage);
        }
Пример #11
0
        /// <summary>
        /// Releases all resources used by the Component.
        /// Stops the grabbing of images, closes the connection
        /// to the device and release the object, that is responsible
        /// for the device connection and image acquisition.
        /// </summary>
        new public void Dispose()
        {
            try
            {
                if (GrabOn)
                {
                    StopGrabThread();
                }

                CloseDevice();

                if (frameGrabber != null)
                {
                    frameGrabber.Dispose();
                }
                if (img != null)
                {
                    img.Dispose();
                }
            }
            finally
            {
                if (frameGrabber != null)
                {
                    frameGrabber.Dispose();
                }
            }
            base.Dispose();
        }
Пример #12
0
        private void 保存图片ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                System.Windows.Forms.SaveFileDialog ofDialog = new System.Windows.Forms.SaveFileDialog();
                ofDialog.InitialDirectory = System.Windows.Forms.Application.StartupPath;
                ofDialog.Filter           = "位图文件(*.bmp)|*.bmp|PNG(*.png)|*.png|JPGE(*.jpge,*.jpg)|*.jpeg;*.jpg";
                ofDialog.FilterIndex      = -1;
                ofDialog.Title            = "保存一张图片";

                string fPath, fName;
                if (ofDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    fPath = ofDialog.FileName;
                    string extension = System.IO.Path.GetExtension(fPath).Remove(0, 1);
                    HImage himage    = this.Camera.GetCurrentImage();
                    himage.WriteImage(extension, 0, fPath);
                    himage.Dispose();
                }
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show("保存图片失败:" + ex.Message);
            }
        }
Пример #13
0
        private void InitAcqBtn_Click(object sender, System.EventArgs e)
        {
            try
            {
                // execute procedure
                InitAcqProcCall.Execute();
                // get output parameters from procedure call
                Framegrabber =
                    new HFramegrabber(InitAcqProcCall.GetOutputCtrlParamTuple("AcqHandle"));
            }
            catch (HDevEngineException Ex)
            {
                MessageBox.Show(Ex.Message, "HDevEngine Exception");
                return;
            }

            HImage Image = Framegrabber.GrabImage();

            Image.DispObj(Window);
            Image.Dispose();

            // enable ProcessImage button and disable InitAcq button
            ProcessImageBtn.Enabled = true;
            InitAcqBtn.Enabled      = false;
        }
Пример #14
0
 protected void TrigerImageEvent()
 {
     //帧率统计增加
     fps.IncreaseFrameNum();
     if (hPylonImage != null && hPylonImage.IsInitialized())
     {
         HImage imgTmp = RotateImage(hPylonImage);
         hPylonImage.Dispose();
         hPylonImage = imgTmp;
         imageResetEvent.Set();
         if (Command != Command.Grab)
         {
             if (timeOld != null)
             {
                 double toolTime = (startTime - timeOld) * 1000.0;
                 if (Command != Command.Video)
                 {
                     Util.Notify(string.Format("相机{0}收到图像,采集间隔{1:f2}ms", CameraIndex, toolTime));
                 }
             }
             timeOld = startTime;
             //Util.Notify("收到图像"+ startTime.D);
             TrigerImageEvent(this, new ImageEventArgs(Command, hPylonImage, cameraIndex, new HTuple(startTime.D)));
         }
         //if (Command!= Command.Video)
         //{
         //    Command = Command.None;
         //}
     }
     else
     {
         Util.Notify(string.Format("相机{0}图像数据为空", cameraIndex));
     }
 }
Пример #15
0
        private void fToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string FilePath;
            HImage Img = new HImage();

            //Open Dialog to let user select image
            if (openImg.ShowDialog() == DialogResult.OK)
            {
                HGraphics.allObj.Clear();
                Control.CheckForIllegalCrossThreadCalls = false;
                //Display the file path on the title
                this.Text = openImg.FileName;
                FilePath  = openImg.FileName.Replace("\\", "/");
                Img.ReadImage(FilePath);
                hWindowControl.SetFullImagePart(Img);
                //Display the image on HALCON window
                HGraphics.allObj["pic"] = new HObject(Img);
                HGraphics.display();
                Img.Dispose();
                LogTextBox.Text += FilePath + "\n";
                //Scroll log to the bottom
                LogTextBox.SelectionStart = LogTextBox.Text.Length;
                LogTextBox.ScrollToCaret();
            }
        }
Пример #16
0
        void connectCam(string _interfacename, string _device)
        {
            _status_connect_cam = false;
            if (Framgraber != null)
            {
                Framgraber.Dispose();
            }

            Framgraber = new HFramegrabber(_interfacename, 0, 0, 0, 0, 0, 0, "progressive",
                                           -1, "default", -1, "default", _interfacename == "File" ? _device : "default", _interfacename == "File" ? "default" : _device, 0, -1);
            if (_interfacename == "GigE")
            {
                HOperatorSet.SetFramegrabberParam(Framgraber, "ExposureTime", 150000);
                HOperatorSet.SetFramegrabberParam(Framgraber, "Gain", 1);
                HOperatorSet.SetFramegrabberParam(Framgraber, "grab_timeout", 60000);
            }
            _status_connect_plc = true;

            Img = Framgraber.GrabImageAsync(1);
            Img.GetImagePointer1(out HTuple typeImg, out HTuple WidthImg, out HTuple HeightImg);
            HTuple a = 0;

            window.SetPart(a, a, HeightImg - 1, WidthImg - 1);
            Img.Dispose();
        }
Пример #17
0
        public HRegion Extract(HImage image)
        {
            var domain        = image.GetDomain();
            var offsetRow1    = domain.GetRow1();
            var offsetColumn1 = domain.GetColumn1();
            var croppedImage  = image.CropDomain();

            var    swThresholdImageFilter = new NotifyStopwatch("DynThresholdCroppedRegionExtractor.ThresholdImageFilter");
            HImage thresholdImage         = ThresholdImageFilter.Process(croppedImage);

            swThresholdImageFilter.Dispose();

            var     swDynThreshold = new NotifyStopwatch("DynThresholdCroppedRegionExtractor.DynThreshold");
            HRegion region         = croppedImage.DynThreshold(
                thresholdImage,
                Offset,
                LightDark.ToHalconString());

            swDynThreshold.Dispose();

            var movedRegion = region.MoveRegion(offsetRow1, offsetColumn1);

            croppedImage.Dispose();
            thresholdImage.Dispose();
            region.Dispose();

            return(movedRegion);
        }
Пример #18
0
 void connectCam(string _interfacename, string _device)
 {
     if (Framgraber != null)
     {
         Framgraber.Dispose();
     }
     try
     {
         Framgraber = new HFramegrabber(_interfacename, 0, 0, 0, 0, 0, 0, "progressive",
                                        -1, "default", -1, "default", _interfacename == "File" ? _device : "default", _interfacename == "File" ? "default" : _device, 0, -1);
         if (_interfacename == "GigE")
         {
             HOperatorSet.SetFramegrabberParam(Framgraber, "ExposureTime", 150000);
             HOperatorSet.SetFramegrabberParam(Framgraber, "Gain", 1);
             HOperatorSet.SetFramegrabberParam(Framgraber, "grab_timeout", 60000);
         }
         _Img = Framgraber.GrabImageAsync(1);
         _Img.GetImagePointer1(out HTuple typeImg, out HTuple WidthImg, out HTuple HeightImg);
         HTuple a = 0;
         _window.SetPart(a, a, HeightImg - 1, WidthImg - 1);
         _Img.Dispose();
     }
     catch (Exception ex)
     {
         MessageBox.Show(" Connnection Camera Error: " + ex, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
         dataerror = true;
     }
 }
Пример #19
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();
        }
        private void SaveImage(string files, HImage ngImage)
        {
            if (ngImage == null || ngImage.IsInitialized() == false)
            {
                return;
            }
            HImage imgSave = ngImage.CopyImage();

            Task.Run(() =>
            {
                try
                {
                    FileInfo fi = new FileInfo(files);
                    if (!fi.Directory.Exists)
                    {
                        fi.Directory.Create();
                    }
                    imgSave.WriteImage("png", 0, files);
                    imgSave.Dispose();
                }
                catch (Exception ex)
                {
                }
            });
        }
Пример #21
0
        private void CoreOnNewImage(HImage hImage, Guid tmpSessionId)
        {
            lock (OnNewImageLock)
            {
                double startTime = HSystem.CountSeconds();

                if (lastGrabImg[0] != null)
                {
                    lastGrabImg[0].Dispose();
                }
                lastGrabImg[0] = hImage.CopyImage();

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

                hImage.Dispose();

                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;

                result.ElapsedTime = tAnalisi;

                RaiseNewImageToDisplayEvent(iconicVarList, result);
            }
        }
Пример #22
0
        //////////////////////////////////////////////////////////////////////////////
        // DisplayResults() - This method is used in/as a delegate. It is invoked
        //                    from the main GUI thread
        //////////////////////////////////////////////////////////////////////////////
        public void DisplayResults()
        {
            int i;

            resultDataMutex.WaitOne();                          // CriticalSect
            HTuple time = resultData.timeNeeded;                // CriticalSect
            HTuple decodedDataStrings = resultData.decodedData; // CriticalSect
            HImage image        = resultData.resultImg;         // CriticalSect
            HTuple resultHandle = resultData.resultHandle;      // CriticalSect
            HXLD   symbolXLDs   = resultData.symbolData;        // CriticalSect

            containerIsFreeEvent.Set();                         // CriticalSect
            resultDataMutex.ReleaseMutex();                     // CriticalSect

            window.DispObj(image);
            window.DispObj(symbolXLDs);

            mainForm.procTimeLabel.Text = time.TupleString(".1f") + "  ms";
            mainForm.procTimeLabel.Refresh();

            for (i = 0; i < resultHandle.Length; i++)
            {
                mainForm.imageDataLabel.Text = decodedDataStrings[i].S;
                mainForm.imageDataLabel.Refresh();
            }

            image.Dispose();
            symbolXLDs.Dispose();
        }
        private void SaveImage(string files, HImage ngImage)
        {
            if (ngImage == null || ngImage.IsInitialized() == false)
            {
                Util.WriteLog(this.GetType(), "异常图像数据丢失");
                Util.Notify("异常图像数据丢失");
                return;
            }
            HImage imgSave = ngImage.CopyImage();

            Task.Run(() =>
            {
                try
                {
                    FileInfo fi = new FileInfo(files);
                    if (!fi.Directory.Exists)
                    {
                        fi.Directory.Create();
                    }

                    Common.FileAct.FileManger.DeleteOverflowFile(Path.GetDirectoryName(files), IniStatus.Instance.NgImageCount);
                    imgSave.WriteImage("png", 0, files);
                    imgSave.Dispose();
                }
                catch (Exception ex)
                {
                    Util.WriteLog(this.GetType(), ex);
                    Util.Notify(string.Format("相机{0}异常图像保存异常", settingIndex));
                }
            });
        }
        private bool StartupLicenseTest()
        {
            bool status = false;

            HImage  testImage  = new HImage();
            HRegion testRegion = new HRegion();

            try
            {
                // This will fail if we don't have a proper license
                testImage  = new HImage("byte", 16, 16);
                testRegion = testImage.Threshold(0.0, 255.0);

                HSystem.SetSystem("temporary_mem_cache", "false");  // This saves RAM significantly!
                HSystem.SetSystem("global_mem_cache", "idle");      // Likewise

                status = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + " " + DateTime.Now);    // Display errors if any in a listbox
            }
            finally
            {
                testImage.Dispose();
                testRegion.Dispose();
            }

            return(status);
        }
        private void SaveImage(string files, HImage ngImage)
        {
            if (ngImage == null || ngImage.IsInitialized() == false)
            {
                Util.WriteLog(this.GetType(), "异常图像数据丢失");
                Util.Notify("异常图像数据丢失");
                return;
            }
            HImage imgSave = ngImage.CopyImage();

            Task.Run(() =>
            {
                try
                {
                    FileInfo fi = new FileInfo(files);
                    if (!fi.Directory.Exists)
                    {
                        fi.Directory.Create();
                    }
                    imgSave.WriteImage("png", 0, files);
                    imgSave.Dispose();
                }
                catch (Exception ex)
                {
                    Util.WriteLog(this.GetType(), ex);
                    Util.Notify(string.Format("相机{0}异常图像保存异常", settingIndex));
                }
            });
        }
Пример #26
0
        public static bool DoDepthFromFocus(IntPtr[] imgPtr, int imgCount, int width, int height, string imgSaveFolder, string imgSaveName)
        {
            bool ret = false;

            try
            {
                if (imgPtr == null || imgCount < 1)
                {
                    return(false);
                }

                HImage ho_Image = new HImage();
                ho_Image.GenImageInterleaved(imgPtr[0], "bgr", width, height, 0, "byte", width, height, 0, 0, -1, 0);
                for (int i = 1; i < imgCount; i++)
                {
                    HImage temp = new HImage();
                    temp.GenImageInterleaved(imgPtr[i], "bgr", width, height, 0, "byte", width, height, 0, 0, -1, 0);
                    ho_Image = ho_Image.ConcatObj(temp);
                }

                ret = DepthFromFocusProc(ho_Image, imgSaveFolder, imgSaveName);
                ho_Image.Dispose();
            }
            catch (HalconException hex)
            {
                Trace.WriteLine(hex.GetErrorMessage(), "HALCON error");
            }
            return(ret);
        }
Пример #27
0
        public static bool DoDepthFromFocus(string imgSaveFolder, string imgSaveName)
        {
            bool ret = false;

            try
            {
                if (!Directory.Exists(imgSaveFolder))
                {
                    Trace.WriteLine(imgSaveFolder + " not exist!");
                    return(ret);
                }

                HTuple hv_Names = new HTuple();
                ListImageFiles(ref hv_Names, imgSaveFolder);
                HImage ho_Image = new HImage(hv_Names);

                ret = DepthFromFocusProc(ho_Image, imgSaveFolder, imgSaveName);
                ho_Image.Dispose();
            }
            catch (HalconException hex)
            {
                Trace.WriteLine(hex.GetErrorMessage(), "HALCON error");
            }
            return(ret);
        }
Пример #28
0
        /// <summary>
        /// Compute the model image and the model contour for the applied ROI.
        /// </summary>
        public void setModelROI(HRegion roi)
        {
            if (mTrainingImage == null)
            {
                return;
            }
            if (mROIModel != null)
            {
                mROIModel.Dispose();
            }
            mROIModel        = roi;
            PyramidROIs      = null;
            createNewModelID = true;

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

            if (mReducedImage != null)
            {
                mReducedImage.Dispose();
            }
            mReducedImage = mTrainingImage.ReduceDomain(mROIModel);

            determineStepRanges();

            if (parameterSet.isOnAuto())
            {
                determineShapeParameter();
            }

            inspectShapeModel();
        }
Пример #29
0
        private void StreamGrabber_ImageGrabbed(object sender, ImageGrabbedEventArgs e)// 回调函数
        {
            IGrabResult grabResult = e.GrabResult;

            using (grabResult)
            {
                try
                {
                    if (grabResult.GrabSucceeded == true)
                    {
                        if (IsMonoFormat(grabResult) == true)//黑白图像
                        {
                            Bitmap _bitmap  = bitmap;
                            HImage _hImage  = hImage;
                            Bitmap __bitmap = null;
                            __bitmap = new Bitmap(grabResult.Width, grabResult.Height, PixelFormat.Format32bppRgb);
                            BitmapData bmpData = __bitmap.LockBits(new Rectangle(0, 0, __bitmap.Width, __bitmap.Height), ImageLockMode.ReadWrite, __bitmap.PixelFormat);
                            converter.OutputPixelFormat = PixelType.BGRA8packed;
                            IntPtr ptrBmp = bmpData.Scan0;
                            converter.Convert(ptrBmp, bmpData.Stride * __bitmap.Height, grabResult);
                            __bitmap.UnlockBits(bmpData);
                            bitmap = RotateImage(__bitmap, 180);
                            byte[] buffer   = grabResult.PixelData as byte[];
                            IntPtr p        = Marshal.UnsafeAddrOfPinnedArrayElement(buffer, 0);
                            HImage __hImage = new HImage("byte", grabResult.Width, grabResult.Height, p);
                            hImage = __hImage.RotateImage(180d, "constant");
                            // CameraData.InertData.bitmap = new Bitmap(bitmap);//如果这里不使用new Bitmap则会内存泄漏
                            // CameraData.InertData.hImage = hImage;
                            DoSomething(bitmap, hImage);
                            if (_bitmap != null)
                            {
                                _bitmap.Dispose();
                            }
                            if (_hImage != null)
                            {
                                _hImage.Dispose();
                            }
                        }
                        else
                        {
                            if (grabResult.PixelTypeValue != PixelType.RGB8packed)//不是RGB8格式,则转换为RGB8格式,然后生成彩色图像(如果是RGB8格式则不需要转换)
                            {
                                byte[] buffer_rgb = new byte[grabResult.Width * grabResult.Height * 3];
                                IntPtr p          = Marshal.UnsafeAddrOfPinnedArrayElement(buffer_rgb, 0);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message.ToString());
                }
                finally
                {
                    e.DisposeGrabResultIfClone();
                }
            }
        }
Пример #30
0
 public void GrabImageVoid(int medianRadius, bool isEnhance, bool isMirror)
 {
     try
     {
         {
             //CurrentImage?.Dispose();
             HImage image = isEnhance ? EnhancedImage(Framegrabber.GrabImage()) : Framegrabber.GrabImage();
             if (medianRadius > 0)
             {
                 HObject medianedImage;
                 HOperatorSet.MedianImage(image, out medianedImage, "circle", medianRadius, "mirrored");
                 image.Dispose();
                 if (isMirror)
                 {
                     HObject imageMirror;
                     HOperatorSet.MirrorImage(medianedImage, out imageMirror, "column");
                     medianedImage.Dispose();
                     CurrentImage = new HImage(imageMirror);
                 }
                 else
                 {
                     CurrentImage = new HImage(medianedImage);
                 }
             }
             else
             {
                 if (isMirror)
                 {
                     HObject imageMirror;
                     HOperatorSet.MirrorImage(image, out imageMirror, "column");
                     image.Dispose();
                     CurrentImage = new HImage(imageMirror);
                 }
                 else
                 {
                     CurrentImage = image;
                 }
             }
         }
     }
     catch
     {
         Connected = false;
     }
 }