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();
        }
示例#2
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;
        }
示例#3
0
        private void WindowControl_Load(object sender, EventArgs e)
        {
            string ImgType;

            Window       = WindowControl.HalconWindow;
            Framegrabber = new HFramegrabber("File", 1, 1, 0, 0, 0, 0, "default",
                                             -1, "default", -1, "default",
                                             "board/board.seq", "default", 1, -1);
            Img = Framegrabber.GrabImage();
            Img.GetImagePointer1(out ImgType, out ImgWidth, out ImgHeight);
            Window.SetPart(0, 0, ImgHeight - 1, ImgWidth - 1);
            Img.DispObj(Window);
            Window.SetDraw("margin");
            Window.SetLineWidth(3);
            Rectangle = new HRegion(188.0, 182, 298, 412);
            Rectangle.AreaCenter(out Row, out Column);
            Rect1Row         = Row - 102;
            Rect1Col         = Column + 5;
            Rect2Row         = Row + 107;
            Rect2Col         = Column + 5;
            RectPhi          = 0;
            RectLength1      = 170;
            RectLength2      = 5;
            this.MouseWheel += my_MouseWheel;
        }
示例#4
0
        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;
                }
            }
        }
示例#5
0
        /**
         * Register the callback type selected by the user.
         *
         * @param acq Reference to an acquisition interface.
         * @param callbackType Selected callback to be registered.
         * @param userContext Object to be used at the other side of the callback.
         * @return If the registration was sucessfull.
         */
        static bool registerCallbackType(ref HFramegrabber acq, HTuple callbackType,
                                         object userContext)
        {
            IntPtr contextPtr, funcPtr;

            funcPtr    = Marshal.GetFunctionPointerForDelegate(gDelegateCallback);
            contextPtr = Marshal.AllocHGlobal(Marshal.SizeOf(userContext));
            Marshal.StructureToPtr(userContext, contextPtr, false);

            try
            {
                // If the user context is not needed, IntPtr.Zero can be passed.
                acq.SetFramegrabberCallback(callbackType.S.ToString(), funcPtr,
                                            contextPtr);
            }
            catch (HalconException exc)
            {
                Console.WriteLine(System.Environment.NewLine + "Callback " +
                                  callbackType.S.ToString() + " registration failed!");
                Console.WriteLine(exc.GetErrorMessage());
                return(false);
            }

            return(true);
        }
示例#6
0
        /**
         * Display all the supported HALCON Image Acquisition callbacks.
         *
         * @param acq Reference to the initialized acquisition interface.
         * @return List of the available callbacks.
         */
        static HTuple showAvailableCallbackTypes(ref HFramegrabber acq)
        {
            HTuple callbacks;

            Console.WriteLine("Get and show the supported callback types using the " +
                              System.Environment.NewLine +
                              "parameter 'available_callback_types'..." +
                              System.Environment.NewLine);

            callbacks = acq.GetFramegrabberParam("available_callback_types");

            if (callbacks.Length > 0)
            {
                Console.WriteLine("Available callback types:" +
                                  System.Environment.NewLine);
            }
            else
            {
                Console.WriteLine("No callback types supported by the selected device"
                                  + System.Environment.NewLine);
                return(callbacks);
            }

            for (int i = 0; i < callbacks.Length; i++)
            {
                Console.WriteLine((i + 1) + ")" + callbacks.TupleSelect(i).S.ToString());
            }

            return(callbacks);
        }
示例#7
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;
     }
 }
示例#8
0
 public ShapeModelDisplay(string path, HDrawingObject obj, IHActor window)
     : base(obj, window)
 {
     if (path == null)
     {
         throw new ArgumentNullException();
     }
     imggrabber = new HFramegrabber("File", 1, 1, 0, 0, 0, 0,
                                    "default", -1, "default", -1, "false", path, "", 1, 2);
 }
