コード例 #1
0
        // Example of an image event handler.
        static void OnImageGrabbed(Object sender, ImageGrabbedEventArgs e)
        {
            // The grab result is automatically disposed when the event call back returns.
            // The grab result can be cloned using IGrabResult.Clone if you want to keep a copy of it (not shown in this sample).
            IGrabResult grabResult = e.GrabResult;

            // Image grabbed successfully?
            if (grabResult.GrabSucceeded)
            {
                // Access the image data.
                Console.WriteLine("SizeX: {0}", grabResult.Width);
                Console.WriteLine("SizeY: {0}", grabResult.Height);
                byte[] buffer = grabResult.PixelData as byte[];
                Console.WriteLine("Gray value of first pixel: {0}", buffer[0]);
                Console.WriteLine("");

                // Display the grabbed image.
                ImageWindow.DisplayImage(0, grabResult);
                ImagePersistence.Save(ImageFileFormat.Bmp, "test.bmp", grabResult);
            }
            else
            {
                Console.WriteLine("Error: {0} {1}", grabResult.ErrorCode, grabResult.ErrorDescription);
            }
        }
コード例 #2
0
        /// <summary>
        /// 触发一次拍照,返回图片宽高和图片数组
        /// </summary>
        /// <param name="status"></param>
        /// <param name="ImageWidth"></param>
        /// <param name="ImageHeight"></param>
        /// <param name="buffer"></param>
        /// <param name="ErrorMessage"></param>
        /// <returns></returns>
        public bool Trigger(out int status, out int ImageWidth, out int ImageHeight, out byte[] buffer, out string ErrorMessage)
        {
            const int isDone       = 0;
            const int noGrabing    = 1;
            const int isTriggering = 2;
            const int ResultError  = 3;

            if (WaitForFrameTriggerReady(1000, TimeoutHandling.ThrowException))
            {
                if (this.StreamGrabber.IsGrabbing)
                {
                    this.ExecuteSoftwareTrigger();
                    IGrabResult grabResult = StreamGrabber.RetrieveResult(5000, TimeoutHandling.ThrowException);
                    using (grabResult)
                    {
                        if (grabResult.GrabSucceeded)
                        {
                            ImageWidth  = grabResult.Width;
                            ImageHeight = grabResult.Height;

                            buffer = grabResult.PixelData as byte[];
                            ImagePersistence.Save(ImageFileFormat.Bmp, "test.bmp", grabResult);
                            status       = isDone;
                            ErrorMessage = null;
                            return(true);
                        }
                        else
                        {
                            status       = ResultError;
                            ImageWidth   = 0;
                            ImageHeight  = 0;
                            buffer       = null;
                            ErrorMessage = grabResult.ErrorCode + grabResult.ErrorDescription;
                            return(false);
                        }
                    }
                }
                else
                {
                    status       = noGrabing;
                    ErrorMessage = "相机不在抓取状态下。";
                    ImageWidth   = 0;
                    ImageHeight  = 0;
                    buffer       = null;
                    return(false);
                }
            }
            else
            {
                ImageWidth   = 0;
                ImageHeight  = 0;
                buffer       = null;
                status       = isTriggering;
                ErrorMessage = "正在等待前一次触发完成。";
                return(false);
            }
        }
コード例 #3
0
 private void StreamGrabber_ImageGrabbed(object sender, ImageGrabbedEventArgs e)
 {
     if (e.GrabResult.GrabSucceeded)
     {
         var    result = camera.StreamGrabber.RetrieveResult(3000, TimeoutHandling.Return);
         byte[] buffer = result.PixelData as byte[];
         ImagePersistence.Save(ImageFileFormat.Bmp, Application.StartupPath + "\\test.bmp", result);
     }
 }
