private void Mytest(object sender, EventArgs e) { IGrabResult grabResult = m_camera.StreamGrabber.RetrieveResult(500, TimeoutHandling.ThrowException); using (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[]; IntPtr ptr = Marshal.AllocHGlobal(buffer.Length); Marshal.Copy(buffer, 0, ptr, buffer.Length); int i = mChipDetection.myfind(ptr, (UInt32)grabResult.Width, (UInt32)grabResult.Height); lblDebug.Text = string.Empty; lblDebug.Text += i.ToString() + "\r\n"; //mChipDetection.savebuffer(ptr, (UInt32)grabResult.Width, (UInt32)grabResult.Height); // Display the grabbed image. ImageWindow.DisplayImage(0, grabResult); } else { Console.WriteLine("Error: {0} {1}", grabResult.ErrorCode, grabResult.ErrorDescription); } } }
// 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); } }
public void GrabImage(string filename) { camera.StreamGrabber.Start(); IGrabResult grabResult = camera.StreamGrabber.RetrieveResult(5000, TimeoutHandling.ThrowException); using (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 Method 1 ############## // Display the grabbed image. ImageWindow.DisplayImage(0, grabResult); //####### Display Method 2 : Convert to C# Image ######### Bitmap bmp = ConvertArrayToImage(buffer, grabResult.Width, grabResult.Height, grabResult); bmp.RotateFlip(RotateFlipType.Rotate90FlipNone); bmp.Save(filename); } else { Console.WriteLine("Error: {0} {1}", grabResult.ErrorCode, grabResult.ErrorDescription); MessageBox.Show("Error : " + grabResult.ErrorDescription); MessageBox.Show("test"); } } camera.StreamGrabber.Stop(); }
static void AutoGainOnce(Camera camera) { // Check whether the gain auto function is available. if (!camera.Parameters[PLCamera.GainAuto].IsWritable) { Console.WriteLine("The camera does not support Gain Auto."); return; } // Maximize the grabbed image area of interest (Image AOI). camera.Parameters[PLCamera.OffsetX].TrySetValue(camera.Parameters[PLCamera.OffsetX].GetMinimum()); camera.Parameters[PLCamera.OffsetX].TrySetValue(camera.Parameters[PLCamera.OffsetY].GetMinimum()); camera.Parameters[PLCamera.Width].SetValue(camera.Parameters[PLCamera.Width].GetMaximum()); camera.Parameters[PLCamera.Height].SetValue(camera.Parameters[PLCamera.Height].GetMaximum()); // Set the Auto Function ROI for luminance statistics. // We want to use ROI1 for gathering the statistics. if (camera.Parameters[autoFunctionAOIROIUseBrightness].IsWritable) { camera.Parameters[regionSelector].SetValue(regionSelectorValue1); camera.Parameters[autoFunctionAOIROIUseBrightness].SetValue(true); // ROI 1 is used for brightness control camera.Parameters[regionSelector].SetValue(regionSelectorValue2); camera.Parameters[autoFunctionAOIROIUseBrightness].SetValue(false); // ROI 2 is not used for brightness control } camera.Parameters[regionSelector].SetValue(regionSelectorValue1); camera.Parameters[regionSelectorOffsetX].SetValue(camera.Parameters [PLCamera.OffsetX].GetMinimum()); camera.Parameters[regionSelectorOffsetY].SetValue(camera.Parameters [PLCamera.OffsetY].GetMinimum()); camera.Parameters[regionSelectorWidth].SetValue(camera.Parameters[PLCamera.Width].GetMaximum()); camera.Parameters[regionSelectorHeight].SetValue(camera.Parameters[PLCamera.Height].GetMaximum()); // We are going to try GainAuto = Once. Console.WriteLine("Trying 'GainAuto = Once'."); if (camera.GetSfncVersion() < sfnc2_0_0) // Handling for older cameras { // Set the target value for luminance control. The value is always expressed // as an 8 bit value regardless of the current pixel data output format, // i.e., 0 -> black, 255 -> white. camera.Parameters[PLCamera.AutoTargetValue].SetValue(80); Console.WriteLine("Initial Gain = {0}", camera.Parameters[PLCamera.GainRaw].GetValue()); // Set the gain ranges for luminance control. camera.Parameters[PLCamera.AutoGainRawLowerLimit].SetValue(camera.Parameters[PLCamera.GainRaw].GetMinimum()); camera.Parameters[PLCamera.AutoGainRawUpperLimit].SetValue(camera.Parameters[PLCamera.GainRaw].GetMaximum()); } else // Handling for newer cameras (using SFNC 2.0, e.g. USB3 Vision cameras) { // Set the target value for luminance control. // A value of 0.3 means that the target brightness is 30 % of the maximum brightness of the raw pixel value read out from the sensor. // A value of 0.4 means 40 % and so forth. camera.Parameters[PLCamera.AutoTargetBrightness].SetValue(0.3); Console.WriteLine("Initial Gain = {0}", camera.Parameters[PLCamera.Gain].GetValue()); // Set the gain ranges for luminance control. camera.Parameters[PLCamera.AutoGainLowerLimit].SetValue(camera.Parameters[PLCamera.Gain].GetMinimum()); camera.Parameters[PLCamera.AutoGainUpperLimit].SetValue(camera.Parameters[PLCamera.Gain].GetMaximum()); } camera.Parameters[PLCamera.GainAuto].SetValue(PLCamera.GainAuto.Once); // When the "once" mode of operation is selected, // the parameter values are automatically adjusted until the related image property // reaches the target value. After the automatic parameter value adjustment is complete, the auto // function will automatically be set to "off" and the new parameter value will be applied to the // subsequently grabbed images. int n = 0; while (camera.Parameters[PLCamera.GainAuto].GetValue() != PLCamera.GainAuto.Off) { IGrabResult result = camera.StreamGrabber.GrabOne(5000, TimeoutHandling.ThrowException); using (result) { // Image grabbed successfully? if (result.GrabSucceeded) { ImageWindow.DisplayImage(1, result); } } n++; //For demonstration purposes only. Wait until the image is shown. System.Threading.Thread.Sleep(100); //Make sure the loop is exited. if (n > 100) { throw new TimeoutException("The adjustment of auto gain did not finish."); } } Console.WriteLine("GainAuto went back to 'Off' after {0} frames", n); if (camera.GetSfncVersion() < sfnc2_0_0) // Handling for older cameras { Console.WriteLine("Final Gain = {0}", camera.Parameters[PLCamera.GainRaw].GetValue()); } else // Handling for newer cameras (using SFNC 2.0, e.g. USB3 Vision cameras) { Console.WriteLine("Final Gain = {0}", camera.Parameters[PLCamera.Gain].GetValue()); } }
static void AutoWhiteBalance(Camera camera) { // Check whether the Balance White Auto feature is available. if (!camera.Parameters[PLCamera.BalanceWhiteAuto].IsWritable) { Console.WriteLine("The Camera does not support balance white auto."); return; } // Maximize the grabbed area of interest (Image AOI). camera.Parameters[PLCamera.OffsetX].TrySetValue(camera.Parameters[PLCamera.OffsetX].GetMinimum()); camera.Parameters[PLCamera.OffsetY].TrySetValue(camera.Parameters[PLCamera.OffsetY].GetMinimum()); camera.Parameters[PLCamera.Width].SetValue(camera.Parameters[PLCamera.Width].GetMaximum()); camera.Parameters[PLCamera.Height].SetValue(camera.Parameters[PLCamera.Height].GetMaximum()); // Set the Auto Function ROI for white balace statistics. // We want to use ROI2 for gathering the statistics. if (camera.Parameters [regionSelector].IsWritable) { camera.Parameters [regionSelector].SetValue(regionSelectorValue1); camera.Parameters [autoFunctionAOIROIUseWhiteBalance].SetValue(false); // ROI 1 is not used for white balance control camera.Parameters [regionSelector].SetValue(regionSelectorValue2); camera.Parameters [autoFunctionAOIROIUseWhiteBalance].SetValue(true); // ROI 2 is used for white balance control } camera.Parameters[regionSelector].SetValue(regionSelectorValue2); camera.Parameters[regionSelectorOffsetX].SetValue(camera.Parameters [PLCamera.OffsetX].GetMinimum()); camera.Parameters[regionSelectorOffsetY].SetValue(camera.Parameters [PLCamera.OffsetY].GetMinimum()); camera.Parameters[regionSelectorWidth].SetValue(camera.Parameters[PLCamera.Width].GetMaximum()); camera.Parameters[regionSelectorHeight].SetValue(camera.Parameters[PLCamera.Height].GetMaximum()); Console.WriteLine("Trying 'BalanceWhiteAuto = Once'."); Console.WriteLine("Initial balance ratio:"); camera.Parameters[PLCamera.BalanceRatioSelector].SetValue(PLCamera.BalanceRatioSelector.Red); Console.Write("R = {0} ", camera.Parameters[balanceRatio].GetValue()); camera.Parameters[PLCamera.BalanceRatioSelector].SetValue(PLCamera.BalanceRatioSelector.Green); Console.Write("G = {0} ", camera.Parameters[balanceRatio].GetValue()); camera.Parameters[PLCamera.BalanceRatioSelector].SetValue(PLCamera.BalanceRatioSelector.Blue); Console.Write("B = {0} ", camera.Parameters[balanceRatio].GetValue()); camera.Parameters[PLCamera.BalanceWhiteAuto].SetValue(PLCamera.BalanceWhiteAuto.Once); // When the "once" mode of operation is selected, // the parameter values are automatically adjusted until the related image property // reaches the target value. After the automatic parameter value adjustment is complete, the auto // function will automatically be set to "off" and the new parameter value will be applied to the // subsequently grabbed images. int n = 0; while (camera.Parameters[PLCamera.BalanceWhiteAuto].GetValue() != PLCamera.BalanceWhiteAuto.Off) { IGrabResult result = camera.StreamGrabber.GrabOne(5000, TimeoutHandling.ThrowException); using (result) { // Image grabbed successfully? if (result.GrabSucceeded) { ImageWindow.DisplayImage(1, result); } } n++; //For demonstration purposes only. Wait until the image is shown. System.Threading.Thread.Sleep(100); //Make sure the loop is exited. if (n > 100) { throw new TimeoutException("The adjustment of auto white balance did not finish."); } } Console.WriteLine("BalanceWhiteAuto went back to 'Off' after {0} Frames", n); Console.WriteLine("Final balance ratio: "); camera.Parameters[PLCamera.BalanceRatioSelector].SetValue(PLCamera.BalanceRatioSelector.Red); Console.Write("R = {0} ", camera.Parameters[balanceRatio].GetValue()); camera.Parameters[PLCamera.BalanceRatioSelector].SetValue(PLCamera.BalanceRatioSelector.Green); Console.Write("G = {0} ", camera.Parameters[balanceRatio].GetValue()); camera.Parameters[PLCamera.BalanceRatioSelector].SetValue(PLCamera.BalanceRatioSelector.Blue); Console.Write("B = {0} ", camera.Parameters[balanceRatio].GetValue()); }
static void AutoExposureContinuous(Camera camera) { // Check whether the Exposure Auto feature is available. if (!camera.Parameters[PLCamera.ExposureAuto].IsWritable) { Console.WriteLine("The camera does not support Exposure Auto."); return; } // Maximize the grabbed image area of interest (Image AOI). camera.Parameters[PLCamera.OffsetX].TrySetValue(camera.Parameters[PLCamera.OffsetX].GetMinimum()); camera.Parameters[PLCamera.OffsetY].TrySetValue(camera.Parameters[PLCamera.OffsetY].GetMinimum()); camera.Parameters[PLCamera.Width].SetValue(camera.Parameters[PLCamera.Width].GetMaximum()); camera.Parameters[PLCamera.Height].SetValue(camera.Parameters[PLCamera.Height].GetMaximum()); // Set the Auto Function ROI for luminance statistics. // We want to use ROI1 for gathering the statistics. if (camera.Parameters[autoFunctionAOIROIUseBrightness].IsWritable) { camera.Parameters[regionSelector].SetValue(regionSelectorValue1); camera.Parameters[autoFunctionAOIROIUseBrightness].SetValue(true); // ROI 1 is used for brightness control camera.Parameters[regionSelector].SetValue(regionSelectorValue2); camera.Parameters[autoFunctionAOIROIUseBrightness].SetValue(false); // ROI 2 is not used for brightness control } camera.Parameters[regionSelector].SetValue(regionSelectorValue1); camera.Parameters[regionSelectorOffsetX].SetValue(camera.Parameters [PLCamera.OffsetX].GetMinimum()); camera.Parameters[regionSelectorOffsetY].SetValue(camera.Parameters [PLCamera.OffsetY].GetMinimum()); camera.Parameters[regionSelectorWidth].SetValue(camera.Parameters[PLCamera.Width].GetMaximum()); camera.Parameters[regionSelectorHeight].SetValue(camera.Parameters[PLCamera.Height].GetMaximum()); if (camera.GetSfncVersion() < sfnc2_0_0) // Handling for older cameras { // Set the target value for luminance control. The value is always expressed // as an 8 bit value regardless of the current pixel data output format, // i.e., 0 -> black, 255 -> white. camera.Parameters[PLCamera.AutoTargetValue].SetValue(80); } else // Handling for newer cameras (using SFNC 2.0, e.g. USB3 Vision cameras) { // Set the target value for luminance control. // A value of 0.3 means that the target brightness is 30 % of the maximum brightness of the raw pixel value read out from the sensor. // A value of 0.4 means 40 % and so forth. camera.Parameters[PLCamera.AutoTargetBrightness].SetValue(0.3); } // Try ExposureAuto = Continuous. Console.WriteLine("Trying 'ExposureAuto = Continuous'."); Console.WriteLine("Initial Exposure time = {0} us", camera.Parameters[exposureTime].GetValue()); camera.Parameters[PLCamera.ExposureAuto].SetValue(PLCamera.ExposureAuto.Continuous); // When "continuous" mode is selected, the parameter value is adjusted repeatedly while images are acquired. // Depending on the current frame rate, the automatic adjustments will usually be carried out for // every or every other image, unless the camera's microcontroller is kept busy by other tasks. // The repeated automatic adjustment will proceed until the "once" mode of operation is used or // until the auto function is set to "off", in which case the parameter value resulting from the latest // automatic adjustment will operate unless the value is manually adjusted. for (int n = 0; n < 20; n++) // For demonstration purposes, we will use only 20 images. { IGrabResult result = camera.StreamGrabber.GrabOne(5000, TimeoutHandling.ThrowException); using (result) { // Image grabbed successfully? if (result.GrabSucceeded) { ImageWindow.DisplayImage(1, result); } } //For demonstration purposes only. Wait until the image is shown. System.Threading.Thread.Sleep(100); } camera.Parameters[PLCamera.ExposureAuto].SetValue(PLCamera.ExposureAuto.Off); // Switch off Exposure Auto. Console.WriteLine("Final Exposure Time = {0} us", camera.Parameters[exposureTime].GetValue()); }
internal static void Main() { // The exit code of the sample application. int exitCode = 0; try { // Create a camera object selecting the first camera device found. // More constructors are available for selecting a specific camera device. using (Camera camera = new Camera()) { // Change default configuration to enable software triggering. camera.CameraOpened += Configuration.SoftwareTrigger; // Open the camera. camera.Open(); // Register image grabbed event to print frame info camera.StreamGrabber.ImageGrabbed += OnImageGrabbed; // DeviceVendorName, DeviceModelName, and DeviceFirmwareVersion are string parameters. Console.WriteLine("Camera Device Information"); Console.WriteLine("========================="); Console.WriteLine("Vendor : {0}", camera.Parameters[PLCamera.DeviceVendorName].GetValue()); Console.WriteLine("Model : {0}", camera.Parameters[PLCamera.DeviceModelName].GetValue()); Console.WriteLine("Firmware version : {0}", camera.Parameters[PLCamera.DeviceFirmwareVersion].GetValue()); Console.WriteLine(""); Console.WriteLine("Camera Device Settings"); Console.WriteLine("======================"); // Can the camera device be queried whether it is ready to accept the next frame trigger? if (camera.CanWaitForFrameTriggerReady) { // bool for testing if sequencer is available or not bool sequencerAvailable = false; if (camera.GetSfncVersion() < sfnc2_0_0) // Handling for older cameras { if (camera.Parameters[PLCamera.SequenceEnable].IsWritable) { sequencerAvailable = true; //Sequencer is available that is why it is true. // Disable the sequencer before changing parameters. // The parameters under control of the sequencer are locked // when the sequencer is enabled. For a list of parameters // controlled by the sequencer, see the camera User's Manual. camera.Parameters[PLCamera.SequenceEnable].SetValue(false); // Turn configuration mode on if (camera.Parameters[PLCamera.SequenceConfigurationMode].IsWritable) { camera.Parameters[PLCamera.SequenceConfigurationMode].SetValue(PLCamera.SequenceConfigurationMode.On); } // Maximize the image area of interest (Image AOI). camera.Parameters[PLCamera.OffsetX].TrySetValue(camera.Parameters[PLCamera.OffsetX].GetMinimum()); camera.Parameters[PLCamera.OffsetY].TrySetValue(camera.Parameters[PLCamera.OffsetY].GetMinimum()); camera.Parameters[PLCamera.Width].SetValue(camera.Parameters[PLCamera.Width].GetMaximum()); camera.Parameters[PLCamera.Height].SetValue(camera.Parameters[PLCamera.Height].GetMaximum()); // Set the pixel data format. camera.Parameters[PLCamera.PixelFormat].SetValue(PLCamera.PixelFormat.Mono8); // Set up sequence sets. // Configure how the sequence will advance. // 'Auto' refers to the auto sequence advance mode. // The advance from one sequence set to the next will occur automatically with each image acquired. // After the end of the sequence set cycle was reached a new sequence set cycle will start. camera.Parameters[PLCamera.SequenceAdvanceMode].SetValue(PLCamera.SequenceAdvanceMode.Auto); // Our sequence sets relate to three steps (0..2). // In each step we will increase the height of the Image AOI by one increment. camera.Parameters[PLCamera.SequenceSetTotalNumber].SetValue(3); long increments = (camera.Parameters[PLCamera.Height].GetMaximum() - camera.Parameters[PLCamera.Height].GetMinimum()) / camera.Parameters[PLCamera.Height].GetIncrement(); // Set the parameters for step 0; quarter height image. camera.Parameters[PLCamera.SequenceSetIndex].SetValue(0); camera.Parameters[PLCamera.Height].SetValue(camera.Parameters[PLCamera.Height].GetIncrement() * (increments / 4) + camera.Parameters[PLCamera.Height].GetMinimum()); camera.Parameters[PLCamera.SequenceSetStore].Execute(); // Set the parameters for step 1; half height image. camera.Parameters[PLCamera.SequenceSetIndex].SetValue(1); camera.Parameters[PLCamera.Height].SetValue(camera.Parameters[PLCamera.Height].GetIncrement() * (increments / 2) + camera.Parameters[PLCamera.Height].GetMinimum()); camera.Parameters[PLCamera.SequenceSetStore].Execute(); // Set the parameters for step 2; full height image. camera.Parameters[PLCamera.SequenceSetIndex].SetValue(2); camera.Parameters[PLCamera.Height].SetValue(camera.Parameters[PLCamera.Height].GetIncrement() * (increments) + camera.Parameters[PLCamera.Height].GetMinimum()); camera.Parameters[PLCamera.SequenceSetStore].Execute(); // Finish configuration if (camera.Parameters[PLCamera.SequenceConfigurationMode].IsWritable) { camera.Parameters[PLCamera.SequenceConfigurationMode].SetValue(PLCamera.SequenceConfigurationMode.Off); } // Enable the sequencer feature. // From here on you cannot change the sequencer settings anymore. camera.Parameters[PLCamera.SequenceEnable].SetValue(true); // Start the grabbing of countOfImagesToGrab images. camera.StreamGrabber.Start(countOfImagesToGrab); } else { sequencerAvailable = false; // Sequencer not available } } else // Handling for newer cameras (using SFNC 2.0, e.g. USB3 Vision cameras) { if (camera.Parameters[PLCamera.SequencerMode].IsWritable) { sequencerAvailable = true; // Disable the sequencer before changing parameters. // The parameters under control of the sequencer are locked // when the sequencer is enabled. For a list of parameters // controlled by the sequencer, see the camera User's Manual. camera.Parameters[PLCamera.SequencerMode].SetValue(PLCamera.SequencerMode.Off); // Maximize the image area of interest (Image AOI). camera.Parameters[PLCamera.OffsetX].TrySetValue(camera.Parameters[PLCamera.OffsetX].GetMinimum()); camera.Parameters[PLCamera.OffsetY].TrySetValue(camera.Parameters[PLCamera.OffsetY].GetMinimum()); camera.Parameters[PLCamera.Width].SetValue(camera.Parameters[PLCamera.Width].GetMaximum()); camera.Parameters[PLCamera.Height].SetValue(camera.Parameters[PLCamera.Height].GetMaximum()); // Set the pixel data format. // This parameter may be locked when the sequencer is enabled. camera.Parameters[PLCamera.PixelFormat].SetValue(PLCamera.PixelFormat.Mono8); // Set up sequence sets and turn sequencer configuration mode on. camera.Parameters[PLCamera.SequencerConfigurationMode].SetValue(PLCamera.SequencerConfigurationMode.On); // Configure how the sequence will advance. // The sequence sets relate to three steps (0..2). // In each step, the height of the Image AOI is doubled. long increments = (camera.Parameters[PLCamera.Height].GetMaximum() - camera.Parameters[PLCamera.Height].GetMinimum()) / camera.Parameters[PLCamera.Height].GetIncrement(); long initialSet = camera.Parameters[PLCamera.SequencerSetSelector].GetMinimum(); long incSet = camera.Parameters[PLCamera.SequencerSetSelector].GetIncrement(); long curSet = initialSet; // Set the parameters for step 0; quarter height image. camera.Parameters[PLCamera.SequencerSetSelector].SetValue(initialSet); { // valid for all sets // reset on software signal 1; camera.Parameters[PLCamera.SequencerPathSelector].SetValue(0); camera.Parameters[PLCamera.SequencerSetNext].SetValue(initialSet); camera.Parameters[PLCamera.SequencerTriggerSource].SetValue(PLCamera.SequencerTriggerSource.SoftwareSignal1); // advance on Frame Start camera.Parameters[PLCamera.SequencerPathSelector].SetValue(1); camera.Parameters[PLCamera.SequencerTriggerSource].SetValue(PLCamera.SequencerTriggerSource.FrameStart); } camera.Parameters[PLCamera.SequencerSetNext].SetValue(curSet + incSet); // Set the parameters for step 0; quarter height image. camera.Parameters[PLCamera.Height].SetValue(camera.Parameters[PLCamera.Height].GetIncrement() * (increments / 4) + camera.Parameters[PLCamera.Height].GetMinimum()); camera.Parameters[PLCamera.SequencerSetSave].Execute(); // Set the parameters for step 1; half height image. curSet += incSet; camera.Parameters[PLCamera.SequencerSetSelector].SetValue(curSet); // advance on Frame Start to next set camera.Parameters[PLCamera.SequencerSetNext].SetValue(curSet + incSet); camera.Parameters[PLCamera.Height].SetValue(camera.Parameters[PLCamera.Height].GetIncrement() * (increments / 2) + camera.Parameters[PLCamera.Height].GetMinimum()); camera.Parameters[PLCamera.SequencerSetSave].Execute(); // Set the parameters for step 2; full height image. curSet += incSet; camera.Parameters[PLCamera.SequencerSetSelector].SetValue(curSet); // advance on Frame End to initial set, camera.Parameters[PLCamera.SequencerSetNext].SetValue(initialSet); // terminates sequence definition // full height camera.Parameters[PLCamera.Height].SetValue(camera.Parameters[PLCamera.Height].GetIncrement() * increments + camera.Parameters[PLCamera.Height].GetMinimum()); camera.Parameters[PLCamera.SequencerSetSave].Execute(); // Enable the sequencer feature. // From here on you cannot change the sequencer settings anymore. camera.Parameters[PLCamera.SequencerConfigurationMode].SetValue(PLCamera.SequencerConfigurationMode.Off); camera.Parameters[PLCamera.SequencerMode].SetValue(PLCamera.SequencerMode.On); // Start the grabbing of countOfImagesToGrab images. camera.StreamGrabber.Start(countOfImagesToGrab); } else { sequencerAvailable = false; // Sequencer not available } } if (sequencerAvailable) { IGrabResult result; // Camera.StopGrabbing() is called automatically by the RetrieveResult() method // when countOfImagesToGrab images have been retrieved. while (camera.StreamGrabber.IsGrabbing) { // Execute the software trigger. Wait up to 1000 ms for the camera to be ready for trigger. if (camera.WaitForFrameTriggerReady(1000, TimeoutHandling.ThrowException)) { camera.ExecuteSoftwareTrigger(); // Wait for an image and then retrieve it. A timeout of 5000 ms is used. result = camera.StreamGrabber.RetrieveResult(5000, TimeoutHandling.ThrowException); using (result) { // Image grabbed successfully? if (result.GrabSucceeded) { // Display the grabbed image. ImageWindow.DisplayImage(1, result); } else { Console.WriteLine("Error code:{0} Error description:{1}", result.ErrorCode, result.ErrorDescription); } } } // Wait for user input. Console.WriteLine("Press Enter to continue."); while (camera.StreamGrabber.IsGrabbing && Console.ReadKey().Key != ConsoleKey.Enter) { ; } } // Disable the sequencer. if (camera.GetSfncVersion() < sfnc2_0_0) // Handling for older cameras { camera.Parameters[PLCamera.SequenceEnable].SetValue(false); } else // Handling for newer cameras (using SFNC 2.0, e.g. USB3 Vision cameras) { camera.Parameters[PLCamera.SequencerMode].SetValue(PLCamera.SequencerMode.Off); } } else { Console.WriteLine("The sequencer feature is not available for this camera."); } } else { Console.WriteLine("This sample can only be used with cameras that can be queried whether they are ready to accept the next frame trigger."); } // Close the camera. camera.Close(); } } catch (Exception e) { // Error handling. Console.Error.WriteLine("Exception: {0}", e.Message); exitCode = 1; } // Comment the following two lines to disable waiting on exit. Console.Error.WriteLine("\nPress enter to exit."); Console.ReadLine(); Environment.Exit(exitCode); }
internal static void Main() { // The exit code of the sample application. int exitCode = 0; try { // Create a camera object that selects the first camera device found. // More constructors are available for selecting a specific camera device. // For multicast only look for GigE cameras here. using (Camera camera = new Camera(DeviceType.GigE, CameraSelectionStrategy.FirstFound)) { // Print the model name of the camera. Console.WriteLine("Using camera {0}.", camera.CameraInfo[CameraInfoKey.ModelName]); String deviceType = camera.CameraInfo[CameraInfoKey.DeviceType]; Console.WriteLine("=========="); Console.WriteLine("{0} Camera", deviceType); Console.WriteLine("=========="); camera.StreamGrabber.ImageGrabbed += OnImageGrabbed; camera.StreamGrabber.ImageGrabbed += OnImageSkipped; // Get the Key from the user for selecting the mode Console.Write("Start multicast sample in (c)ontrol or in (m)onitor mode? (c/m) "); ConsoleKeyInfo keyPressed = Console.ReadKey(); switch (keyPressed.KeyChar) { // The default configuration must be removed when monitor mode is selected // because the monitoring application is not allowed to modify any parameter settings. case 'm': case 'M': // Monitor mode selected. Console.WriteLine("\nIn Monitor mode"); // Set MonitorModeActive to true to act as monitor camera.Parameters [PLCameraInstance.MonitorModeActive].SetValue(true); // Set monitor mode // Open the camera. camera.Open(); // Select transmission type. If the camera is already controlled by another application // and configured for multicast, the active camera configuration can be used // (IP Address and Port will be set automatically). camera.Parameters[PLGigEStream.TransmissionType].TrySetValue(PLGigEStream.TransmissionType.UseCameraConfig); // Alternatively, the stream grabber could be explicitly set to "multicast"... // In this case, the IP Address and the IP port must also be set. // //camera.Parameters[PLGigEStream.TransmissionType].SetValue(PLGigEStream.TransmissionType.Multicast); //camera.Parameters[PLGigEStream.DestinationAddr].SetValue("239.0.0.1"); //camera.Parameters[PLGigEStream.DestinationPort].SetValue(49152); if ((camera.Parameters[PLGigEStream.DestinationAddr].GetValue() != "0.0.0.0") && (camera.Parameters[PLGigEStream.DestinationPort].GetValue() != 0)) { camera.StreamGrabber.Start(countOfImagesToGrab); } else { throw new Exception("Failed to open stream grabber (monitor mode): The acquisition is not yet started by the controlling application. Start the controlling application before starting the monitor application."); } break; case 'c': case 'C': // Controlling mode selected. Console.WriteLine("\nIn Control mode"); // Open the camera. camera.Open(); // Set transmission type to "multicast"... // In this case, the IP Address and the IP port must also be set. camera.Parameters[PLGigEStream.TransmissionType].SetValue(PLGigEStream.TransmissionType.Multicast); //camera.Parameters[PLGigEStream.DestinationAddr].SetValue("239.0.0.1"); //camera.Parameters[PLGigEStream.DestinationPort].SetValue(49152); // Maximize the image area of interest (Image AOI). camera.Parameters[PLGigECamera.OffsetX].TrySetValue(camera.Parameters[PLGigECamera.OffsetX].GetMinimum()); camera.Parameters[PLGigECamera.OffsetY].TrySetValue(camera.Parameters[PLGigECamera.OffsetY].GetMinimum()); camera.Parameters[PLGigECamera.Width].SetValue(camera.Parameters[PLGigECamera.Width].GetMaximum()); camera.Parameters[PLGigECamera.Height].SetValue(camera.Parameters[PLGigECamera.Height].GetMaximum()); // Set the pixel data format. camera.Parameters[PLGigECamera.PixelFormat].SetValue(PLGigECamera.PixelFormat.Mono8); camera.StreamGrabber.Start(); break; default: throw new NotSupportedException("Invalid mode selected."); } IGrabResult grabResult; // Camera.StopGrabbing() is called automatically by the RetrieveResult() method // when countOfImagesToGrab images have been retrieved in monitor mode // or when a key is pressed and the camera object is destroyed. Console.WriteLine("Press any key to quit FrameGrabber..."); while (!Console.KeyAvailable && camera.StreamGrabber.IsGrabbing) { grabResult = camera.StreamGrabber.RetrieveResult(5000, TimeoutHandling.ThrowException); using (grabResult) { // Image grabbed successfully? if (grabResult.GrabSucceeded) { // Display the image ImageWindow.DisplayImage(1, grabResult); // The grab result could now be processed here. } else { Console.WriteLine("Error: {0} {1}", grabResult.ErrorCode, grabResult.ErrorDescription); } } } camera.Close(); } } catch (Exception e) { // Error handling Console.Error.WriteLine("\nException: {0}", e.Message); exitCode = 1; } finally { // Comment the following two lines to disable waiting on exit. Console.Error.WriteLine("\nPress enter to exit."); Console.ReadLine(); } Environment.Exit(exitCode); }
internal static void Main() { // The exit code of the sample application. int exitCode = 0; 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. 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(); // Set buffer factory before starting the stream grabber because allocation // happens there. MyBufferFactory myFactory = new MyBufferFactory(); camera.StreamGrabber.BufferFactory = myFactory; // 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(5000, TimeoutHandling.ThrowException); using (grabResult) { // Image grabbed successfully? if (grabResult.GrabSucceeded) { // Access the image data. Console.WriteLine("SizeX: {0}", grabResult.Width); Console.WriteLine("SizeY: {0}", grabResult.Height); // Normally we would have a byte array in the pixel data. // However we are using the buffer factory here which allocates // ushort arrays. ushort[] buffer = grabResult.PixelData as ushort[]; Console.WriteLine("First value of pixel data: {0}", buffer[0]); Console.WriteLine(""); // Display the grabbed image. ImageWindow.DisplayImage(0, grabResult); } else { Console.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) { Console.Error.WriteLine("Exception: {0}", e.Message); exitCode = 1; } finally { // Comment the following two lines to disable waiting on exit. Console.Error.WriteLine("\nPress enter to exit."); Console.ReadLine(); } Environment.Exit(exitCode); }
internal static void Main() { // Time to wait for the user to disconnect the camera device. const int cTimeOutMs = 60000; // The exit code of the sample application. int exitCode = 0; 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. 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; // For demonstration purposes, only add an event handler for connection loss. camera.ConnectionLost += OnConnectionLost; // Open the connection to the camera device. camera.Open(); ///////////////// Don't single step beyond this line when using GigE cameras (see comments above) /////////////////////////////// // Before testing the callbacks, we manually set the heartbeat timeout to a short value when using GigE cameras. // For debug versions, the heartbeat timeout has been set to 5 minutes, so it would take up to 5 minutes // until device removal is detected. camera.Parameters[PLTransportLayer.HeartbeatTimeout].TrySetValue(1000, IntegerValueCorrection.Nearest); // 1000 ms timeout // Start the grabbing. camera.StreamGrabber.Start(); // Start the timeout timer. Console.WriteLine("Please disconnect the device. (Timeout {0}s)", cTimeOutMs / 1000.0); Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); // Grab and display images until timeout. while (camera.StreamGrabber.IsGrabbing && stopWatch.ElapsedMilliseconds < cTimeOutMs) { try { // 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) { // Display the grabbed image. ImageWindow.DisplayImage(0, grabResult); } } } catch (Exception) { // An exception occurred. Is it because the camera device has been physically removed? // Known issue: Wait until the system safely detects a possible removal. System.Threading.Thread.Sleep(1000); if (!camera.IsConnected) { // Yes, the camera device has been physically removed. Console.WriteLine("The camera device has been removed. Please reconnect. (Timeout {0}s)", cTimeOutMs / 1000.0); // Close the camera object to close underlying resources used for the previous connection. camera.Close(); // Try to re-establish a connection to the camera device until timeout. // Reopening the camera triggers the above registered Configuration.AcquireContinous. // Therefore, the camera is parameterized correctly again. camera.Open(cTimeOutMs, TimeoutHandling.ThrowException); // Due to unplugging the camera, settings have changed, e.g. the heartbeat timeout value for GigE cameras. // After the camera has been reconnected, all settings must be restored. This can be done in the CameraOpened // event as shown for the Configuration.AcquireContinous. camera.Parameters[PLTransportLayer.HeartbeatTimeout].TrySetValue(1000, IntegerValueCorrection.Nearest); // Restart grabbing. camera.StreamGrabber.Start(); // Restart the timeout timer. Console.WriteLine("Camera reconnected. You may disconnect the camera device again (Timeout {0}s)", cTimeOutMs / 1000.0); stopWatch.Restart(); } else { throw; } } } } } catch (Exception e) { Console.Error.WriteLine("Exception: {0}", e.Message); exitCode = 1; } finally { // Comment the following two lines to disable waiting on exit. Console.Error.WriteLine("\nPress enter to exit."); Console.ReadLine(); } Environment.Exit(exitCode); }
internal static void Main() { const int c_countOfImagesToGrab = 10; int exitCode = 0; try { // Create a camera object and select the first camera device found. using (EventCamera eventCamera = new EventCamera()) { // Register the ExposureEnd event with the event handler member. eventCamera.Configure(); // Register an event handler object with an anonymous method. The object is important if you want to unregister this event. EventHandler <ParameterChangedEventArgs> handlerTimestamp = (s, e) => { Console.WriteLine("Anonymous method: TimeStamp {0}", e.Parameter.ToString()); }; eventCamera.Parameters[eventCamera.ExposureEndTimestamp].ParameterChanged += handlerTimestamp; eventCamera.StreamGrabber.Start(c_countOfImagesToGrab); while (eventCamera.StreamGrabber.IsGrabbing) { if (eventCamera.WaitForFrameTriggerReady(1000, TimeoutHandling.ThrowException)) { eventCamera.ExecuteSoftwareTrigger(); } // Wait for an image and then retrieve it. A timeout of 5000 ms is used. IGrabResult grabResult = eventCamera.StreamGrabber.RetrieveResult(5000, TimeoutHandling.ThrowException); using (grabResult) { // Image grabbed successfully? if (grabResult.GrabSucceeded) { ImageWindow.DisplayImage(0, grabResult); } else { Console.WriteLine("Error: {0} {1}", grabResult.ErrorCode, grabResult.ErrorDescription); } } } // If events are not required anymore, you should unregister the event handlers. eventCamera.Parameters[eventCamera.ExposureEndDataName].ParameterChanged -= eventCamera.OnEventExposureEndData; eventCamera.Parameters[eventCamera.ExposureEndTimestamp].ParameterChanged -= handlerTimestamp; } } catch (Exception e) { Console.Error.WriteLine("Exception: {0}", e.Message); exitCode = 1; } finally { // Comment the following two lines to disable waiting on exit. Console.Error.WriteLine("\nPress enter to exit."); Console.ReadLine(); } Environment.Exit(exitCode); }
internal static void Main() { // The exit code of the sample application. int exitCode = 0; 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. 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(); Configure(camera); // Set the pixel format to one from a list of ones compatible with this example string[] pixelFormats = new string[] { PLCamera.PixelFormat.YUV422_YUYV_Packed, PLCamera.PixelFormat.YCbCr422_8, PLCamera.PixelFormat.BayerBG8, PLCamera.PixelFormat.BayerRG8, PLCamera.PixelFormat.BayerGR8, PLCamera.PixelFormat.BayerGB8, PLCamera.PixelFormat.Mono8 }; camera.Parameters[PLCamera.PixelFormat].SetValue(pixelFormats); // Disable test image generator if available camera.Parameters[PLCamera.TestImageSelector].TrySetValue(PLCamera.TestImageSelector.Off); camera.Parameters[PLCamera.TestPattern].TrySetValue(PLCamera.TestPattern.Off); // Set the Auto Function ROI for luminance and white balance statistics. // We want to use ROI2 for gathering the statistics. if (camera.Parameters[regionSelector].IsWritable) { camera.Parameters[regionSelector].SetValue(regionSelectorValue1); camera.Parameters[autoFunctionAOIROIUseBrightness].SetValue(true); // ROI 1 is used for brightness control camera.Parameters[autoFunctionAOIROIUseWhiteBalance].SetValue(true); // ROI 1 is used for white balance control } camera.Parameters[regionSelector].SetValue(regionSelectorValue1); camera.Parameters[regionSelectorOffsetX].SetValue(camera.Parameters[PLCamera.OffsetX].GetMinimum()); camera.Parameters[regionSelectorOffsetY].SetValue(camera.Parameters[PLCamera.OffsetY].GetMinimum()); camera.Parameters[regionSelectorWidth].SetValue(camera.Parameters[PLCamera.Width].GetMaximum()); camera.Parameters[regionSelectorHeight].SetValue(camera.Parameters[PLCamera.Height].GetMaximum()); if (camera.GetSfncVersion() < sfnc2_0_0) // Handling for older cameras { camera.Parameters[PLCamera.ProcessedRawEnable].TrySetValue(true); camera.Parameters[PLCamera.GammaEnable].TrySetValue(true); camera.Parameters[PLCamera.GammaSelector].TrySetValue(PLCamera.GammaSelector.sRGB); camera.Parameters[PLCamera.AutoTargetValue].TrySetValue(80); camera.Parameters[PLCamera.AutoFunctionProfile].TrySetValue(PLCamera.AutoFunctionProfile.GainMinimum); camera.Parameters[PLCamera.AutoGainRawLowerLimit].TrySetToMinimum(); camera.Parameters[PLCamera.AutoGainRawUpperLimit].TrySetToMaximum(); camera.Parameters[PLCamera.AutoExposureTimeAbsLowerLimit].TrySetToMinimum(); camera.Parameters[PLCamera.AutoExposureTimeAbsUpperLimit].TrySetToMaximum(); } else // Handling for newer cameras (using SFNC 2.0, e.g. USB3 Vision cameras) { camera.Parameters[PLCamera.AutoTargetBrightness].TrySetValue(0.3); camera.Parameters[PLCamera.AutoFunctionProfile].TrySetValue(PLCamera.AutoFunctionProfile.MinimizeGain); camera.Parameters[PLCamera.AutoGainLowerLimit].TrySetToMinimum(); camera.Parameters[PLCamera.AutoGainUpperLimit].TrySetToMaximum(); double maxExposure = camera.Parameters[PLCamera.AutoExposureTimeUpperLimit].GetMaximum(); // Reduce upper limit to one second for this example if (maxExposure > 1000000) { maxExposure = 1000000; } camera.Parameters[PLCamera.AutoExposureTimeUpperLimit].TrySetValue(maxExposure); } // Set all auto functions to once in this example camera.Parameters[PLCamera.GainSelector].TrySetValue(PLCamera.GainSelector.All); camera.Parameters[PLCamera.GainAuto].TrySetValue(PLCamera.GainAuto.Once); camera.Parameters[PLCamera.ExposureAuto].TrySetValue(PLCamera.ExposureAuto.Once); camera.Parameters[PLCamera.BalanceWhiteAuto].TrySetValue(PLCamera.BalanceWhiteAuto.Once); if (camera.GetSfncVersion() < sfnc2_0_0) // Handling for older cameras { camera.Parameters[PLCamera.LightSourceSelector].TrySetValue(PLCamera.LightSourceSelector.Daylight); } else // Handling for newer cameras (using SFNC 2.0, e.g. USB3 Vision cameras) { camera.Parameters[PLCamera.LightSourcePreset].TrySetValue(PLCamera.LightSourcePreset.Daylight5000K); } camera.StreamGrabber.Start(); for (int n = 0; n < 20; n++) // For demonstration purposes, we will grab "only" 20 images. { IGrabResult result = camera.StreamGrabber.RetrieveResult(5000, TimeoutHandling.ThrowException); using (result) { // Image grabbed successfully? if (result.GrabSucceeded) { ImageWindow.DisplayImage(1, result); } } //For demonstration purposes only. Wait until the image is shown. System.Threading.Thread.Sleep(100); } // Close the camera. camera.Close(); } } catch (Exception e) { // Error handling. Console.Error.WriteLine("Exception: {0}", e.Message); exitCode = 1; } finally { // Comment the following two lines to disable waiting on exit. Console.Error.WriteLine("\nPress enter to exit."); Console.ReadLine(); } Environment.Exit(exitCode); }
internal static void Main() { // The exit code of the sample application. int exitCode = 0; 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. Console.WriteLine("Using camera {0}.", camera.CameraInfo [CameraInfoKey.ModelName]); // Set the acquisition mode to single frame acquisition when the camera is opened. camera.CameraOpened += Configuration.AcquireSingleFrame; // Open the connection to the camera device. camera.Open(); // Remember the original compression mode. string oldCompressionMode = camera.Parameters [PLCamera.ImageCompressionMode].GetValue(); // Set the compression mode to BaslerCompressionBeyond if available. camera.Parameters [PLCamera.ImageCompressionMode].SetValue(PLCamera.ImageCompressionMode.BaslerCompressionBeyond); // After enabling the compression, we can read the compression rate option. string oldCompressionRateOption = camera.Parameters [PLCamera.ImageCompressionRateOption].GetValue(); // Configure lossless compression. camera.Parameters [PLCamera.ImageCompressionRateOption].SetValue(PLCamera.ImageCompressionRateOption.Lossless); // Create the decompressor and initialize it with the camera. using (ImageDecompressor decompressor = new ImageDecompressor(camera)) { // Wait max. 5000ms for a new image. IGrabResult grabResult = camera.StreamGrabber.GrabOne(5000); using (grabResult) { if (grabResult.GrabSucceeded) { // Fetch compression info and check whether the image was compressed by the camera. CompressionInfo compressionInfo = new CompressionInfo(); if (ImageDecompressor.GetCompressionInfo(ref compressionInfo, grabResult)) { // Print content of CompressionInfo. PrintCompressionInfo(compressionInfo); // Check if we have a valid compressed image if (compressionInfo.CompressionStatus == CompressionStatus.Ok) { // Show compression ratio. Console.WriteLine("\nTransferred compressed payload: {0}", grabResult.PayloadSize); Console.WriteLine("Compression ratio: {0:N2}%", (Single)grabResult.PayloadSize / (Single)compressionInfo.DecompressedPayloadSize * 100.0); // Create buffer for storing the decompressed image. var myBuffer = new Byte [compressionInfo.DecompressedImageSize]; // Decompress the image. decompressor.DecompressImage(myBuffer, grabResult); // Show the image. ImageWindow.DisplayImage(1, myBuffer, compressionInfo.PixelType, compressionInfo.Width, compressionInfo.Height, 0, ImageOrientation.TopDown); } else { Console.WriteLine("There was an error while the camera was compressing the image."); } } } else { // Somehow image grabbing failed. Console.WriteLine("Error: {0} {1}", grabResult.ErrorCode, grabResult.ErrorDescription); } } Console.WriteLine("\n\n--- Switching to Fix Ratio compression ---"); // Take another picture with lossy compression (if available). if (camera.Parameters [PLCamera.ImageCompressionRateOption].TrySetValue(PLCamera.ImageCompressionRateOption.FixRatio)) { // After changing the compression parameters, the decompressor MUST be reconfigured. decompressor.SetCompressionDescriptor(camera); // Wait max. 5000ms for a new image. grabResult = camera.StreamGrabber.GrabOne(5000); using (grabResult) { if (grabResult.GrabSucceeded) { // Fetch compression info and check whether the image was compressed by the camera. CompressionInfo compressionInfo = new CompressionInfo(); if (ImageDecompressor.GetCompressionInfo(ref compressionInfo, grabResult)) { // Print content of CompressionInfo. PrintCompressionInfo(compressionInfo); // Check if we have a valid compressed image if (compressionInfo.CompressionStatus == CompressionStatus.Ok) { // Show compression ratio. Console.WriteLine("\nTransferred compressed payload: {0}", grabResult.PayloadSize); Console.WriteLine("Compression ratio: {0:N2}%", (Single)grabResult.PayloadSize / (Single)compressionInfo.DecompressedPayloadSize * 100.0); // Create buffer for storing the decompressed image. var myBuffer = new Byte [compressionInfo.DecompressedImageSize]; // Decompress the image. decompressor.DecompressImage(myBuffer, grabResult); // Show the image. ImageWindow.DisplayImage(2, myBuffer, compressionInfo.PixelType, compressionInfo.Width, compressionInfo.Height, 0, ImageOrientation.TopDown); } else { Console.WriteLine("There was an error while the camera was compressing the image."); } } } else { // Somehow image grabbing failed. Console.WriteLine("Error: {0} {1}", grabResult.ErrorCode, grabResult.ErrorDescription); } } } else { Console.WriteLine("With this setting the camera does not support the \"FixRatio\" Image Compression Rate Option."); } } // restore the old camera settings camera.Parameters [PLCamera.ImageCompressionRateOption].SetValue(oldCompressionRateOption); camera.Parameters [PLCamera.ImageCompressionMode].SetValue(oldCompressionMode); camera.Close(); } } catch (InvalidOperationException e) { Console.Error.WriteLine("Exception: Camera does not support Compression. {0}", e.Message); exitCode = 1; } catch (Exception e) { Console.Error.WriteLine("Exception: {0}", e.Message); exitCode = 1; } finally { // Comment the following two lines to disable waiting on exit. Console.Error.WriteLine("\nPress enter to exit."); Console.ReadLine(); } Environment.Exit(exitCode); }
internal static void Main() { // The exit code of the sample application. int exitCode = 0; 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. 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); // 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(5000, TimeoutHandling.ThrowException); using (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); } else { Console.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) { Console.Error.WriteLine("Exception: {0}", e.Message); exitCode = 1; } finally { // Comment the following two lines to disable waiting on exit. Console.Error.WriteLine("\nPress enter to exit."); Console.ReadLine(); } Environment.Exit(exitCode); }
internal static void Main() { // The number of images to grab. const int c_countOfImagesToGrab = 10; // The exit code of the sample application. int exitCode = 0; 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. 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. while (camera.StreamGrabber.IsGrabbing) { // 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) { // Display the grabbed image. ImageWindow.DisplayImage(0, grabResult); // Check to see if a buffer containing chunk data has been received. if (PayloadType.ChunkData != grabResult.PayloadTypeValue) { throw new Exception("Unexpected payload type received."); } // Because we have enabled the CRC Checksum feature, we can check // the integrity of the buffer. // Note: Enabling the CRC Checksum feature is not a prerequisite for using chunks. // Chunks can also be handled when the CRC Checksum feature is disabled. if (grabResult.HasCRC && grabResult.CheckCRC() == false) { throw new Exception("Image was damaged!"); } // Access the chunk data attached to the result. // Before accessing the chunk data, you should check to see // if the chunk is readable. If it is readable, the buffer // contains the requested chunk data. if (grabResult.ChunkData[PLChunkData.ChunkTimestamp].IsReadable) { Console.WriteLine("ChunkData: TimeStamp = {0}", grabResult.ChunkData[PLChunkData.ChunkTimestamp]); } else { Console.WriteLine("ChunkData: No TimeStamp"); } // Print the frame counter value. if (grabResult.ChunkData[PLChunkData.ChunkFramecounter].IsReadable) { Console.WriteLine("ChunkData: FrameCounter = {0}", grabResult.ChunkData[PLChunkData.ChunkFramecounter]); } // Print the generic counter value (USB camera devices). else if (grabResult.ChunkData[PLChunkData.ChunkCounterSelector].TrySetValue(PLChunkData.ChunkCounterSelector.Counter1) && grabResult.ChunkData[PLChunkData.ChunkCounterValue].IsReadable ) { Console.WriteLine("ChunkData: FrameCounter = {0}", grabResult.ChunkData[PLChunkData.ChunkCounterValue]); } Console.WriteLine(""); } else { Console.WriteLine("Error: {0} {1}", grabResult.ErrorCode, grabResult.ErrorDescription); } } } camera.Parameters[PLCamera.ChunkModeActive].SetValue(false); } } catch (Exception e) { Console.Error.WriteLine("Exception: {0}", e.Message); exitCode = 1; } finally { // Comment the following two lines to disable waiting on exit. Console.Error.WriteLine("\nPress enter to exit."); Console.ReadLine(); } Environment.Exit(exitCode); }