示例#9
0
        private void btnConnectDevice_Click(object sender, EventArgs e)
        {
            bool   isFileInterface     = false;
            string regexDevicePattern  = @"(device:)(.+?)(\s\|)";
            string regexGenericPattern = @"(suggestion:)(.+)(\s\|)";
            string deviceInfo          = cbDeviceList.SelectedItem.ToString();
            string device = Regex.Match(deviceInfo, regexDevicePattern).Groups[2].Value;

            if (device.Length < 3)
            {
                device = "default";
            }
            HTuple generic;

            if (deviceInfo.Contains("misconfigured"))
            {
                generic = Regex.Match(deviceInfo, regexGenericPattern).Groups[2].Value;
            }
            else
            {
                generic = new HTuple(-1);
            }
            //------------------------------------------------------------
            // Check if is File Interface
            //------------------------------------------------------------
            string interfaceName = cbInterfaceList.SelectedItem.ToString();

            if (interfaceName == "File")
            {
                isFileInterface = true;
            }
            if (!isFileInterface)
            {
                CameraFrameGrabber01 = new HFramegrabber(interfaceName, 1, 1, 0, 0, 0, 0, "default", new HTuple(-1), new HTuple("default"), generic, "default", new HTuple("default"), new HTuple(device), new HTuple(-1), new HTuple(-1));
            }
            else
            {
                CameraFrameGrabber01 = null;
            }
            //------------------------------------------------------------
            // Set Window display image
            //------------------------------------------------------------
            string ImgType;
            int    ImgWidth, ImgHeight;
            HImage Img;

            if (!isFileInterface)
            {
                Img = CameraFrameGrabber01.GrabImageAsync(1);
            }
            else
            {
                if (ListImageFiles.Count > 0)
                {
                    HOperatorSet.ReadImage(out HObject imageRead, ListImageFiles[0]);
示例#10
0
 public ImageGrabber(string path, IHActor destination) :
     base(destination, false)
 {
     SlowMotion = true;
     if (path == null)
     {
         throw new ArgumentNullException();
     }
     grabber = new HFramegrabber("File", 1, 1, 0, 0, 0, 0,
                                 "default", -1, "default", -1, "false", path, "", 1, 2);
 }
示例#11
0
        private void ExecuteBtn_Click(object sender, System.EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;

            HFramegrabber Framegrabber = new HFramegrabber();

            // read images and process them
            try
            {
                Framegrabber.OpenFramegrabber("File", 1, 1, 0, 0, 0, 0, "default",
                                              -1, "default", -1, "default", "fin.seq", "default", -1, -1);

                HImage  Image = new HImage();
                HRegion FinRegion;
                HTuple  FinArea;

                for (int i = 0; i <= 2; i++)
                {
                    Image.GrabImage(Framegrabber);
                    Image.DispObj(Window);

                    // execute procedure
                    ProcCall.SetInputIconicParamObject("Image", Image);
                    ProcCall.Execute();
                    // get output parameters from procedure call
                    FinRegion = ProcCall.GetOutputIconicParamRegion("FinRegion");
                    FinArea   = ProcCall.GetOutputCtrlParamTuple("FinArea");

                    // display results
                    Image.DispObj(Window);
                    Window.SetColor("red");
                    Window.DispObj(FinRegion);
                    Window.SetColor("white");
                    Window.SetTposition(150, 20);
                    Window.WriteString("FinArea: " + FinArea.D);
                    HSystem.WaitSeconds(2);

                    FinRegion.Dispose();
                    Image.Dispose();
                }
            }
            catch (HOperatorException Ex)
            {
                MessageBox.Show(Ex.Message, "HALCON Exception");
            }
            catch (HDevEngineException Ex)
            {
                MessageBox.Show(Ex.Message, "HDevEngine Exception");
            }

            Framegrabber.Dispose();

            this.Cursor = Cursors.Default;
        }
示例#12
0
        private void Load(int numberCodeReaderToLoad)
        {
            string jsonStr;
            //------------------------------------------------------------
            // Load cấu hình camera
            //------------------------------------------------------------
            string cameraSetUrl = Url + "\\CamSettings.json";

            if (File.Exists(cameraSetUrl))
            {
                jsonStr        = File.ReadAllText(cameraSetUrl);
                CameraSettings = JsonConvert.DeserializeObject <CameraSet>(jsonStr);
            }
            else
            {
                CameraSettings = new CameraSet();
            }
            //------------------------------------------------------------
            // Load cài đặt các module đọc code
            //------------------------------------------------------------
            CodeReaders = new List <CodeReader>();
            for (int i = 0; i < numberCodeReaderToLoad; i++)
            {
                string codeReaderFolder = Url + "\\" + i.ToString();
                string codeReaderUrl    = codeReaderFolder + "\\CodeReaderSettings.json";

                if (Directory.Exists(codeReaderFolder))
                {
                    jsonStr = File.ReadAllText(codeReaderUrl);
                    CodeReader tempCodeReader
                        = JsonConvert.DeserializeObject <CodeReader>(jsonStr);
                    CodeReaders.Add(tempCodeReader);
                }
            }
            //------------------------------------------------------------
            // Khởi tạo Camera
            //------------------------------------------------------------
            if (CameraSettings.Device.Length > 0)
            {
                string interfaceName = CameraSettings.Interface;
                string device        = CameraSettings.Device;
                string generic       = CameraSettings.Generic;
                Camera = new HFramegrabber(interfaceName, 1, 1, 0, 0, 0, 0, "default",
                                           new HTuple(-1), new HTuple("default"), generic,
                                           "default", new HTuple("default"), new HTuple(device),
                                           new HTuple(-1), new HTuple(-1));
            }
            else
            {
                Camera = null;
            }
        }
        private void hWindowControlWPF1_HInitWindow(object sender, EventArgs e)
        {
            // Get HALCON window from control. Due to restrictions of WPF
            // interoperating with native Windows, this is not yet available
            // in the Loaded event of the control or the parent window. The
            // best time to extract the HALCON window is in this event.
            Window = hWindowControlWPF1.HalconWindow;

            // Attention: Technically we are called by the control during its
            // initialization. Under now account should an exception be allowed
            // to propagate upwards from here (under Windows 7, not even the
            // Visual Studio debugger will function properly in this case).

            try
            {
                // Initialize enabled states
                CreateBtn.IsEnabled = true;
                StartBtn.IsEnabled  = false;
                StopBtn.IsEnabled   = false;

                // Create a timer for execution loop;
                Timer          = new DispatcherTimer();
                Timer.Interval = new TimeSpan(10);
                Timer.Tick    += new EventHandler(Timer_Tick);

                // Prepare image processing
                string ImgType;
                Framegrabber = new HFramegrabber("File", 1, 1, 0, 0, 0, 0, "default",
                                                 -1, "default", -1, "default",
                                                 "board/board.seq", "default", 1, -1);
                Img = Framegrabber.GrabImage();
                Img.GetImagePointer1(out ImgType, out ImgWidth, out ImgHeight);
                Window.SetPart(0, 0, ImgHeight - 1, ImgWidth - 1);
                Img.DispObj(Window);
                Window.SetDraw("margin");
                Window.SetLineWidth(3);
                Rectangle = new HRegion(188.0, 182, 298, 412);
                Rectangle.AreaCenter(out Row, out Column);
                Rect1Row    = Row - 102;
                Rect1Col    = Column + 5;
                Rect2Row    = Row + 107;
                Rect2Col    = Column + 5;
                RectPhi     = 0;
                RectLength1 = 170;
                RectLength2 = 5;
            }
            catch (Exception ex)
            {
                // Catch all
                MessageBox.Show("Error in HInitWindow:" + ex.ToString());
            }
        }
示例#14
0
 private void reconnectButton_Click(object sender, EventArgs e)
 {
     if (topView != null)
     {
         topView.Dispose();
         topView = new HFramegrabber();
     }
     if (bottomView != null)
     {
         bottomView.Dispose();
         bottomView = new HFramegrabber();
     }
     setCamera();
 }
示例#15
0
        /// <summary>
        /// 打开相机
        /// </summary>
        /// <param name="cameraName">相机名字</param>
        /// <param name="CameraInterface">相机接口</param>
        /// <returns></returns>
        public bool OpenCamera(string cameraName, string CameraInterface)
        {
            try
            {
                Framegrabber = new HFramegrabber(CameraInterface, 0, 0, 0, 0, 0, 0, "default", -1, "default", -1, "false", "default", cameraName, 0, -1);

                Connected = true;
                //GrabImageaAsyncStart();
                //Framegrabber.SetFramegrabberParam("AcquisitionMode", "SingleFrame");


                return(true);
            }
            catch (HalconException ex) { Connected = false; return(false); }
        }
示例#16
0
        private void OpenOfflineIADevice()
        {
            bool try_halcon_path = false;

            try
            {
                OpenFrameGrabber();
            }
            catch (HOperatorException)
            {
                try_halcon_path = true;
            }

            if (try_halcon_path)
            {
                String halconImagesPath, imPath;
                halconImagesPath = CreateHalconImagesPath();

                imPath = halconImagesPath + "\\" + this.CameraType;
                imPath = imPath.Replace("\\", "/");

                try
                {
                    // try to create framegrabber with the path
                    // to the HALCON images directory
                    frameGrabber = new HFramegrabber(this.IAName,
                                                     this.HorizontalResolution,
                                                     this.VerticalResolution,
                                                     this.ImageWidth,
                                                     this.ImageHeight,
                                                     this.StartRow,
                                                     this.StartColumn,
                                                     this.Field,
                                                     this.BitsPerChannel,
                                                     this.ColorSpace,
                                                     this.Generic,
                                                     this.ExternalTrigger,
                                                     imPath,
                                                     this.Device,
                                                     this.Port,
                                                     this.LineIn);
                }
                catch (HOperatorException exp)
                {
                    throw exp;
                }
            }
        }
示例#17
0
 public void CloseDevice()
 {
     if (frameGrabber != null)
     {
         if (frameGrabber.IsInitialized())
         {
             // if device performs image acquisition, then stop it
             if (GrabOn)
             {
                 StopGrabThread();
             }
             imCounter = 0;
             // close connection to IA device
             frameGrabber.Dispose();
             frameGrabber = null;
         }
     }
 }
        /// <summary>
        /// 打开相机
        /// </summary>
        /// <param name="cameraName">相机名字</param>
        /// <param name="CameraInterface">相机接口</param>
        /// <returns></returns>
        public bool OpenCamera(string cameraName, string CameraInterface)
        {
            try
            {
                //        "DirectShow", 1, 1, 0, 0, 0, 0, "default", 8, "rgb",
                //-1, "false", "default", "[0] Integrated Camera", 0, -1, out hv_AcqHandle
                //            Framegrabber = new HFramegrabber(CameraInterface, 1, 1, 0, 0, 0, 0, "default", 8, "rgb",
                //-1, "false", "default", cameraName, 0, -1);
                Framegrabber = new HFramegrabber(CameraInterface, 0, 0, 0, 0, 0, 0, "default", -1, "default", -1, "false", "default", cameraName, 0, -1);

                Connected = true;
                //GrabImageaAsyncStart();
                //Framegrabber.SetFramegrabberParam("AcquisitionMode", "SingleFrame");


                return(true);
            }
            catch (HalconException ex) { Connected = false; return(false); }
        }
示例#19
0
 /// <summary>
 /// Encapsulates the call of new framegrabber-Object with
 /// default parameters, that are already set up as class
 /// members.
 /// </summary>
 private void OpenFrameGrabber()
 {
     frameGrabber = new HFramegrabber(this.IAName,
                                      this.HorizontalResolution,
                                      this.VerticalResolution,
                                      this.ImageWidth,
                                      this.ImageHeight,
                                      this.StartRow,
                                      this.StartColumn,
                                      this.Field,
                                      this.BitsPerChannel,
                                      this.ColorSpace,
                                      this.Generic,
                                      this.ExternalTrigger,
                                      this.CameraType,
                                      this.Device,
                                      this.Port,
                                      this.LineIn);
 }
 public override void Close()
 {
     try
     {
         IsLink = false;
         threadRunSignal.Set();
         // Reset the stopwatch.
         //stopWatch.Reset();
         if (framegrabber != null)
         {
             framegrabber.Dispose();
             framegrabber = null;
         }
     }
     catch (Exception ex)
     {
         Util.WriteLog(this.GetType(), ex);
         Util.Notify("相机关闭异常");
     }
 }
示例#21
0
        //////////////////////////////////////////////////////////////////////////////
        // FGRun() - The thread functionFGRun is in charge of the asynchronous
        //           grabbing. To pass the images to the  other threads, we use
        //           a list. In case  the list exceeds a certain length, because
        //           the processing thread is slower then the grabbing thread,
        //           we omit new images until the list decreases again.
        //           To prevent data races, weuse a mutex to assure mutual
        //           access to the image list.
        //////////////////////////////////////////////////////////////////////////////
        public void ImgAcqRun()
        {
            // -------------------  INIT ----------------

            string sequenceName = "datacode/ecc200/ecc200.seq";

            HFramegrabber acquisition = new HFramegrabber("File", 1, 1, 0, 0, 0, 0,
                                                          "default", -1, "default", -1, "default", sequenceName, "default", -1, -1);

            // -----------  WAIT FOR EVENTS  ---------------

            while (true)
            {
                HImage grabbedImage = acquisition.GrabImageAsync(-1);

                newImgMutex.WaitOne();           // CriticalSect
                if (imgList.Count < MAX_BUFFERS) // CriticalSect
                {                                // CriticalSect
                    imgList.Add(grabbedImage);
                }
                else
                {
                    grabbedImage.Dispose();
                }                             // CriticalSect
                newImgMutex.ReleaseMutex();   // CriticalSect

                newImgEvent.Set();

                if (delegatedStopEvent.WaitOne(0, true))
                {
                    break;
                }
            }

            // --------  RESET/CLOSE ALL HANDLES  ---------

            acquisition.Dispose();
            newImgEvent.Reset();

            return;
        }
示例#22
0
 private void setCamera()
 {
     if (topView != null)
     {
         topView.Dispose();
         topView = new HFramegrabber();
     }
     if (bottomView != null)
     {
         bottomView.Dispose();
         bottomView = new HFramegrabber();
     }
     if (engMode == true)
     {
         topView.OpenFramegrabber("DirectShow", 1, 1, 0, 0, 0, 0, "default", 8, "rgb", -1, "false", "default", "[0] Integrated Webcam", 0, -1);
     }
     else
     {
         bottomView.OpenFramegrabber("GigEVision2", 0, 0, 0, 0, 0, 0, "progressive", -1, "default", -1, "false", "default", "licenseCam", 0, -1);
         //topView.OpenFramegrabber("GigEVision2", 0, 0, 0, 0, 0, 0, "progressive", -1, "default", -1, "false", "default", "containerCam", 0, -1);
     }
 }
示例#23
0
        /// <summary>
        /// Initializes a new instance of the HImageAcquisition from
        /// already initialized frame grabber handler.
        /// </summary>
        public HImageAcquisition(HTuple acqHandle)
        {
            InitializeComponent();

            if (locker == null)
            {
                locker = new object();
            }

            if (acqHandle.Length != 1)
            {
                throw new System.ArgumentOutOfRangeException("acqHandle",
                                                             acqHandle,
                                                             "Only one valid image acquisition handle" +
                                                             " is accepted as valid parameter!");
            }

            using (frameGrabber = new HFramegrabber(acqHandle[0].IP))
            {
                this.acqHandle = acqHandle[0];
            }
        }
 private void setHFramegrabber()
 {
     if (_hFrameGrabber == null)
     {
         _hFrameGrabber = new HFramegrabber(_FGArgs.Name,
                                            _FGArgs.HorizontalResolution,
                                            _FGArgs.VerticalResolution,
                                            _FGArgs.ImageWidth,
                                            _FGArgs.ImageHeight,
                                            _FGArgs.StartRow,
                                            _FGArgs.StartColumn,
                                            _FGArgs.Field,
                                            _FGArgs.BitsPerChannel,
                                            _FGArgs.ColorSpace,
                                            _FGArgs.Generic,
                                            _FGArgs.ExternalTrigger,
                                            _FGArgs.CameraType,
                                            _FGArgs.Device,
                                            _FGArgs.Port,
                                            _FGArgs.LineIn);
     }
 }
        //

        /// <summary>
        /// 設定 HFramegrabber 參數
        /// </summary>
        private void setHFramegrabber()
        {
            if (_hFrameGrabber == null || !_hFrameGrabber.IsInitialized())
            {
                _hFrameGrabber = new HFramegrabber(_FGArgs.Name,
                                                   _FGArgs.HorizontalResolution,
                                                   _FGArgs.VerticalResolution,
                                                   _FGArgs.ImageWidth,
                                                   _FGArgs.ImageHeight,
                                                   _FGArgs.StartRow,
                                                   _FGArgs.StartColumn,
                                                   _FGArgs.Field,
                                                   new HTuple(_FGArgs.BitsPerChannel),
                                                   new HTuple(_FGArgs.ColorSpace),
                                                   new HTuple(_FGArgs.Generic),
                                                   _FGArgs.ExternalTrigger,
                                                   new HTuple(_FGArgs.CameraType),
                                                   new HTuple(_FGArgs.Device),
                                                   new HTuple(_FGArgs.Port),
                                                   new HTuple(_FGArgs.LineIn));
            }
        }
示例#26
0
        private void btnConectaCam_Click(object sender, EventArgs e)
        {
            if (Framgraber != null)
            {
                Framgraber.Dispose();
            }
            _interfacename = cbxInterface.SelectedItem.ToString();
            _device        = cbxCamera.SelectedItem.ToString();
            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);


            //Framgraber = new HFramegrabber(_interfacename, 0, 0, 0, 0, 0, 0, "progressive", -1, "default", -1, "default",
            //   _interfacename == "file" ? "default" : _device, _interfacename == "file" ? _device : "default", 0, -1);

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

            //Window.SetPart(a , a, WidthImg - 1, HeightImg - 1);
            window.SetPart(a, a, WidthImg - 1, HeightImg - 1);
            Img.Dispose();
        }
示例#27
0
 public void OpenCamera()
 {
     try
     {
         GlobalVar.AddMessage("相机打开中...");
         //Image Acquisition 01: Code generated by Image Acquisition 01
         Framegrabber1 = new HFramegrabber("GigEVision", 0, 0, 0, 0, 0, 0, "default",
                                           -1, "default", -1, "false", "default", "CAM1", 0, -1);
         Framegrabber2 = new HFramegrabber("GigEVision", 0, 0, 0, 0, 0, 0, "default",
                                           -1, "default", -1, "false", "default", "CAM2", 0, -1);
         Framegrabber3 = new HFramegrabber("GigEVision", 0, 0, 0, 0, 0, 0, "default",
                                           -1, "default", -1, "false", "default", "CAM3", 0, -1);
         //Framegrabber = new HFramegrabber("GigEVision", 0, 0, 0, 0, 0, 0, "default",
         //    -1, "default", -1, "false", "default", "cam1", 0, -1);
         GlobalVar.AddMessage("相机打开成功!");
         CCDStatus = true;
     }
     catch (Exception ex)
     {
         CCDStatus = false;
         GlobalVar.AddMessage(ex.Message);
     }
 }
示例#28
0
        private void btnConnect_Click(object sender, EventArgs e)
        {
            //------------------------------------------------------------
            // Kiểm tra lệnh kết nối hay ngắt kết nối
            //------------------------------------------------------------
            if (CameraConnected)
            {
                MainFrameGrabber.Dispose();
                btnConnect.Text = "  Connect";
                CameraConnected = false;
                return;
            }
            //------------------------------------------------------------
            // Lấy giá trị device và generic cho hàm kết nối camera
            //------------------------------------------------------------
            bool   isFileInterface     = false;
            string regexDevicePattern  = @"(device:)(.+?)(\s\|)";
            string regexGenericPattern = @"(suggestion:)(.+)(\s\|)";
            string deviceInfo          = cbDevices.SelectedItem.ToString();
            string device = Regex.Match(deviceInfo, regexDevicePattern).Groups[2].Value;

            if (device.Length < 3)
            {
                device = "default";
            }
            HTuple generic;

            if (deviceInfo.Contains("misconfigured"))
            {
                generic = Regex.Match(deviceInfo, regexGenericPattern).Groups[2].Value;
            }
            else
            {
                generic = new HTuple(-1);
            }
            //------------------------------------------------------------
            // Check if is File Interface
            //------------------------------------------------------------
            string interfaceName = cbInterfaces.SelectedItem.ToString();

            if (interfaceName == "File")
            {
                isFileInterface = true;
            }
            if (!isFileInterface)
            {
                try
                {
                    MainFrameGrabber = new HFramegrabber(interfaceName, 1, 1, 0, 0, 0, 0, "default",
                                                         new HTuple(-1), new HTuple("default"), generic,
                                                         "default", new HTuple("default"), new HTuple(device),
                                                         new HTuple(-1), new HTuple(-1));
                }
                catch
                {
                    return;
                }
                try
                {
                    //------------------------------------------------------------
                    // Lấy giá trị Gain, Exposure từ Camera
                    //------------------------------------------------------------
                    HTuple gain         = MainFrameGrabber.GetFramegrabberParam("Gain");
                    HTuple exposureTime = MainFrameGrabber.GetFramegrabberParam("ExposureTime");
                    //------------------------------------------------------------
                    // Hiển thị lên ô cài đặt
                    //------------------------------------------------------------
                    txtGainValue.Text     = gain.D.ToString();
                    txtExposureValue.Text = exposureTime.D.ToString();
                    //------------------------------------------------------------
                    // Thay đổi trạng thái kết nối
                    //------------------------------------------------------------
                    btnConnect.Text = "  Connected";
                    CameraConnected = true;
                    //------------------------------------------------------------
                    // Cập nhật CameraSet
                    //------------------------------------------------------------
                    CurrentCameraSet.Device  = device;
                    CurrentCameraSet.Generic = generic;
                }
                catch (Exception ex) { }
            }
            else
            {
                MainFrameGrabber = null;
            }
            //------------------------------------------------------------
            // Set Window display image
            //------------------------------------------------------------
            string ImgType;
            int    ImgWidth, ImgHeight;
            HImage Img;

            Img = MainFrameGrabber.GrabImageAsync(1);
            Img.GetImagePointer1(out ImgType, out ImgWidth, out ImgHeight);
            MainWindow.SetPart(0, 0, ImgHeight - 1, ImgWidth - 1);
            Img.DispObj(MainWindow);
            Img.Dispose();
        }
 public void CloseDevice()
 {
     if (frameGrabber != null)
     {
         if (frameGrabber.IsInitialized())
         {
             // if device performs image acquisition, then stop it
             if (GrabOn)
                 StopGrabThread();
             imCounter = 0;
             // close connection to IA device
             frameGrabber.Dispose();
             frameGrabber = null;
         }
     }
 }
        /// <summary>
        /// Initializes a new instance of the HImageAcquisition from
        /// already initialized frame grabber handler.
        /// </summary>
        public HImageAcquisition(HTuple acqHandle)
        {
            InitializeComponent();

            if (locker == null)
                locker = new object();

            if (acqHandle.Length != 1)
                throw new System.ArgumentOutOfRangeException("acqHandle",
                                                             acqHandle,
                 "Only one valid image acquisition handle"+
                 " is accepted as valid parameter!");

             using (frameGrabber = new HFramegrabber(acqHandle[0].IP))
             {
                 this.acqHandle = acqHandle[0];
             }
        }
        private void OpenOfflineIADevice()
        {
            bool try_halcon_path = false;
            try
            {
                OpenFrameGrabber();

            }
            catch (HOperatorException)
            {
                try_halcon_path = true;
            }

            if (try_halcon_path)
            {
                String halconImagesPath, imPath;
                halconImagesPath = CreateHalconImagesPath();

                imPath = halconImagesPath + "\\" + this.CameraType;
                imPath = imPath.Replace("\\", "/");

                try
                {
                    // try to create framegrabber with the path
                    // to the HALCON images directory
                    frameGrabber = new HFramegrabber(this.IAName,
                                               this.HorizontalResolution,
                                               this.VerticalResolution,
                                               this.ImageWidth,
                                               this.ImageHeight,
                                               this.StartRow,
                                               this.StartColumn,
                                               this.Field,
                                               this.BitsPerChannel,
                                               this.ColorSpace,
                                               this.Generic,
                                               this.ExternalTrigger,
                                               imPath,
                                               this.Device,
                                               this.Port,
                                               this.LineIn);

                }
                catch (HOperatorException exp)
                {
                    throw exp;
                }
            }
        }
 /// <summary>
 /// Encapsulates the call of new framegrabber-Object with
 /// default parameters, that are already set up as class
 /// members.
 /// </summary>
 private void OpenFrameGrabber()
 {
     frameGrabber = new HFramegrabber(this.IAName,
                                 this.HorizontalResolution,
                                 this.VerticalResolution,
                                 this.ImageWidth,
                                 this.ImageHeight,
                                 this.StartRow,
                                 this.StartColumn,
                                 this.Field,
                                 this.BitsPerChannel,
                                 this.ColorSpace,
                                 this.Generic,
                                 this.ExternalTrigger,
                                 this.CameraType,
                                 this.Device,
                                 this.Port,
                                 this.LineIn);
 }
        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;
                }
            }
        }