コード例 #4
0
ファイル: MyGrab.cs プロジェクト: KDW79/BaslerCamTest
        public void GrabImage(string path)
        {
            try
            {
                // Create a camera object that selects the first camera device found.
                // More constructors are available for selecting a specific camera device.
                using (Camera camera = new Camera())
                {
                    // Print the model name of the camera.
                    Debug.WriteLine("Using camera {0}.", camera.CameraInfo[CameraInfoKey.ModelName]);

                    // Set the acquisition mode to free running continuous acquisition when the camera is opened.
                    camera.CameraOpened += Configuration.AcquireContinuous;

                    // Open the connection to the camera device.
                    camera.Open();

                    // The parameter MaxNumBuffer can be used to control the amount of buffers
                    // allocated for grabbing. The default value of this parameter is 10.
                    camera.Parameters[PLCameraInstance.MaxNumBuffer].SetValue(5);

                    // Start grabbing.
                    camera.StreamGrabber.Start();

                    // Grab a image.
                    // Wait for an image and then retrieve it. A timeout of 5000 ms is used.
                    IGrabResult grabResult = camera.StreamGrabber.RetrieveResult(5000, TimeoutHandling.ThrowException);

                    using (grabResult)
                    {
                        // Image grabbed successfully?
                        if (grabResult.GrabSucceeded)
                        {
                            // Access the image data.
                            Debug.WriteLine("SizeX: {0}", grabResult.Width);
                            Debug.WriteLine("SizeY: {0}", grabResult.Height);
                            Debug.WriteLine("IsValid: {0}", grabResult.IsValid);
                            Debug.WriteLine("Orientation: {0}", grabResult.Orientation);
                            Debug.WriteLine("PaddingX: {0}", grabResult.PaddingX);
                            Debug.WriteLine("PaddingY: {0}", grabResult.PaddingY);
                            byte[] buffer = grabResult.PixelData as byte[];
                            Debug.WriteLine("PixelData Count: {0}", buffer.Length);
                            //Debug.WriteLine("Gray value of first pixel: {0}", buffer[0]);
                            Debug.WriteLine("");

                            // Display the grabbed image.
                            //ImageWindow.DisplayImage(0, grabResult);

                            // 이미지를 하드디스크에 저장
                            ImagePersistence.Save((int)ImageFileFormat.BMP, path + "\\" + DateTime.Now.ToString("yyyyMMdd_HHMMss") + "_GrabOrg.bmp", grabResult);
                            //ImagePersistence.Save((int)ImageFileFormat.BMP, @"D:\" + DateTime.Now.ToString("yyyyMMdd_HHMMss") + "_GrabOrg.bmp", grabResult);

                            // IImage를 bitmap 형식으로 변환
                            myBitmap = new Bitmap(grabResult.Width, grabResult.Height, PixelFormat.Format32bppRgb);
                            // Lock the bits of the bitmap.
                            BitmapData bmpData = myBitmap.LockBits(new Rectangle(0, 0, myBitmap.Width, myBitmap.Height), ImageLockMode.ReadWrite, myBitmap.PixelFormat);
                            // Place the pointer to the buffer of the bitmap.
                            myPixelDataConverter.OutputPixelFormat = PixelType.BGRA8packed;
                            IntPtr ptrBmp = bmpData.Scan0;
                            myPixelDataConverter.Convert(ptrBmp, bmpData.Stride * myBitmap.Height, grabResult);
                            myBitmap.UnlockBits(bmpData);

                        }
                        else
                        {
                            Debug.WriteLine("Error: {0} {1}", grabResult.ErrorCode, grabResult.ErrorDescription);
                        }
                    }

                    // Stop grabbing.
                    camera.StreamGrabber.Stop();

                    // Close the connection to the camera device.
                    camera.Close();
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine("Exception: {0}", e.Message);
            }
        }
コード例 #5
0
        public bool Grab(string CameraSelect)
        {
            bool status = false;

            try
            {
                // Create a camera object that selects the first camera device found.
                // More constructors are available for selecting a specific camera device.
                string datePatt = @"yyyyMMdd";


                using (Camera camera = new Camera(CameraSelect))
                {
                    // Print the model name of the camera.
                    //Console.WriteLine("Using camera {0}.", camera.CameraInfo[CameraInfoKey.ModelName]);

                    // Set the acquisition mode to free running continuous acquisition when the camera is opened.
                    camera.CameraOpened += Configuration.AcquireContinuous;

                    // Open the connection to the camera device.
                    camera.Open();

                    // The parameter MaxNumBuffer can be used to control the amount of buffers
                    // allocated for grabbing. The default value of this parameter is 10.
                    camera.Parameters[PLCameraInstance.MaxNumBuffer].SetValue(5);
                    camera.Parameters[PLCamera.PixelFormat].TrySetValue(PLCamera.PixelFormat.Mono8);
                    camera.Parameters[PLCamera.GainAuto].TrySetValue(PLCamera.GainAuto.Off);
                    camera.Parameters[PLCamera.CenterX].TrySetValue(true);
                    camera.Parameters[PLCamera.CenterY].TrySetValue(true);
                    camera.Parameters[PLCamera.ExposureTimeAbs].TrySetValue(40000.0);
                    camera.Parameters[PLCamera.ExposureTime].TrySetValue(40000.0);
                    // Setting the AOI. OffsetX, OffsetY, Width, and Height are integer parameters.
                    // On some cameras, the offsets are read-only. If they are writable, set the offsets to min.
                    camera.Parameters[PLCamera.OffsetX].TrySetToMinimum();
                    camera.Parameters[PLCamera.OffsetY].TrySetToMinimum();
                    // Some parameters have restrictions. You can use GetIncrement/GetMinimum/GetMaximum to make sure you set a valid value.
                    // Here, we let pylon correct the value if needed.
                    camera.Parameters[PLCamera.Width].SetValue(1139, IntegerValueCorrection.Nearest);
                    camera.Parameters[PLCamera.Height].SetValue(866, IntegerValueCorrection.Nearest);
                    // Start grabbing.
                    camera.StreamGrabber.Start();

                    // Grab a number of images.
                    for (int i = 0; i < 10; ++i)
                    {
                        // Wait for an image and then retrieve it. A timeout of 5000 ms is used.
                        IGrabResult grabResult = camera.StreamGrabber.RetrieveResult(3000, TimeoutHandling.ThrowException);
                        using (grabResult)
                        {
                            // Image grabbed successfully?
                            if (grabResult.GrabSucceeded)
                            {
                                if (grabResult.HasCRC && grabResult.CheckCRC() == false)
                                {
                                    Common.Reports.LogFile.Log("Image is corrupted: " + grabResult.ErrorCode + " " + grabResult.ErrorDescription);
                                }

                                // Access the image data.
                                imageWidth  = grabResult.Width;
                                imageHeight = grabResult.Height;
                                int width  = Convert.ToInt32(imageWidth);
                                int height = Convert.ToInt32(imageHeight);
                                //Bitmap bmp = new Bitmap(grabResult.Width, grabResult.Height);
                                if (!Directory.Exists(path))
                                {
                                    System.IO.Directory.CreateDirectory(path);
                                }

                                //file = path + DateTime.Now.ToString(datePatt);
                                if (File.Exists(@"D:\\LOGIMG\\raw.bmp")) //@"C:\tidy.exe"
                                {
                                    // If file found, delete it
                                    File.Delete(@"D:\\LOGIMG\\raw.bmp");
                                }
                                file = path + "raw.bmp";
                                ImagePersistence.Save(ImageFileFormat.Bmp, file, grabResult);

                                Common.Reports.LogFile.Log("Grab Image Succeeded.");
                                camera.StreamGrabber.Stop();
                                camera.Close();
                                return(true);
                                // Display the grabbed image.
                                //ImageWindow.DisplayImage(0, grabResult);
                            }
                            else
                            {
                                Common.Reports.LogFile.Log("Failed to grab image: " + grabResult.ErrorCode + " " + grabResult.ErrorDescription);
                                camera.StreamGrabber.Stop();
                                camera.Close();
                            }
                        }
                    }

                    // Stop grabbing.
                    camera.StreamGrabber.Stop();

                    // Close the connection to the camera device.
                    camera.Close();
                }
            }
            catch (Exception ex)
            {
                Common.Reports.LogFile.Log("Failed to grab image: " + ex.Message);
            }
            finally
            {
            }
            return(status);
        }
コード例 #6
0
        public static void Grab_One_Image_v3(String divece_SN, String filename)
        {
            bool        camera_on_list = false;
            Camera      camera         = null;
            ICameraInfo tag            = null;

            try
            {
                // Ask the camera finder for a list of camera devices.
                List <ICameraInfo> allCameras = CameraFinder.Enumerate();


                // Check if the given camera is in the camera list
                foreach (ICameraInfo cameraInfo in allCameras)
                {
                    if (cameraInfo[CameraInfoKey.SerialNumber] == divece_SN)
                    {
                        //save tags for camera
                        camera_on_list = true;
                        tag            = cameraInfo;
                        break;
                    }
                }

                if (!camera_on_list)
                {
                    Console.WriteLine("No such camera: " + divece_SN + "\n");
                    return;
                }

                if (camera_on_list == true && tag != null)
                {
                    try
                    {
                        //create a new camera object
                        using (camera = new Camera(tag))
                        {
                            camera.CameraOpened += Configuration.AcquireContinuous;

                            // Register for the events of the image provider needed for proper operation.
                            //camera.ConnectionLost += OnConnectionLost;
                            //camera.CameraOpened += OnCameraOpened;
                            //camera.CameraClosed += OnCameraClosed;
                            //camera.StreamGrabber.GrabStarted += OnGrabStarted;
                            //camera.StreamGrabber.ImageGrabbed += OnImageGrabbed;
                            //camera.StreamGrabber.GrabStopped += OnGrabStopped;

                            // Open the connection to the camera device
                            camera.Open();

                            //Set the parameters for the controls.
                            camera.Parameters[PLCamera.GainAuto].SetValue("Off");
                            camera.Parameters[PLCamera.GainRaw].SetValue(85);
                            camera.Parameters[PLCamera.DecimationHorizontal].SetValue(2);
                            camera.Parameters[PLCamera.DecimationVertical].SetValue(2);
                            camera.Parameters[PLCamera.BalanceWhiteAuto].SetValue("Off");
                            camera.Parameters[PLCamera.LightSourceSelector].SetValue("Daylight");
                            camera.Parameters[PLCamera.BalanceRatioSelector].SetValue("Red");
                            camera.Parameters[PLCamera.BalanceRatioRaw].SetValue(101);
                            camera.Parameters[PLCamera.PixelFormat].SetValue("YUV422_YUYV_Packed");
                            camera.Parameters[PLCamera.ExposureTimeRaw].SetValue(24500);

                            // Start Stream Grabber
                            try
                            {
                                // Starts the grabbing of one image.
                                camera.Parameters[PLCamera.AcquisitionMode].SetValue(PLCamera.AcquisitionMode.SingleFrame);
                                camera.StreamGrabber.Start();
                                IGrabResult grabResult = camera.StreamGrabber.RetrieveResult(10000, TimeoutHandling.ThrowException);
                                using (grabResult)
                                {
                                    if (grabResult.GrabSucceeded)
                                    {
                                        byte[] buffer = grabResult.PixelData as byte[];
                                        ImagePersistence.Save(ImageFileFormat.Jpeg, filename, grabResult);
                                        Console.WriteLine("Saving... " + filename + "\n");
                                    }
                                    else
                                    {
                                        //error
                                    }
                                }
                                camera.StreamGrabber.Stop();
                                camera.Close();
                            }
                            catch (Exception exception)
                            {
                                ShowException(exception);
                                camera.StreamGrabber.Stop();
                                camera.Close();
                            }


                            //camera.Dispose(); //May damage the buffer, do not use it!
                        }
                    }

                    catch (Exception exception)
                    {
                        ShowException(exception);
                        camera.StreamGrabber.Stop();
                        camera.Close();
                    }
                }
            }

            catch (Exception exception)
            {
                ShowException(exception);
                camera.StreamGrabber.Stop();
                camera.Close();
            }
        }
コード例 #7
0
        private void grabOne()
        {
            var result = camera.StreamGrabber.GrabOne(200);

            ImagePersistence.Save(ImageFileFormat.Bmp, Application.StartupPath + "\\test.bmp", result);
        }
コード例 #8
0
        private void button8_Click(object sender, EventArgs e)
        {
            const int c_countOfImagesToGrab = 2;    //获取2张图像

            // The exit code of the sample application.
            //  int exitCode = 0;


            // Create a camera object that selects the first camera device found。创建一个相机对象,该对象选择第一个被发现的相机设备。
            // More constructors are available for selecting a specific camera device.

            using (Camera camera = new Camera())    //需要对这种异常检测的用法注意一下。
            {
                // Print the model name of the camera.
                Console.WriteLine("Using camera {0}.", camera.CameraInfo[CameraInfoKey.ModelName]);

                // Set the acquisition mode to free running continuous acquisition when the camera is opened. 将相机设定为获取模式。
                camera.CameraOpened += Configuration.AcquireContinuous;    //连续取相

                // Open the connection to the camera device.打开与相机设备的链接
                camera.Open();

                // Enable the chunk mode. 启动块模式、

                if (!camera.Parameters[PLCamera.ChunkModeActive].TrySetValue(true))
                {
                    throw new Exception("The camera doesn't support chunk features");
                }

                // Enable time stamp chunks.
                camera.Parameters[PLCamera.ChunkSelector].SetValue(PLCamera.ChunkSelector.Timestamp);
                camera.Parameters[PLCamera.ChunkEnable].SetValue(true);

                // Enable frame counter chunk if possible. 启动桢数数
                if (camera.Parameters[PLCamera.ChunkSelector].TrySetValue(PLCamera.ChunkSelector.Framecounter))
                {
                    camera.Parameters[PLCamera.ChunkEnable].SetValue(true);
                }
                // Enable generic counters if possible (USB camera devices).
                else if (camera.Parameters[PLCamera.ChunkSelector].TrySetValue(PLCamera.ChunkSelector.CounterValue))
                {
                    camera.Parameters[PLCamera.ChunkEnable].SetValue(true);
                    camera.Parameters[PLCamera.CounterSelector].SetValue(PLCamera.CounterSelector.Counter1);
                    camera.Parameters[PLCamera.CounterEventSource].SetValue(PLCamera.CounterEventSource.FrameStart);
                }

                // Enable CRC checksum chunks.
                camera.Parameters[PLCamera.ChunkSelector].SetValue(PLCamera.ChunkSelector.PayloadCRC16);
                camera.Parameters[PLCamera.ChunkEnable].SetValue(true);


                // Start grabbing c_countOfImagesToGrab images.开始获取图像
                camera.StreamGrabber.Start(c_countOfImagesToGrab);

                // camera.StreamGrabber.Stop() is called automatically by the RetrieveResult() method
                // when c_countOfImagesToGrab images have been retrieved.

                // Wait for an image and then retrieve it. A timeout of 5000 ms is used.
                IGrabResult grabResult = camera.StreamGrabber.RetrieveResult(5000, TimeoutHandling.ThrowException);
                using (grabResult)
                {
                    // Image grabbed successfully?
                    if (grabResult.GrabSucceeded)
                    {
                        PictureAddress          = "E:\\实验缓存照片\\" + System.DateTime.Now.Day.ToString() + System.DateTime.Now.Hour.ToString() + System.DateTime.Now.Minute.ToString() + System.DateTime.Now.Second.ToString() + ".png";
                        PictureProcessedAddress = "E:\\实验缓存照片\\" + System.DateTime.Now.Day.ToString() + System.DateTime.Now.Hour.ToString() + System.DateTime.Now.Minute.ToString() + System.DateTime.Now.Second.ToString() + "(Processed).png";

                        ImagePersistence.Save(ImageFileFormat.Png, PictureAddress, grabResult);


                        //Mat original_picture = CvInvoke.Imread(PictureAddress, LoadImageType.AnyColor);
                        //string win1 = "original picture";
                        //CvInvoke.NamedWindow(win1, NamedWindowType.Normal);
                        //CvInvoke.Imshow(win1, original_picture);

                        //CvInvoke.WaitKey(0);
                        //IntPtr mat = original_picture.Ptr;
                        //CvInvoke.cvReleaseMat(ref mat);
                        //CvInvoke.DestroyWindow(win1);

                        pictureBox1.Load(PictureAddress);
                        pictureBox2.Load(PictureAddress);
                        camera.Close();
                    }
                    else
                    {
                        Console.WriteLine("Error: {0} {1}", grabResult.ErrorCode, grabResult.ErrorDescription);
                        MessageBox.Show("something Wrong :Error: {0} {1}, grabResult.ErrorCode, grabResult.ErrorDescription");
                    }
                }
            }
        }