示例#34
0
        public static bool Open()
        {
            try
            {
                int cameraCount = 0;
                if ((CameraFlag & CameraFlag.Basler) == CameraFlag.Basler)
                {
                    //#region basler相机遍历查询

                    //List<Basler.Pylon.ICameraInfo> g_allCameras = Basler.Pylon.CameraFinder.Enumerate();

                    //if (g_allCameras.Count > 0)
                    //{
                    //    for (int i = 0; i < g_allCameras.Count; i++)
                    //    {
                    //        Basler.Pylon.Camera g_camera = new Basler.Pylon.Camera(g_allCameras[i]);
                    //        if (true == g_camera.IsOpen)
                    //            g_camera.Close();

                    //        g_camera.Open();
                    //        string id = g_camera.Parameters[Basler.Pylon.PLCamera.DeviceUserID].GetValue();
                    //        int id1;
                    //        if (int.TryParse(id, out id1))
                    //        {
                    //            if (CameraDic.Keys.Contains(id1) == false)
                    //            {
                    //                CameraDic.Add(id1, new BaslerCamera(g_camera, id1));
                    //                cameraCount++;
                    //            }
                    //        }
                    //        else
                    //        {
                    //            Util.Notify("相机ID未设置");
                    //        }
                    //    }
                    //}

                    //#endregion
                }
                if ((CameraFlag & CameraFlag.Hikvision) == CameraFlag.Hikvision)
                {
                    #region 海康相机遍历枚举
                    MyCamera.MV_CC_DEVICE_INFO_LIST m_pDeviceList = new MyCamera.MV_CC_DEVICE_INFO_LIST();
                    int nRet;


                    nRet = CameraOperator.EnumDevices(MyCamera.MV_GIGE_DEVICE | MyCamera.MV_USB_DEVICE, ref m_pDeviceList);
                    if (0 == nRet && m_pDeviceList.nDeviceNum > 0)
                    {
                        for (int i = 0; i < m_pDeviceList.nDeviceNum; i++)
                        {
                            MyCamera.MV_CC_DEVICE_INFO device =
                                (MyCamera.MV_CC_DEVICE_INFO)Marshal.PtrToStructure(m_pDeviceList.pDeviceInfo[i],
                                                                                   typeof(MyCamera.MV_CC_DEVICE_INFO));

                            if (device.nTLayerType == MyCamera.MV_GIGE_DEVICE)
                            {
                                IntPtr buffer = Marshal.UnsafeAddrOfPinnedArrayElement(device.SpecialInfo.stGigEInfo, 0);
                                MyCamera.MV_GIGE_DEVICE_INFO gigeInfo = (MyCamera.MV_GIGE_DEVICE_INFO)Marshal.PtrToStructure(buffer, typeof(MyCamera.MV_GIGE_DEVICE_INFO));

                                int key;

                                if (int.TryParse(gigeInfo.chUserDefinedName, out key))
                                {
                                    if (CameraDic.Keys.Contains(key) == false)
                                    {
                                        CameraOperator m_pOperator = new CameraOperator();
                                        //打开设备
                                        nRet = m_pOperator.Open(ref device);
                                        //Util.Notify("打开相机");
                                        if (MyCamera.MV_OK == nRet)
                                        {
                                            CameraDic.Add(key, new HikvisionCamera(m_pOperator, key));
                                            cameraCount++;
                                        }
                                    }
                                }
                                else
                                {
                                    Util.Notify("相机ID未设置");
                                }
                            }
                            else if (device.nTLayerType == MyCamera.MV_USB_DEVICE)
                            {
                                IntPtr buffer = Marshal.UnsafeAddrOfPinnedArrayElement(device.SpecialInfo.stUsb3VInfo, 0);
                                MyCamera.MV_USB3_DEVICE_INFO usbInfo = (MyCamera.MV_USB3_DEVICE_INFO)Marshal.PtrToStructure(buffer, typeof(MyCamera.MV_USB3_DEVICE_INFO));

                                int key;

                                if (int.TryParse(usbInfo.chUserDefinedName, out key))
                                {
                                    if (CameraDic.Keys.Contains(key) == false)
                                    {
                                        CameraOperator m_pOperator = new CameraOperator();
                                        //打开设备
                                        nRet = m_pOperator.Open(ref device);
                                        if (MyCamera.MV_OK == nRet)
                                        {
                                            CameraDic.Add(key, new HikvisionCamera(m_pOperator, key));
                                            cameraCount++;
                                        }
                                    }
                                    else
                                    {
                                        Util.Notify("相机ID未设置");
                                    }
                                }
                            }
                        }
                    }

                    #endregion
                }
                if ((CameraFlag & CameraFlag.Mindvision) == CameraFlag.Mindvision)
                {
                    #region 迈徳威视相机遍历枚举

                    CameraSdkStatus     status;
                    tSdkCameraDevInfo[] tCameraDevInfoList;

                    status = MvApi.CameraEnumerateDevice(out tCameraDevInfoList);
                    if (status == CameraSdkStatus.CAMERA_STATUS_SUCCESS)
                    {
                        if (tCameraDevInfoList != null && tCameraDevInfoList.Count() > 0)//此时iCameraCounts返回了实际连接的相机个数。如果大于1,则初始化第一个相机
                        {
                            for (int i = 0; i < tCameraDevInfoList.Count(); i++)
                            {
                                IntPtr m_Grabber;
                                status = MvApi.CameraGrabber_Create(out m_Grabber, ref tCameraDevInfoList[i]);
                                if (status == CameraSdkStatus.CAMERA_STATUS_SUCCESS)
                                {
                                    CameraHandle m_hCamera = 0;             // 句柄
                                    MvApi.CameraGrabber_GetCameraHandle(m_Grabber, out m_hCamera);
                                    byte[] pName = new byte[255];
                                    MvApi.CameraGetFriendlyName(m_hCamera, pName);
                                    string str = System.Text.Encoding.ASCII.GetString(pName).Substring(0, 1);

                                    int key = -1;

                                    if (int.TryParse(str, out key) && CameraDic.Keys.Contains(key) == false)
                                    {
                                        CameraDic.Add(key, new MindCamera(m_hCamera, m_Grabber, key));
                                        cameraCount++;
                                    }
                                    //else
                                    //{
                                    //    Util.Notify("相机ID未设置");
                                    //}
                                }
                            }
                        }
                    }

                    #endregion
                }
                if ((CameraFlag & CameraFlag.Microvision) == CameraFlag.Microvision)
                {
                    #region 维视图像相机相机遍历枚举

                    //个数枚举
                    MVGigE.MVInitLib();
                    int      CamNum = 0;
                    MVSTATUS r      = MVGigE.MVGetNumOfCameras(out CamNum);
                    for (int i = 0; i < CamNum; i++)
                    {
                        IntPtr m_hCam;
                        byte   index = (byte)i;
                        r = MVGigE.MVOpenCamByIndex(index, out m_hCam);
                        if (m_hCam != IntPtr.Zero)
                        {
                            MVCamInfo pCamInfo;
                            MVGigE.MVGetCameraInfo(index, out pCamInfo);

                            string str = pCamInfo.mUserDefinedName;

                            int key = -1;

                            if (int.TryParse(str, out key) && CameraDic.Keys.Contains(key) == false)
                            {
                                CameraDic.Add(key, new MicrovisionCamera(m_hCam, key));
                                cameraCount++;
                            }
                            else
                            {
                                Util.Notify("相机ID未设置");
                            }
                        }
                    }

                    #endregion
                }
                if ((CameraFlag & CameraFlag.ICImaging) == CameraFlag.ICImaging)
                {
                    #region  美精相机遍历查询
                    TIS.Imaging.ICImagingControl cameraFind = new TIS.Imaging.ICImagingControl();

                    foreach (TIS.Imaging.Device Item in cameraFind.Devices)
                    {
                        string cameraName = Item.Name;
                        int    index1     = cameraName.IndexOf("[");
                        if (index1 > -1)
                        {
                            string dat  = cameraName.Substring(index1);
                            string dat1 = dat.Replace("[", "").Replace("]", "");
                            int    id1;
                            if (int.TryParse(dat1, out id1))
                            {
                                if (CameraDic.Keys.Contains(id1) == false)
                                {
                                    TIS.Imaging.ICImagingControl cameraTmp = new TIS.Imaging.ICImagingControl();
                                    cameraTmp.Device = Item.Name;
                                    bool x = cameraTmp.DeviceValid;
                                    CameraDic.Add(id1, new ICImagingCamera(cameraTmp, id1));
                                    cameraCount++;
                                }
                            }
                        }
                    }

                    #endregion
                }
                if ((CameraFlag & CameraFlag.DirectShow) == CameraFlag.DirectShow)
                {
                    #region DirectShow相机 当前只支持一个相机
                    HFramegrabber framegrabber = new HFramegrabber();
                    //HTuple Information = null;
                    //HTuple ValueList = null;
                    //HOperatorSet.InfoFramegrabber("DirectShow", "info_boards",out Information,out ValueList);
                    framegrabber.OpenFramegrabber("DirectShow", 1, 1, 0, 0, 0, 0, "default", 8, DirectShowColorSpace,
                                                  -1, "false", DirectShowCameraType, DirectShowIndex, 0, -1);
                    CameraDic.Add(1, new DirectShowCamera(framegrabber, 1));
                    #endregion
                }
                if ((CameraFlag & CameraFlag.DaHeng) == CameraFlag.DaHeng)
                {
                    //#region 大恒相机
                    //List<IGXDeviceInfo> listGXDeviceInfo = new List<IGXDeviceInfo>();
                    //IGXFactory IGXFactory1 = IGXFactory.GetInstance();
                    //IGXFactory1.Init();
                    //IGXFactory1.UpdateDeviceList(200, listGXDeviceInfo);
                    //foreach (var item in listGXDeviceInfo)
                    //{
                    //    string name = item.GetUserID();
                    //    int key;

                    //    if (int.TryParse(name, out key))
                    //    {
                    //        if (CameraDic.Keys.Contains(key) == false)
                    //        {
                    //            IGXDevice IGXDevice1 = null;
                    //            IGXDevice1 = IGXFactory1.OpenDeviceBySN(item.GetSN(), GX_ACCESS_MODE.GX_ACCESS_EXCLUSIVE);
                    //            CameraDic.Add(key, new DHCamera(IGXFactory1, IGXDevice1));

                    //        }
                    //    }

                    //}

                    //#endregion
                }

                if ((CameraFlag & CameraFlag.Gige) == CameraFlag.Gige)
                {
                    //#region Gige相机遍历查询

                    HTuple Information = null;
                    HTuple ValueList   = null;
                    HOperatorSet.InfoFramegrabber("GigEVision", "info_boards", out Information, out ValueList);
                    for (int i = 0; i < ValueList.Length; i++)
                    {
                        string valueTmp = ValueList[i];
                        string name     = GetGigeValue(valueTmp, "user_name:");

                        string device = GetGigeValue(valueTmp, "device:");
                        if (name != null && device != null)
                        {
                            int id1;
                            if (int.TryParse(name, out id1))
                            {
                                if (CameraDic.Keys.Contains(id1) == false)
                                {
                                    HFramegrabber grabber = new HFramegrabber();
                                    grabber.OpenFramegrabber("GigEVision", 0, 0, 0, 0, 0, 0, "default", -1,
                                                             "default", -1, "false", "default", device, 0, -1);
                                    CameraDic.Add(id1, new GigeCamera(grabber, id1));
                                    cameraCount++;
                                }
                            }
                        }
                    }
                    //List<ICameraInfo> g_allCameras = CameraFinder.Enumerate();

                    //if (g_allCameras.Count > 0)
                    //{
                    //    for (int i = 0; i < g_allCameras.Count; i++)
                    //    {
                    //        Basler.Pylon.Camera g_camera = new Basler.Pylon.Camera(g_allCameras[i]);
                    //        if (true == g_camera.IsOpen)
                    //            g_camera.Close();

                    //        g_camera.Open();
                    //        string id = g_camera.Parameters[PLCamera.DeviceUserID].GetValue();
                    //        int id1;
                    //        if (int.TryParse(id, out id1))
                    //        {
                    //            if (CameraDic.Keys.Contains(id1) == false)
                    //            {
                    //                CameraDic.Add(id1, new BaslerCamera(g_camera, id1));
                    //                cameraCount++;
                    //            }
                    //        }
                    //        else
                    //        {
                    //            Util.Notify("相机ID未设置");
                    //        }
                    //    }
                    //}

                    //#endregion
                }
                //打开相机
                foreach (var item in CameraDic.Values)
                {
                    item.Open();
                    Thread.Sleep(30);
                }

                if (CameraInitFinishEvent != null)
                {
                    CameraInitFinishEvent(null, null);
                }
                //else
                //{
                //    Util.Notify("无相机连接");
                //    return false;
                //}
            }
            catch (Exception ex)
            {
                Util.WriteLog(typeof(CameraManger), ex);
                Util.Notify("相机打开出现异常");
                Close();
                return(false);
            }
            return(true);
        }
        //
        /// <summary>
        /// 設定 HFramegrabber 參數
        /// </summary>
        private void setHFramegrabber()
        {
            if (_hFrameGrabber == null || !_hFrameGrabber.IsInitialized())
            {
                _hFrameGrabber = new HFramegrabber(_FGArgs.Name,
                                                                    _FGArgs.HorizontalResolution,
                                                                    _FGArgs.VerticalResolution,
                                                                    _FGArgs.ImageWidth,
                                                                    _FGArgs.ImageHeight,
                                                                    _FGArgs.StartRow,
                                                                    _FGArgs.StartColumn,
                                                                    _FGArgs.Field,
                                                                    new HTuple(_FGArgs.BitsPerChannel),
                                                                    new HTuple(_FGArgs.ColorSpace),
                                                                    new HTuple(_FGArgs.Generic),
                                                                    _FGArgs.ExternalTrigger,
                                                                    new HTuple(_FGArgs.CameraType),
                                                                    new HTuple(_FGArgs.Device),
                                                                    new HTuple(_FGArgs.Port),
                                                                    new HTuple(_FGArgs.LineIn));

            }
        }
 public GigeCamera(HFramegrabber framegrabber, int index)
 {
     this.framegrabber = framegrabber;
     this.cameraIndex  = index;
 }
 private void setHFramegrabber()
 {
     if (_hFrameGrabber == null)
     {
         _hFrameGrabber = new HFramegrabber(_FGArgs.Name,
                                             _FGArgs.HorizontalResolution,
                                             _FGArgs.VerticalResolution,
                                             _FGArgs.ImageWidth,
                                             _FGArgs.ImageHeight,
                                             _FGArgs.StartRow,
                                             _FGArgs.StartColumn,
                                             _FGArgs.Field,
                                             _FGArgs.BitsPerChannel,
                                             _FGArgs.ColorSpace,
                                             _FGArgs.Generic,
                                             _FGArgs.ExternalTrigger,
                                             _FGArgs.CameraType,
                                             _FGArgs.Device,
                                             _FGArgs.Port,
                                             _FGArgs.LineIn);
     }
 }