Ejemplo n.º 1
0
        ///////////////////////////////////////////////////////////////////////////////////////////////
        /// <summary>
        /// Allocates a MIL application, system, display, image buffer and digitizer (if available).
        /// </summary>
        public void Allocate()
        {
            // Allocate a MIL application.
            MIL.MappAlloc(MIL.M_NULL, MIL.M_DEFAULT, ref _appId);

            // Allocate a MIL system.
            MIL.MsysAlloc(MIL.M_DEFAULT, "M_DEFAULT", MIL.M_DEFAULT, MIL.M_DEFAULT, ref _sysId);

            // Allocate a MIL display.
            MIL.MdispAlloc(_sysId, MIL.M_DEFAULT, "M_DEFAULT", MIL.M_WINDOWED, ref _dispId);

            // Set default values for the image buffer in case no digitizer can be allocated.
            MIL_INT bufferSizeX     = DEFAULT_IMAGE_SIZE_X;
            MIL_INT bufferSizeY     = DEFAULT_IMAGE_SIZE_Y;
            MIL_INT bufferSizeBand  = DEFAULT_IMAGE_SIZE_BAND;
            long    imageAttributes = MIL.M_IMAGE | MIL.M_DISP | MIL.M_PROC;

            // Inquire the number of digitizers for the system.
            MIL_INT numberOfDigitizers = MIL.MsysInquire(_sysId, MIL.M_DIGITIZER_NUM, MIL.M_NULL);

            if (numberOfDigitizers > 0)
            {
                // Allocate a digitizer.
                MIL.MdigAlloc(_sysId, MIL.M_DEFAULT, "M_DEFAULT", MIL.M_DEFAULT, ref _digId);

                // Inquire the digitizer to determine the image buffer size.
                bufferSizeBand = MIL.MdigInquire(_digId, MIL.M_SIZE_BAND, MIL.M_NULL);
                bufferSizeX    = MIL.MdigInquire(_digId, MIL.M_SIZE_X, MIL.M_NULL);
                bufferSizeY    = MIL.MdigInquire(_digId, MIL.M_SIZE_Y, MIL.M_NULL);

                // Add the M_GRAB attibute to the image buffer.
                imageAttributes |= MIL.M_GRAB;
            }

            // Notify the UI that grabbing options have changed.
            RaisePropertyChangedEvent("CanStartGrab");
            RaisePropertyChangedEvent("CanStopGrab");

            // Allocate the image buffer.
            MIL.MbufAllocColor(_sysId, bufferSizeBand, bufferSizeX, bufferSizeY, 8 + MIL.M_UNSIGNED, imageAttributes, ref _bufId);

            // Notify the UI that the buffer size changed.
            RaisePropertyChangedEvent("BufferSizeX");
            RaisePropertyChangedEvent("BufferSizeY");

            // Fill the buffer with a default message.
            FillImageBuffer(bufferSizeX, bufferSizeY);
        }
Ejemplo n.º 2
0
        const int HALF_LUMINANCE  = 128;            // All colors have half luminance.

        // Creates a color display LUT to show defects in red.
        static void SetupColorDisplay(MIL_ID MilSystem, MIL_ID MilDisplay, MIL_INT SizeBit)
        {
            MIL_ID  MilRampLut1Band   = MIL.M_NULL; // LUT containing hue values.
            MIL_ID  MilRampLut3Band   = MIL.M_NULL; // RGB LUT used by display.
            MIL_ID  MilColorImage     = MIL.M_NULL; // Image used for HSL to RGB conversion.
            MIL_INT DefectGrayLevel   = 0;          // Gray level under which all is red.
            MIL_INT ExpectedGrayLevel = 0;          // Gray level over which all is blue.
            MIL_INT NbGrayLevels;

            // Number of possible gray levels in corrected depth map.
            NbGrayLevels = (MIL_INT)(1 << (int)SizeBit);

            // Allocate 1-band LUT that will contain hue values.
            MIL.MbufAlloc1d(MilSystem, NbGrayLevels, 8 + MIL.M_UNSIGNED, MIL.M_LUT, ref MilRampLut1Band);

            // Compute limit gray values.
            DefectGrayLevel   = (MIL_INT)((EXPECTED_HEIGHT - SATURATED_DEFECT) * SCALE_FACTOR);
            ExpectedGrayLevel = (MIL_INT)(EXPECTED_HEIGHT * SCALE_FACTOR);

            // Create hue values for each possible gray level.
            MIL.MgenLutRamp(MilRampLut1Band, 0, RED_HUE, DefectGrayLevel, RED_HUE);
            MIL.MgenLutRamp(MilRampLut1Band, DefectGrayLevel, RED_HUE, ExpectedGrayLevel, BLUE_HUE);
            MIL.MgenLutRamp(MilRampLut1Band, ExpectedGrayLevel, BLUE_HUE, NbGrayLevels - 1, BLUE_HUE);

            // Create a HSL image buffer.
            MIL.MbufAllocColor(MilSystem, 3, NbGrayLevels, 1, 8 + MIL.M_UNSIGNED, MIL.M_IMAGE, ref MilColorImage);
            MIL.MbufClear(MilColorImage, MIL.M_RGB888(0, FULL_SATURATION, HALF_LUMINANCE));

            // Set its H band (hue) to the LUT contents and convert the image to RGB.
            MIL.MbufCopyColor2d(MilRampLut1Band, MilColorImage, 0, 0, 0, 0, 0, 0, NbGrayLevels, 1);
            MIL.MimConvert(MilColorImage, MilColorImage, MIL.M_HSL_TO_RGB);

            // Create RGB LUT to give to display and copy image contents.
            MIL.MbufAllocColor(MilSystem, 3, NbGrayLevels, 1, 8 + MIL.M_UNSIGNED, MIL.M_LUT, ref MilRampLut3Band);
            MIL.MbufCopy(MilColorImage, MilRampLut3Band);

            // Associates LUT to display.
            MIL.MdispLut(MilDisplay, MilRampLut3Band);

            // Free all allocations.
            MIL.MbufFree(MilRampLut1Band);
            MIL.MbufFree(MilRampLut3Band);
            MIL.MbufFree(MilColorImage);
        }
Ejemplo n.º 3
0
        //*****************************************************************************
        // Processing initialization function.
        //*****************************************************************************
        private static void ProcessingInit(MIL_ID MilSystem, ref PROC_PARAM ProcParamPtr)
        {
            // Allocate a MIL source buffer.
            MIL.MbufAllocColor(MilSystem,
                               MIL.MbufDiskInquire(IMAGE_FILE, MIL.M_SIZE_BAND, MIL.M_NULL),
                               MIL.MbufDiskInquire(IMAGE_FILE, MIL.M_SIZE_X, MIL.M_NULL),
                               MIL.MbufDiskInquire(IMAGE_FILE, MIL.M_SIZE_Y, MIL.M_NULL),
                               MIL.MbufDiskInquire(IMAGE_FILE, MIL.M_SIZE_BIT, MIL.M_NULL) + MIL.M_UNSIGNED,
                               MIL.M_IMAGE + MIL.M_PROC, ref ProcParamPtr.MilSourceImage);

            // Load the image into the source image.
            MIL.MbufLoad(IMAGE_FILE, ProcParamPtr.MilSourceImage);

            // Allocate a MIL destination buffer.
            MIL.MbufAllocColor(MilSystem,
                               MIL.MbufDiskInquire(IMAGE_FILE, MIL.M_SIZE_BAND, MIL.M_NULL),
                               MIL.MbufDiskInquire(IMAGE_FILE, MIL.M_SIZE_X, MIL.M_NULL),
                               MIL.MbufDiskInquire(IMAGE_FILE, MIL.M_SIZE_Y, MIL.M_NULL),
                               MIL.MbufDiskInquire(IMAGE_FILE, MIL.M_SIZE_BIT, MIL.M_NULL) + MIL.M_UNSIGNED,
                               MIL.M_IMAGE + MIL.M_PROC, ref ProcParamPtr.MilDestinationImage);
        }
Ejemplo n.º 4
0
        private void CameraGrabStart()
        {
            try
            {
                //이미지 버퍼 배열 선언
                _ImageBuffer = new MIL_ID[BufferCount];

                //배열 수만큼 돎
                for (int i = 0; i < _ImageBuffer.Length; i++)
                {
                    //400x400 크기의 모노 이미지 버퍼 선언 (원하는대로 변경 가능)
                    MIL.MbufAllocColor(CurrentUseCamera.SystemID, 1, 400, 400, 8, MIL.M_IMAGE + MIL.M_GRAB + MIL.M_PROC, ref _ImageBuffer[i]);
                }
                //그랩 콜백 등록
                _GrabCallbackFunc = OnGrab;
                //콜백 및 그랩 비동기 시작
                MIL.MdigProcess(CurrentUseCamera.DigitizerID, _ImageBuffer, _ImageBuffer.Length, MIL.M_START, MIL.M_ASYNCHRONOUS + MIL.M_TRIGGER_FOR_FIRST_GRAB, _GrabCallbackFunc, IntPtr.Zero);
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message + "\n" + err.StackTrace);
            }
        }
Ejemplo n.º 5
0
        static void ColorSegmentationExample(MIL_ID MilSystem, MIL_ID MilDisplay)
        {
            MIL_ID SourceChild  = MIL.M_NULL;           // Source image buffer identifier.
            MIL_ID DestChild    = MIL.M_NULL;           // Dest image buffer identifier.
            MIL_ID MatchContext = MIL.M_NULL;           // Color matching context identifier.
            MIL_ID MatchResult  = MIL.M_NULL;           // Color matching result identifier.
            MIL_ID DisplayImage = MIL.M_NULL;           // Display image buffer identifier.

            MIL_INT SourceSizeX = 0;
            MIL_INT SourceSizeY = 0;                    // Source image sizes
            MIL_INT SampleIndex = 0;
            MIL_INT SpacesIndex = 0;                    // Indices

            double MatchScore = 0.0;                    // Color matching score.

            // Blank spaces to align the samples names evenly.
            string[] Spaces = { "", " ", "  ", "   " };

            // Color samples names.
            string[] SampleNames = { "Green", "Red", "Yellow", "Purple", "Blue", "Pink" };

            // Color samples position: {OffsetX, OffsetY}
            double[,] SamplesROI = new double[, ] {
                { 58, 143 }, { 136, 148 }, { 217, 144 }, { 295, 142 }, { 367, 143 }, { 442, 147 }
            };

            // Color samples size.
            const double SampleSizeX = 36, SampleSizeY = 32;

            // Array for match sample colors.
            MIL_INT[,] SampleMatchColor = new MIL_INT[NUM_SAMPLES, 3];

            Console.Write("\nCOLOR SEGMENTATION:\n");
            Console.Write("-------------------\n");

            // Allocate the parent display image.
            MIL.MbufDiskInquire(CANDY_SAMPLE_IMAGE_FILE, MIL.M_SIZE_X, ref SourceSizeX);
            MIL.MbufDiskInquire(CANDY_SAMPLE_IMAGE_FILE, MIL.M_SIZE_Y, ref SourceSizeY);
            MIL.MbufAllocColor(MilSystem, 3, 2 * SourceSizeX + DISPLAY_CENTER_MARGIN_X, SourceSizeY, 8 + MIL.M_UNSIGNED, MIL.M_IMAGE + MIL.M_DISP + MIL.M_PROC, ref DisplayImage);
            MIL.MbufClear(DisplayImage, MIL.M_COLOR_BLACK);

            // Create a source and dest child in the display image.
            MIL.MbufChild2d(DisplayImage, 0, 0, SourceSizeX, SourceSizeY, ref SourceChild);
            MIL.MbufChild2d(DisplayImage, SourceSizeX + DISPLAY_CENTER_MARGIN_X, 0, SourceSizeX, SourceSizeY, ref DestChild);

            // Load the source image into the source child.
            MIL.MbufLoad(CANDY_SAMPLE_IMAGE_FILE, SourceChild);

            // Allocate a color matching context.
            MIL.McolAlloc(MilSystem, MIL.M_COLOR_MATCHING, MIL.M_RGB, MIL.M_DEFAULT, MIL.M_DEFAULT, ref MatchContext);

            // Define each color sample in the context.
            for (int i = 0; i < NUM_SAMPLES; i++)
            {
                MIL.McolDefine(MatchContext, SourceChild, MIL.M_SAMPLE_LABEL(i + 1), MIL.M_IMAGE, SamplesROI[i, 0], SamplesROI[i, 1], SampleSizeX, SampleSizeY);
            }

            // Set the color matching parameters.
            MIL.McolSetMethod(MatchContext, MATCH_MODE, DISTANCE_TYPE, MIL.M_DEFAULT, MIL.M_DEFAULT);
            MIL.McolControl(MatchContext, MIL.M_CONTEXT, MIL.M_DISTANCE_TOLERANCE_MODE, TOLERANCE_MODE);
            MIL.McolControl(MatchContext, MIL.M_ALL, MIL.M_DISTANCE_TOLERANCE, TOLERANCE_VALUE);

            // Adjust tolerances for the red, yellow and pink samples.
            MIL.McolControl(MatchContext, MIL.M_SAMPLE_INDEX(1), MIL.M_DISTANCE_TOLERANCE, RED_TOLERANCE_VALUE);
            MIL.McolControl(MatchContext, MIL.M_SAMPLE_INDEX(2), MIL.M_DISTANCE_TOLERANCE, YELLOW_TOLERANCE_VALUE);
            MIL.McolControl(MatchContext, MIL.M_SAMPLE_INDEX(5), MIL.M_DISTANCE_TOLERANCE, PINK_TOLERANCE_VALUE);

            // Preprocess the context.
            MIL.McolPreprocess(MatchContext, MIL.M_DEFAULT);

            // Fill the samples colors array.
            for (int i = 0; i < NUM_SAMPLES; i++)
            {
                MIL.McolInquire(MatchContext, MIL.M_SAMPLE_LABEL(i + 1), MIL.M_MATCH_SAMPLE_COLOR_BAND_0 + MIL.M_TYPE_MIL_INT, ref SampleMatchColor[i, 0]);
                MIL.McolInquire(MatchContext, MIL.M_SAMPLE_LABEL(i + 1), MIL.M_MATCH_SAMPLE_COLOR_BAND_1 + MIL.M_TYPE_MIL_INT, ref SampleMatchColor[i, 1]);
                MIL.McolInquire(MatchContext, MIL.M_SAMPLE_LABEL(i + 1), MIL.M_MATCH_SAMPLE_COLOR_BAND_2 + MIL.M_TYPE_MIL_INT, ref SampleMatchColor[i, 2]);
            }

            // Draw the samples.
            DrawSampleColors(DestChild, SampleMatchColor, SampleNames, NUM_SAMPLES, CANDY_SAMPLES_XSPACING, CANDY_SAMPLES_YOFFSET);

            // Select the image buffer for display.
            MIL.MdispSelect(MilDisplay, DisplayImage);

            // Pause to show the original image.
            Console.Write("Color samples are defined for each possible candy color.\n");
            Console.Write("Press <Enter> to do color matching.\n\n");
            Console.ReadKey();

            // Load the target image.*/
            MIL.MbufClear(DisplayImage, MIL.M_COLOR_BLACK);
            MIL.MbufLoad(CANDY_TARGET_IMAGE_FILE, SourceChild);

            // Allocate a color matching result buffer.
            MIL.McolAllocResult(MilSystem, MIL.M_COLOR_MATCHING_RESULT, MIL.M_DEFAULT, ref MatchResult);

            // Enable controls to draw the labeled color image.
            MIL.McolControl(MatchContext, MIL.M_CONTEXT, MIL.M_GENERATE_PIXEL_MATCH, MIL.M_ENABLE);
            MIL.McolControl(MatchContext, MIL.M_CONTEXT, MIL.M_GENERATE_SAMPLE_COLOR_LUT, MIL.M_ENABLE);

            // Match with target image.
            MIL.McolMatch(MatchContext, SourceChild, MIL.M_DEFAULT, MIL.M_NULL, MatchResult, MIL.M_DEFAULT);

            // Retrieve and display results.
            Console.Write("Each pixel of the mixture is matched " +
                          "with one of the color samples.\n");
            Console.Write("\nColor segmentation results:\n");
            Console.Write("---------------------------\n");

            for (SampleIndex = 0; SampleIndex < NUM_SAMPLES; SampleIndex++)
            {
                MIL.McolGetResult(MatchResult, MIL.M_DEFAULT, MIL.M_SAMPLE_INDEX((int)SampleIndex), MIL.M_SCORE, ref MatchScore);
                SpacesIndex = 6 - SampleNames[SampleIndex].Length;
                Console.Write("Ratio of {0}{1} sample = {2,5:0.00}%\n", SampleNames[SampleIndex], Spaces[SpacesIndex], MatchScore);
            }
            Console.Write("\nResults reveal the low proportion of Blue candy.\n");

            // Draw the colored label image in the destination child.
            MIL.McolDraw(MIL.M_DEFAULT, MatchResult, DestChild, MIL.M_DRAW_PIXEL_MATCH_USING_COLOR, MIL.M_ALL, MIL.M_ALL, MIL.M_DEFAULT);

            // Pause to show the result image.
            Console.Write("\nPress <Enter> to end.\n\n");
            Console.ReadKey();

            // Free all allocations.
            MIL.MbufFree(DestChild);
            MIL.MbufFree(SourceChild);
            MIL.MbufFree(DisplayImage);
            MIL.McolFree(MatchResult);
            MIL.McolFree(MatchContext);
        }
Ejemplo n.º 6
0
        static void ColorSeparationExample(MIL_ID MilSystem, MIL_ID MilDisplay)
        {
            MIL_ID DisplayImage = MIL.M_NULL;           // Display image buffer identifier.
            MIL_ID SourceChild  = MIL.M_NULL;           // Source image buffer identifier.
            MIL_ID DestChild    = MIL.M_NULL;           // Destination image buffer identifier.
            MIL_ID Child        = MIL.M_NULL;           // Child buffer identifier.
            MIL_ID ColorsArray  = MIL.M_NULL;           // Array buffer identifier.

            // Source image sizes.
            MIL_INT SourceSizeX = 0;
            MIL_INT SourceSizeY = 0;

            // Color samples' names
            string[] ColorNames = { "BACKGROUND", "WRITING", "STAMP" };

            // Array with color patches to draw.
            MIL_INT[,] Colors = new MIL_INT[, ] {
                { 245, 234, 206 }, { 141, 174, 174 }, { 226, 150, 118 }
            };

            // Samples' color coordinates
            byte[] BackgroundColor = new byte[3] {
                245, 234, 206
            };
            byte[] SelectedColor = new byte[3] {
                141, 174, 174
            };
            byte[] RejectedColor = new byte[3] {
                226, 150, 118
            };

            Console.Write("\nCOLOR SEPARATION:\n");
            Console.Write("-----------------\n");

            // Allocate an array buffer and fill it with the color coordinates.
            MIL.MbufAlloc2d(MilSystem, 3, 3, 8 + MIL.M_UNSIGNED, MIL.M_ARRAY, ref ColorsArray);
            MIL.MbufPut2d(ColorsArray, 0, 0, 3, 1, BackgroundColor);
            MIL.MbufPut2d(ColorsArray, 0, 1, 3, 1, SelectedColor);
            MIL.MbufPut2d(ColorsArray, 0, 2, 3, 1, RejectedColor);

            // Allocate the parent display image.
            MIL.MbufDiskInquire(WRITING_IMAGE_FILE, MIL.M_SIZE_X, ref SourceSizeX);
            MIL.MbufDiskInquire(WRITING_IMAGE_FILE, MIL.M_SIZE_Y, ref SourceSizeY);
            MIL.MbufAllocColor(MilSystem, 3, 2 * SourceSizeX + DISPLAY_CENTER_MARGIN_X, SourceSizeY, 8 + MIL.M_UNSIGNED, MIL.M_IMAGE + MIL.M_DISP + MIL.M_PROC, ref DisplayImage);
            MIL.MbufClear(DisplayImage, MIL.M_COLOR_BLACK);

            // Clear the overlay.
            MIL.MdispControl(MilDisplay, MIL.M_OVERLAY_CLEAR, MIL.M_DEFAULT);

            // Create a source and dest child in the display image
            MIL.MbufChild2d(DisplayImage, 0, 0, SourceSizeX, SourceSizeY, ref SourceChild);
            MIL.MbufChild2d(DisplayImage, SourceSizeX + DISPLAY_CENTER_MARGIN_X, 0, SourceSizeX, SourceSizeY, ref DestChild);

            // Load the source image into the display image source child.
            MIL.MbufLoad(WRITING_IMAGE_FILE, SourceChild);

            // Draw the color patches.
            DrawSampleColors(DestChild, Colors, ColorNames, 3, PATCHES_XSPACING, -1);

            // Display the image.
            MIL.MdispSelect(MilDisplay, DisplayImage);

            // Pause to show the source image and color patches.
            Console.Write("The writing will be separated from the stamp using the following triplets:\n");
            Console.Write("the background color: beige [{0}, {1}, {2}],\n", BackgroundColor[0], BackgroundColor[1], BackgroundColor[2]);
            Console.Write("the writing color   : green [{0}, {1}, {2}],\n", SelectedColor[0], SelectedColor[1], SelectedColor[2]);
            Console.Write("the stamp color     : red   [{0}, {1}, {2}].\n\n", RejectedColor[0], RejectedColor[1], RejectedColor[2]);
            Console.Write("Press <Enter> to extract the writing.\n\n");
            Console.ReadKey();

            // Perform the color projection.
            MIL.McolProject(SourceChild, ColorsArray, DestChild, MIL.M_NULL, MIL.M_COLOR_SEPARATION, MIL.M_DEFAULT, MIL.M_NULL);

            // Wait for a key.
            Console.Write("Press <Enter> to extract the stamp.\n\n");
            Console.ReadKey();

            // Switch the order of the selected vs rejected colors in the color array.
            MIL.MbufPut2d(ColorsArray, 0, 2, 3, 1, SelectedColor);
            MIL.MbufPut2d(ColorsArray, 0, 1, 3, 1, RejectedColor);

            // Perform the color projection.
            MIL.McolProject(SourceChild, ColorsArray, DestChild, MIL.M_NULL, MIL.M_COLOR_SEPARATION, MIL.M_DEFAULT, MIL.M_NULL);

            // Wait for a key.
            Console.Write("Press <Enter> to end.\n\n");
            Console.ReadKey();

            // Free all allocations.
            MIL.MbufFree(ColorsArray);
            MIL.MbufFree(SourceChild);
            MIL.MbufFree(DestChild);
            MIL.MbufFree(DisplayImage);
        }
Ejemplo n.º 7
0
        static void ColorMatchingExample(MIL_ID MilSystem, MIL_ID MilDisplay)
        {
            MIL_ID DisplayImage       = MIL.M_NULL;     // Display image buffer identifier.
            MIL_ID SourceChild        = MIL.M_NULL;     // Source image buffer identifier.
            MIL_ID DestChild          = MIL.M_NULL;     // Dest image buffer identifier.
            MIL_ID ColMatchContext    = MIL.M_NULL;     // Color matching context identifier.
            MIL_ID ColMatchResult     = MIL.M_NULL;     // Color matching result identifier.
            MIL_ID ModelImage         = MIL.M_NULL;     // Model image buffer identifier.
            MIL_ID AreaImage          = MIL.M_NULL;     // Area  image buffer identifier.
            MIL_ID OverlayID          = MIL.M_NULL;     // Overlay image buffer identifier.
            MIL_ID OverlaySourceChild = MIL.M_NULL;     // Overlay source child identifier.
            MIL_ID OverlayDestChild   = MIL.M_NULL;     // Overlay dest child identifier.
            MIL_ID FuseFinderCtx      = MIL.M_NULL;     // Model finder context identifier.
            MIL_ID FuseFinderRes      = MIL.M_NULL;     // Model finder result identifier.

            // Image sizes
            MIL_INT SizeX = 0;
            MIL_INT SizeY = 0;

            // Color sample names
            string[] SampleNames = { "Green", " Blue", " Red", "Yellow" };

            // Sample ROIs coordinates: OffsetX, OffsetY, SizeX, SizeY
            MIL_INT[,] SampleROIs = new MIL_INT[, ] {
                { 54, 139, 28, 14 },
                { 172, 137, 30, 23 },
                { 296, 135, 31, 23 },
                { 417, 134, 27, 22 }
            };

            // Array of match sample colors.
            MIL_INT[,] SampleMatchColor = new MIL_INT[NUM_FUSES, 3];

            Console.Write("\nCOLOR IDENTIFICATION:\n");
            Console.Write("---------------------\n");

            // Allocate the parent display image.
            MIL.MbufDiskInquire(FUSE_TARGET_IMAGE, MIL.M_SIZE_X, ref SizeX);
            MIL.MbufDiskInquire(FUSE_TARGET_IMAGE, MIL.M_SIZE_Y, ref SizeY);
            MIL.MbufAllocColor(MilSystem, 3, 2 * SizeX + DISPLAY_CENTER_MARGIN_X, SizeY, 8 + MIL.M_UNSIGNED, MIL.M_IMAGE + MIL.M_DISP + MIL.M_PROC, ref DisplayImage);
            MIL.MbufClear(DisplayImage, MIL.M_COLOR_BLACK);

            // Allocate the model, area and label images.
            MIL.MbufAlloc2d(MilSystem, SizeX, SizeY, 8 + MIL.M_UNSIGNED, MIL.M_IMAGE + MIL.M_PROC + MIL.M_DISP, ref ModelImage);
            MIL.MbufAlloc2d(MilSystem, SizeX, SizeY, 8 + MIL.M_UNSIGNED, MIL.M_IMAGE + MIL.M_PROC + MIL.M_DISP, ref AreaImage);

            // Create a source and destination child in the display image.
            MIL.MbufChild2d(DisplayImage, 0, 0, SizeX, SizeY, ref SourceChild);
            MIL.MbufChild2d(DisplayImage, SizeX + DISPLAY_CENTER_MARGIN_X, 0, SizeX, SizeY, ref DestChild);

            // Load the sample source image.
            MIL.MbufLoad(FUSE_SAMPLES_IMAGE, SourceChild);

            // Display the image buffer.
            MIL.MdispSelect(MilDisplay, DisplayImage);

            // Prepare the overlay.
            MIL.MdispControl(MilDisplay, MIL.M_OVERLAY, MIL.M_ENABLE);
            MIL.MdispControl(MilDisplay, MIL.M_OVERLAY_CLEAR, MIL.M_DEFAULT);
            MIL.MdispInquire(MilDisplay, MIL.M_OVERLAY_ID, ref OverlayID);
            MIL.MbufChild2d(OverlayID, 0, 0, SizeX, SizeY, ref OverlaySourceChild);
            MIL.MbufChild2d(OverlayID, SizeX + DISPLAY_CENTER_MARGIN_X, 0, SizeX, SizeY, ref OverlayDestChild);

            // Prepare the model finder context and result.
            MIL.MmodRestore(FINDER_CONTEXT, MilSystem, MIL.M_DEFAULT, ref FuseFinderCtx);
            MIL.MmodPreprocess(FuseFinderCtx, MIL.M_DEFAULT);
            MIL.MmodAllocResult(MilSystem, MIL.M_DEFAULT, ref FuseFinderRes);

            // Allocate a color match context and result.
            MIL.McolAlloc(MilSystem, MIL.M_COLOR_MATCHING, MIL.M_RGB, MIL.M_DEFAULT, MIL.M_DEFAULT, ref ColMatchContext);
            MIL.McolAllocResult(MilSystem, MIL.M_COLOR_MATCHING_RESULT, MIL.M_DEFAULT, ref ColMatchResult);

            // Define the color samples in the context.
            for (int i = 0; i < NUM_FUSES; i++)
            {
                MIL.McolDefine(ColMatchContext, SourceChild, MIL.M_SAMPLE_LABEL(i + 1), MIL.M_IMAGE, (double)SampleROIs[i, 0], (double)SampleROIs[i, 1], (double)SampleROIs[i, 2], (double)SampleROIs[i, 3]);
            }

            // Preprocess the context.
            MIL.McolPreprocess(ColMatchContext, MIL.M_DEFAULT);

            // Fill the samples colors array.
            for (int i = 0; i < NUM_FUSES; i++)
            {
                MIL.McolInquire(ColMatchContext, MIL.M_SAMPLE_LABEL(i + 1), MIL.M_MATCH_SAMPLE_COLOR_BAND_0 + MIL.M_TYPE_MIL_INT, ref SampleMatchColor[i, 0]);
                MIL.McolInquire(ColMatchContext, MIL.M_SAMPLE_LABEL(i + 1), MIL.M_MATCH_SAMPLE_COLOR_BAND_1 + MIL.M_TYPE_MIL_INT, ref SampleMatchColor[i, 1]);
                MIL.McolInquire(ColMatchContext, MIL.M_SAMPLE_LABEL(i + 1), MIL.M_MATCH_SAMPLE_COLOR_BAND_2 + MIL.M_TYPE_MIL_INT, ref SampleMatchColor[i, 2]);
            }

            // Draw the color samples.
            DrawSampleColors(DestChild, SampleMatchColor, SampleNames, NUM_FUSES, FUSE_SAMPLES_XSPACING, FUSE_SAMPLES_YOFFSET);

            // Draw the sample ROIs in the source image overlay.
            MIL.MgraColor(MIL.M_DEFAULT, MIL.M_COLOR_RED);
            for (MIL_INT SampleIndex = 0; SampleIndex < NUM_FUSES; SampleIndex++)
            {
                MIL_INT XEnd = SampleROIs[SampleIndex, 0] + SampleROIs[SampleIndex, 2] - 1;
                MIL_INT YEnd = SampleROIs[SampleIndex, 1] + SampleROIs[SampleIndex, 3] - 1;
                MIL.MgraRect(MIL.M_DEFAULT, OverlaySourceChild, SampleROIs[SampleIndex, 0], SampleROIs[SampleIndex, 1], XEnd, YEnd);
            }

            // Pause to show the source image.
            Console.Write("Colors are defined using one color sample region per fuse.\n");
            Console.Write("Press <Enter> to process the target image.\n");
            Console.ReadKey();

            // Clear the overlay.
            MIL.MdispControl(MilDisplay, MIL.M_OVERLAY_CLEAR, MIL.M_DEFAULT);

            // Load the target image into the source child.
            MIL.MbufLoad(FUSE_TARGET_IMAGE, SourceChild);

            // Get the grayscale model image and copy it into the display dest child.
            MIL.MimConvert(SourceChild, ModelImage, MIL.M_RGB_TO_L);
            MIL.MbufCopy(ModelImage, DestChild);

            // Find the Model.
            MIL.MmodFind(FuseFinderCtx, ModelImage, FuseFinderRes);

            // Draw the blob image: labeled circular areas centered at each found fuse occurrence.
            MIL_INT Number = 0;

            MIL.MmodGetResult(FuseFinderRes, MIL.M_DEFAULT, MIL.M_NUMBER + MIL.M_TYPE_MIL_INT, ref Number);
            MIL.MbufClear(AreaImage, 0);
            for (MIL_INT ii = 0; ii < Number; ii++)
            {
                double X = 0.0;
                double Y = 0.0;

                // Get the position
                MIL.MmodGetResult(FuseFinderRes, ii, MIL.M_POSITION_X, ref X);
                MIL.MmodGetResult(FuseFinderRes, ii, MIL.M_POSITION_Y, ref Y);

                // Set the label color
                MIL.MgraColor(MIL.M_DEFAULT, (double)ii + 1);

                // Draw the filled circle
                MIL.MgraArcFill(MIL.M_DEFAULT, AreaImage, X, Y, 20, 20, 0, 360);
            }

            // Enable controls to draw the labeled color image.
            MIL.McolControl(ColMatchContext, MIL.M_CONTEXT, MIL.M_SAVE_AREA_IMAGE, MIL.M_ENABLE);
            MIL.McolControl(ColMatchContext, MIL.M_CONTEXT, MIL.M_GENERATE_SAMPLE_COLOR_LUT, MIL.M_ENABLE);

            // Perform the color matching.
            MIL.McolMatch(ColMatchContext, SourceChild, MIL.M_DEFAULT, AreaImage, ColMatchResult, MIL.M_DEFAULT);

            // Draw the label image into the overlay child.
            MIL.McolDraw(MIL.M_DEFAULT, ColMatchResult, OverlayDestChild, MIL.M_DRAW_AREA_MATCH_USING_COLOR, MIL.M_ALL, MIL.M_ALL, MIL.M_DEFAULT);

            // Draw the model position over the colored areas.
            MIL.MgraColor(MIL.M_DEFAULT, MIL.M_COLOR_BLUE);
            MIL.MmodDraw(MIL.M_DEFAULT, FuseFinderRes, OverlayDestChild, MIL.M_DRAW_BOX + MIL.M_DRAW_POSITION, MIL.M_ALL, MIL.M_DEFAULT);

            // Enable the display update.
            MIL.MdispControl(MilDisplay, MIL.M_UPDATE, MIL.M_ENABLE);

            // Pause to show the resulting image.
            Console.Write("\nFuses are located using the Model Finder tool.\n");
            Console.Write("The color of each target area is identified.\n");
            Console.Write("Press <Enter> to end.\n");
            Console.ReadKey();

            // Free all allocations.
            MIL.MmodFree(FuseFinderRes);
            MIL.MmodFree(FuseFinderCtx);
            MIL.MbufFree(AreaImage);
            MIL.MbufFree(ModelImage);
            MIL.MbufFree(SourceChild);
            MIL.MbufFree(DestChild);
            MIL.MbufFree(OverlaySourceChild);
            MIL.MbufFree(OverlayDestChild);
            MIL.MbufFree(DisplayImage);
            MIL.McolFree(ColMatchContext);
            MIL.McolFree(ColMatchResult);
        }
Ejemplo n.º 8
0
        public long Init(int nCamIndex, MIL_ID MilSystem, string sDcfPath)
        {
            //HookDataStruct UserHookData = new HookDataStruct();

            if (string.IsNullOrEmpty(sDcfPath))
            {
                MIL.MdigAlloc(MilSystem, nCamIndex, ("M_DEFAULT"), MIL.M_DEFAULT, ref MilDigitizer);
            }
            else
            {
                MIL.MdigAlloc(MilSystem, nCamIndex, sDcfPath, MIL.M_DEFAULT, ref MilDigitizer);
            }

            MIL.MdispAlloc(MilSystem, MIL.M_DEFAULT, ("M_DEFAULT"), MIL.M_DEFAULT, ref MilDisplay);


            // Allocate the grab buffers and clear them.
            MilImageWidth  = MIL.MdigInquire(MilDigitizer, MIL.M_SIZE_X, MIL.M_NULL);
            MilImageHeight = MIL.MdigInquire(MilDigitizer, MIL.M_SIZE_Y, MIL.M_NULL);
            MilImageBand   = MIL.MdigInquire(MilDigitizer, MIL.M_SIZE_BAND, MIL.M_NULL);

            MIL.MappControl(MIL.M_ERROR, MIL.M_PRINT_DISABLE);

            MIL.MbufAllocColor(MilSystem,
                               MilImageBand,
                               MilImageWidth,
                               MilImageHeight,
                               8 + MIL.M_UNSIGNED,
                               MIL.M_IMAGE + MIL.M_GRAB + MIL.M_PROC + MIL.M_DISP,  // 参数MIL.M_DISP用于添加显示图片功能
                               ref MilImageBuf);

            MIL.MappControl(MIL.M_ERROR, MIL.M_PRINT_ENABLE);
            MIL.MbufClear(MilImageBuf, 0);
            MIL.MdispSelect(MilDisplay, MilImageBuf);       // 选择用于显示的Buffer
            //MIL.MdispSelectWindow(MilDisplay, MilImageBuf, pictureBox1.Handle);
            //MIL.MdispControl(MilDisplay, MIL.M_SCALE_DISPLAY, MIL.M_ENABLE);

            // Allocate the grab buffers and clear them.
            for (MilGrabBufferListSize = 0; MilGrabBufferListSize < BUFFERING_SIZE_MAX; MilGrabBufferListSize++)
            {
                MIL.MbufAllocColor(MilSystem,
                                   MIL.MdigInquire(MilDigitizer, MIL.M_SIZE_BAND, MIL.M_NULL),
                                   MIL.MdigInquire(MilDigitizer, MIL.M_SIZE_X, MIL.M_NULL),
                                   MIL.MdigInquire(MilDigitizer, MIL.M_SIZE_Y, MIL.M_NULL),
                                   8 + MIL.M_UNSIGNED,
                                   MIL.M_IMAGE + MIL.M_GRAB + MIL.M_PROC,
                                   ref MilGrabBufferList[MilGrabBufferListSize]);

                if (MilGrabBufferList[MilGrabBufferListSize] != MIL.M_NULL)
                {
                    MIL.MbufClear(MilGrabBufferList[MilGrabBufferListSize], 0xFF);
                }
                else
                {
                    break;
                }
            }


            //********设置相机采集模式和超时时间
            MIL.MdigControl(MilDigitizer, MIL.M_GRAB_MODE, MIL.M_ASYNCHRONOUS);
            MIL.MdigControl(MilDigitizer, MIL.M_GRAB_TIMEOUT, MIL.M_INFINITE);


            imgData = new byte[((int)(MilImageWidth * MilImageHeight * MilImageBand))];

            thObject = GCHandle.Alloc(imgData, GCHandleType.Pinned);

            hUserData = GCHandle.Alloc(this);

            return(0);
        }
Ejemplo n.º 9
0
        // Main function.
        static void Main(string[] args)
        {
            MIL_ID  MilApplication       = MIL.M_NULL;      // Application identifier.
            MIL_ID  MilSystem            = MIL.M_NULL;      // System identifier.
            MIL_ID  MilDisplay           = MIL.M_NULL;      // Display identifier.
            MIL_ID  MilImage             = MIL.M_NULL;      // Image buffer identifier.
            MIL_ID  MilLeftSubImage      = MIL.M_NULL;      // Sub-image buffer identifier for original image.
            MIL_ID  MilRightSubImage     = MIL.M_NULL;      // Sub-image buffer identifier for processed image.
            MIL_ID  MilLumSubImage       = MIL.M_NULL;      // Sub-image buffer identifier for luminance.
            MIL_ID  MilRedBandSubImage   = MIL.M_NULL;      // Sub-image buffer identifier for red component.
            MIL_ID  MilGreenBandSubImage = MIL.M_NULL;      // Sub-image buffer identifier for green component.
            MIL_ID  MilBlueBandSubImage  = MIL.M_NULL;      // Sub-image buffer identifier for blue component.
            MIL_INT SizeX    = 0;
            MIL_INT SizeY    = 0;
            MIL_INT SizeBand = 0;
            MIL_INT Type     = 0;

            // Allocate defaults.
            MIL.MappAllocDefault(MIL.M_DEFAULT, ref MilApplication, ref MilSystem, ref MilDisplay, MIL.M_NULL, MIL.M_NULL);

            // Allocate a color display buffer twice the size of the source image and display it.
            MIL.MbufAllocColor(MilSystem,
                               MIL.MbufDiskInquire(IMAGE_FILE, MIL.M_SIZE_BAND, ref SizeBand),
                               MIL.MbufDiskInquire(IMAGE_FILE, MIL.M_SIZE_X, ref SizeX) * 2,
                               MIL.MbufDiskInquire(IMAGE_FILE, MIL.M_SIZE_Y, ref SizeY),
                               MIL.MbufDiskInquire(IMAGE_FILE, MIL.M_TYPE, ref Type),
                               MIL.M_IMAGE + MIL.M_DISP + MIL.M_PROC, ref MilImage);
            MIL.MbufClear(MilImage, 0);
            MIL.MdispSelect(MilDisplay, MilImage);

            // Define 2 child buffers that maps to the left and right part of the display
            // buffer, to put the source and destination color images.
            //
            MIL.MbufChild2d(MilImage, 0, 0, SizeX, SizeY, ref MilLeftSubImage);
            MIL.MbufChild2d(MilImage, SizeX, 0, SizeX, SizeY, ref MilRightSubImage);

            // Load the color source image on the left.
            MIL.MbufLoad(IMAGE_FILE, MilLeftSubImage);

            // Define child buffers that map to the red, green and blue components
            // of the source image.
            //
            MIL.MbufChildColor(MilLeftSubImage, MIL.M_RED, ref MilRedBandSubImage);
            MIL.MbufChildColor(MilLeftSubImage, MIL.M_GREEN, ref MilGreenBandSubImage);
            MIL.MbufChildColor(MilLeftSubImage, MIL.M_BLUE, ref MilBlueBandSubImage);

            // Write color text annotations to show access in each individual band of the image.
            //
            // Note that this is typically done more simply by using:
            //  MIL.MgraColor(MIL.M_DEFAULT, MIL.M_RGB(0xFF,0x90,0x00));
            //  MIL.MgraText(MIL.M_DEFAULT, MilLeftSubImage, ...);

            MIL.MgraColor(MIL.M_DEFAULT, 0xFF);
            MIL.MgraText(MIL.M_DEFAULT, MilRedBandSubImage, SizeX / 16, SizeY / 8, " TOUCAN ");
            MIL.MgraColor(MIL.M_DEFAULT, 0x90);
            MIL.MgraText(MIL.M_DEFAULT, MilGreenBandSubImage, SizeX / 16, SizeY / 8, " TOUCAN ");
            MIL.MgraColor(MIL.M_DEFAULT, 0x00);
            MIL.MgraText(MIL.M_DEFAULT, MilBlueBandSubImage, SizeX / 16, SizeY / 8, " TOUCAN ");

            // Print a message.
            Console.Write("\nCOLOR OPERATIONS:\n");
            Console.Write("-----------------\n\n");
            Console.Write("A color source image was loaded on the left and color text\n");
            Console.Write("annotations were written in it.\n");
            Console.Write("Press <Enter> to continue.\n\n");
            Console.ReadKey();

            // Convert image to Hue, Luminance, Saturation color space (HSL).
            MIL.MimConvert(MilLeftSubImage, MilRightSubImage, MIL.M_RGB_TO_HSL);

            // Create a child buffer that maps to the luminance component.
            MIL.MbufChildColor(MilRightSubImage, MIL.M_LUMINANCE, ref MilLumSubImage);

            // Add an offset to the luminance component.
            MIL.MimArith(MilLumSubImage, IMAGE_LUMINANCE_OFFSET, MilLumSubImage, MIL.M_ADD_CONST + MIL.M_SATURATION);

            // Convert image back to Red, Green, Blue color space (RGB) for display.
            MIL.MimConvert(MilRightSubImage, MilRightSubImage, MIL.M_HSL_TO_RGB);

            // Print a message.
            Console.Write("Luminance was increased using color image processing.\n");

            // Print a message.
            Console.Write("Press <Enter> to end.\n");
            Console.ReadKey();

            // Release sub-images and color image buffer.
            MIL.MbufFree(MilLumSubImage);
            MIL.MbufFree(MilRedBandSubImage);
            MIL.MbufFree(MilGreenBandSubImage);
            MIL.MbufFree(MilBlueBandSubImage);
            MIL.MbufFree(MilRightSubImage);
            MIL.MbufFree(MilLeftSubImage);
            MIL.MbufFree(MilImage);

            // Release defaults.
            MIL.MappFreeDefault(MilApplication, MilSystem, MilDisplay, MIL.M_NULL, MIL.M_NULL);
        }
Ejemplo n.º 10
0
        // Main function. //
        // ---------------//
        static int Main(string[] args)
        {
            MIL_ID MilApplication       = MIL.M_NULL;
            MIL_ID MilRemoteApplication = MIL.M_NULL;
            MIL_ID MilSystem            = MIL.M_NULL;
            MIL_ID MilDigitizer         = MIL.M_NULL;
            MIL_ID MilDisplay           = MIL.M_NULL;
            MIL_ID MilImageDisp         = MIL.M_NULL;

            MIL_ID[]                       MilGrabBufferList    = new MIL_ID[BUFFERING_SIZE_MAX];
            MIL_ID                         MilCompressContext   = MIL.M_NULL;
            MIL_ID                         MilDecompressContext = MIL.M_NULL;
            MIL_INT                        LicenseModules       = 0;
            MIL_INT                        MilSystemLocation    = MIL.M_NULL;
            MIL_INT                        MilGrabBufferListSize;
            MIL_INT                        ProcessFrameCount = 0;
            MIL_INT                        NbFrames          = 0;
            MIL_INT                        n = 0;
            double                         EncodingDesiredFrameRate     = 0.0;
            double                         ProcessFrameRate             = 0.0;
            MIL_INT                        SeqProcessFilePathSize       = 0;
            StringBuilder                  SeqProcessFilePath           = null;
            ProcessingHookDataStruct       ProcessingUserHookData       = new ProcessingHookDataStruct();
            EncodingFrameEndHookDataStruct EncodingFrameEndUserHookData = new EncodingFrameEndHookDataStruct();
            DecodingFrameEndHookDataStruct DecodingFrameEndUserHookData = new DecodingFrameEndHookDataStruct();
            MIL_INT                        SeqSystemType = MIL.M_NULL;

            // Allocate defaults.
            MIL.MappAllocDefault(MIL.M_DEFAULT, ref MilApplication, ref MilSystem, ref MilDisplay, ref MilDigitizer, ref MilImageDisp);

            MIL.MsysInquire(MilSystem, MIL.M_OWNER_APPLICATION, ref MilRemoteApplication);
            MilSystemLocation = MIL.MsysInquire(MilSystem, MIL.M_LOCATION, MIL.M_NULL);

            if (MIL.MappInquire(MilRemoteApplication, MIL.M_PLATFORM_OS_TYPE, MIL.M_NULL) != MIL.M_OS_WINDOWS)
            {
                if (MilSystemLocation == MIL.M_REMOTE)
                {
                    Console.WriteLine("The Distributed MIL server must run on a Windows system.");
                }
                else
                {
                    Console.WriteLine("This example only works with a Windows system.");
                }

                Console.WriteLine("Press <Enter> to end.");
                Console.ReadKey();

                MIL.MappFreeDefault(MilApplication, MilSystem, MilDisplay, MilDigitizer, MilImageDisp);
                return(0);
            }

            // Inquire MIL licenses.

            MIL.MappInquire(MilRemoteApplication, MIL.M_LICENSE_MODULES, ref LicenseModules);

            if ((LicenseModules & MIL.M_LICENSE_JPEGSTD) != MIL.M_LICENSE_JPEGSTD)
            {
                Console.WriteLine("Need a Compression/Decompression license to run this example.");
                Console.WriteLine("Press <Enter> to end.");
                Console.ReadKey();

                MIL.MappFreeDefault(MilApplication, MilSystem, MilDisplay, MilDigitizer, MilImageDisp);
                return(0);
            }

            // Allocate the grab buffers and clear them.
            MIL.MappControl(MIL.M_DEFAULT, MIL.M_ERROR, MIL.M_PRINT_DISABLE);
            for (MilGrabBufferListSize = 0; MilGrabBufferListSize < BUFFERING_SIZE_MAX; MilGrabBufferListSize++)
            {
                MIL.MbufAllocColor(MilSystem, MIL.MdigInquire(MilDigitizer, MIL.M_SIZE_BAND, MIL.M_NULL),
                                   MIL.MdigInquire(MilDigitizer, MIL.M_SIZE_X, MIL.M_NULL),
                                   MIL.MdigInquire(MilDigitizer, MIL.M_SIZE_Y, MIL.M_NULL),
                                   8 + MIL.M_UNSIGNED, MIL.M_IMAGE + MIL.M_GRAB + MIL.M_PROC,
                                   ref MilGrabBufferList[MilGrabBufferListSize]);

                if (MilGrabBufferList[MilGrabBufferListSize] != MIL.M_NULL)
                {
                    MIL.MbufClear(MilGrabBufferList[MilGrabBufferListSize], 0xFF);
                }
                else
                {
                    break;
                }
            }
            MIL.MappControl(MIL.M_DEFAULT, MIL.M_ERROR, MIL.M_PRINT_ENABLE);

            // Free buffers to leave space for possible temporary buffers.
            for (n = 0; n < 2 && MilGrabBufferListSize > 0; n++)
            {
                MilGrabBufferListSize--;
                MIL.MbufFree(MilGrabBufferList[MilGrabBufferListSize]);
            }

            if (MilGrabBufferListSize == 0)
            {
                Console.WriteLine("!!! No grab buffers have been allocated. Need to set more Non-Paged Memory. !!!");

                MIL.MappFreeDefault(MilApplication, MilSystem, MilDisplay, MilDigitizer, MilImageDisp);
                Console.WriteLine("Press <Enter> to end.");
                Console.ReadKey();
                return(1);
            }

            /* Initialize the User's processing function data structure only for Display. */
            ProcessingUserHookData.MilDigitizer        = MilDigitizer;
            ProcessingUserHookData.MilSeqContext       = MIL.M_NULL;
            ProcessingUserHookData.MilImageDisp        = MilImageDisp;
            ProcessingUserHookData.ProcessedImageCount = 0;
            ProcessingUserHookData.ProcessingOperation = ProcessingHookOperation.DISPLAY;

            // get a handle to the HookDataStruct object in the managed heap, we will use this
            // handle to get the object back in the callback function
            GCHandle hUserData = GCHandle.Alloc(ProcessingUserHookData);

            // Start the sequence acquisition. The preprocessing and encoding hook function
            // is called for every frame grabbed.
            MIL_DIG_HOOK_FUNCTION_PTR ProcessingFunctionDelegate = new MIL_DIG_HOOK_FUNCTION_PTR(ProcessingFunction);

            /* Start a digProcess to show the live camera output. */
            MIL.MdigProcess(MilDigitizer, MilGrabBufferList, MilGrabBufferListSize, MIL.M_START, MIL.M_DEFAULT, ProcessingFunctionDelegate, GCHandle.ToIntPtr(hUserData));

            /* Print a message. */
            Console.Write("\nH.264 IMAGE SEQUENCE COMPRESSION.\n");
            Console.Write("---------------------------------\n\n");
            Console.Write("Press <Enter> to start compression.\r");
            Console.ReadKey();

            /* Stop digProcess. */
            MIL.MdigProcess(MilDigitizer, MilGrabBufferList, MilGrabBufferListSize, MIL.M_STOP, MIL.M_DEFAULT, ProcessingFunctionDelegate, GCHandle.ToIntPtr(hUserData));

            /* Inquire the dig process frame rate */
            MIL.MdigInquire(MilDigitizer, MIL.M_PROCESS_FRAME_RATE, ref EncodingDesiredFrameRate);
            Console.Write("Grabbing frames at {0:0.00} frames/sec.\n", EncodingDesiredFrameRate);


            // Creates a context for the H.264 compression engine. Compression will be done
            // using hardware or software depending on the system hardware configuration.
            MIL.MseqAlloc(MilSystem, MIL.M_DEFAULT, MIL.M_SEQ_COMPRESS, MIL.M_DEFAULT, MIL.M_DEFAULT, ref MilCompressContext);

            // Specify the destination of the compressed file and the target container type.
            // The last argument specifies to generate an MP4 file.
            MIL.MseqDefine(MilCompressContext, MIL.M_SEQ_OUTPUT(0) + MIL.M_SEQ_DEST(0), MIL.M_FILE,
                           (MilSystemLocation != MIL.M_REMOTE ? SEQUENCE_FILE : REMOTE_SEQUENCE_FILE),
                           MIL.M_FILE_FORMAT_MP4);

            // Set the compression parameters.
            // Sets the compression parameters valid for any resolution under 1920X1080.
            // Any resolution higher than that will generate an warning that can be disabled using
            // MseqControl with M_SETTING_AUTO_ADJUSTMENT. See documentation for more details.
            MIL.MseqControl(MilCompressContext, MIL.M_CONTEXT, MIL.M_STREAM_BIT_RATE_MODE, MIL.M_VARIABLE);         // MIL.M_VARIABLE or MIL.M_CONSTANT
            MIL.MseqControl(MilCompressContext, MIL.M_CONTEXT, MIL.M_STREAM_BIT_RATE, 5000);                        // 5 Mbps bit rate
            MIL.MseqControl(MilCompressContext, MIL.M_CONTEXT, MIL.M_STREAM_BIT_RATE_MAX, 5000);                    // 5 Mbps bit rate
            MIL.MseqControl(MilCompressContext, MIL.M_CONTEXT, MIL.M_STREAM_FRAME_RATE, EncodingDesiredFrameRate);  // 60Hz frame rate.
            MIL.MseqControl(MilCompressContext, MIL.M_CONTEXT, MIL.M_STREAM_FRAME_RATE_MODE, MIL.M_VARIABLE);       // Attempts to update the file header with the encoding frame rate
                                                                                                                    // if lower than the specified frame rate.

            MIL.MseqControl(MilCompressContext, MIL.M_CONTEXT, MIL.M_STREAM_QUALITY, 100);                          // 1=best speed, 100=best quality
            MIL.MseqControl(MilCompressContext, MIL.M_CONTEXT, MIL.M_STREAM_PROFILE, MIL.M_PROFILE_HIGH);           // MIL.M_PROFILE_BASELINE, MIL.M_PROFILE_MAIN, MIL.M_PROFILE_HIGH
            MIL.MseqControl(MilCompressContext, MIL.M_CONTEXT, MIL.M_STREAM_LEVEL, MIL.M_LEVEL_4_2);                // MIL.M_LEVEL_1, MIL.M_LEVEL_1B, MIL.M_LEVEL_1_1, MIL.M_LEVEL_1_2, MIL.M_LEVEL_1_3,
                                                                                                                    // MIL.M_LEVEL_2, MIL.M_LEVEL_2_1, MIL.M_LEVEL_2_2,
                                                                                                                    // MIL.M_LEVEL_3, MIL.M_LEVEL_3_1, MIL.M_LEVEL_3_2,
                                                                                                                    // MIL.M_LEVEL_4, MIL.M_LEVEL_4_1, MIL.M_LEVEL_4_2,
                                                                                                                    // MIL.M_LEVEL_5, MIL.M_LEVEL_5_1
            MIL.MseqControl(MilCompressContext, MIL.M_CONTEXT, MIL.M_STREAM_GROUP_OF_PICTURE_SIZE, 30);             // Interval between I-Frame

            // Initialize the optional encoding end function data structure.
            EncodingFrameEndUserHookData.EncodedImageCount = 0;

            // get a handle to the HookDataStruct object in the managed heap, we will use this
            // handle to get the object back in the callback function
            GCHandle EncodingFrameEndUserHookDataHandle = GCHandle.Alloc(EncodingFrameEndUserHookData);

            // Register the encoding end function to the sequence context.
            MIL_SEQ_HOOK_FUNCTION_PTR FrameEncodingEndFunctionDelegate = new MIL_SEQ_HOOK_FUNCTION_PTR(FrameEncodingEndFunction);

            MIL.MseqHookFunction(MilCompressContext, MIL.M_FRAME_END, FrameEncodingEndFunctionDelegate, GCHandle.ToIntPtr(EncodingFrameEndUserHookDataHandle));

            // Provide a sample image to initialize the encoding engine accordingly.
            MIL.MseqControl(MilCompressContext, MIL.M_CONTEXT, MIL.M_BUFFER_SAMPLE, MilGrabBufferList[0]);

            // Start the encoding process, waits for buffer to be fed for encoding.
            MIL.MseqProcess(MilCompressContext, MIL.M_START, MIL.M_ASYNCHRONOUS);

            // Display the type of compression used.
            Console.Write("Live image capture and compression to file using ");
            MIL.MseqInquire(MilCompressContext, MIL.M_CONTEXT, MIL.M_CODEC_TYPE, ref SeqSystemType);
            if (SeqSystemType == MIL.M_HARDWARE + MIL.M_QSV)
            {
                Console.WriteLine("Hardware acceleration.");
            }
            else // MIL.M_SOFTWARE + MIL.M_QSV
            {
                Console.WriteLine("Software implementation.");
            }

            // Set the sequence context id in the user hook data structure to start
            // feeding buffers for encoding in ProcessingFunction.
            //
            ProcessingUserHookData.MilSeqContext       = MilCompressContext;
            ProcessingUserHookData.ProcessedImageCount = 0;
            ProcessingUserHookData.ProcessingOperation = ProcessingHookOperation.ENCODE;

            MIL.MdigProcess(MilDigitizer, MilGrabBufferList, MilGrabBufferListSize, MIL.M_START, MIL.M_DEFAULT, ProcessingFunctionDelegate, GCHandle.ToIntPtr(hUserData));

            // NOTE: Now the main() is free to perform other tasks while the compression is executing.
            // ---------------------------------------------------------------------------------------

            // Print a message and wait for a key press after a minimum number of frames.
            Console.WriteLine("Press <Enter> to stop.\n");
            Console.ReadKey();

            // Stop the processing.
            MIL.MdigProcess(MilDigitizer, MilGrabBufferList, MilGrabBufferListSize, MIL.M_STOP + MIL.M_WAIT, MIL.M_DEFAULT, ProcessingFunctionDelegate, GCHandle.ToIntPtr(hUserData));

            // Free the processing user data handle.
            hUserData.Free();

            // Stop the encoding process
            MIL.MseqProcess(MilCompressContext, MIL.M_STOP, MIL.M_WAIT);

            // Make sure the hook handler function delegate is not prematurely garbage collected since
            // only MIL has a reference to it.
            GC.KeepAlive(FrameEncodingEndFunctionDelegate);

            // Free the encoding user data handle.
            EncodingFrameEndUserHookDataHandle.Free();

            // Print statistics.
            MIL.MdigInquire(MilDigitizer, MIL.M_PROCESS_FRAME_COUNT, ref ProcessFrameCount);
            MIL.MdigInquire(MilDigitizer, MIL.M_PROCESS_FRAME_RATE, ref ProcessFrameRate);
            Console.WriteLine("{0} frames encoded at {1:0.00} frames/sec ({2:0.0} ms/frame).", ProcessFrameCount, ProcessFrameRate, 1000.0 / ProcessFrameRate);
            Console.WriteLine();

            MIL.MseqInquire(MilCompressContext, MIL.M_SEQ_OUTPUT(0) + MIL.M_SEQ_DEST(0), MIL.M_STREAM_FILE_NAME_SIZE, ref SeqProcessFilePathSize);
            SeqProcessFilePath = new StringBuilder((int)SeqProcessFilePathSize);
            MIL.MseqInquire(MilCompressContext, MIL.M_SEQ_OUTPUT(0) + MIL.M_SEQ_DEST(0), MIL.M_STREAM_FILE_NAME, SeqProcessFilePath);
            Console.WriteLine("The video sequence file was written to:");
            Console.WriteLine("{0}.", SeqProcessFilePath.ToString());
            Console.WriteLine();
            Console.WriteLine("It can be played back using any compatible video player.");

            // Free the grab buffers and sequence context.
            while (MilGrabBufferListSize > 0)
            {
                MIL.MbufFree(MilGrabBufferList[--MilGrabBufferListSize]);
                MilGrabBufferList[MilGrabBufferListSize] = MIL.M_NULL;
            }

            MIL.MseqFree(MilCompressContext);

            // Wait for a key to start the replay.
            Console.WriteLine("Press <Enter> to replay encoded sequence.");
            Console.ReadKey();

            MIL.MseqAlloc(MilSystem, MIL.M_DEFAULT, MIL.M_SEQ_DECOMPRESS,
                          MIL.M_DEFAULT, MIL.M_DEFAULT, ref MilDecompressContext);

            // Specify the destination of the compressed file and the target container type.
            // The last argument specifies to generate an MP4 file.
            MIL.MseqDefine(MilDecompressContext, MIL.M_SEQ_INPUT(0), MIL.M_FILE,
                           (MilSystemLocation != MIL.M_REMOTE ? SEQUENCE_FILE : REMOTE_SEQUENCE_FILE),
                           MIL.M_FILE_FORMAT_MP4);

            double outputFrameRate = 0.0;

            MIL.MseqInquire(MilDecompressContext, MIL.M_SEQ_INPUT(0), MIL.M_STREAM_FRAME_RATE, ref outputFrameRate);

            Console.WriteLine();
            Console.WriteLine("Replaying file at {0:0.00} frames/second.", outputFrameRate);

            // Initialize the optional decoding end function data structure.
            DecodingFrameEndUserHookData.DecodedImageCount = 0;
            DecodingFrameEndUserHookData.MilImageDisp      = MilImageDisp;

            // get a handle to the HookDataStruct object in the managed heap, we will use this
            // handle to get the object back in the callback function
            GCHandle DecodingFrameEndUserHookDataHandle = GCHandle.Alloc(DecodingFrameEndUserHookData);

            // Register the decoding end function to the sequence context.
            MIL_SEQ_HOOK_FUNCTION_PTR FrameDecodingEndFunctionDelegate = new MIL_SEQ_HOOK_FUNCTION_PTR(FrameDecodingEndFunction);

            MIL.MseqHookFunction(MilDecompressContext, MIL.M_FRAME_END, FrameDecodingEndFunctionDelegate, GCHandle.ToIntPtr(DecodingFrameEndUserHookDataHandle));

            // Start the decoding process, waits for buffer to be fed for encoding.
            MIL.MseqProcess(MilDecompressContext, MIL.M_START, MIL.M_ASYNCHRONOUS);

            // Print a message and wait for a key press after a minimum number of frames.
            Console.WriteLine("Press <Enter> to stop.\n");
            Console.ReadKey();

            // Stop the play back.
            MIL.MseqProcess(MilDecompressContext, MIL.M_STOP, MIL.M_NULL);

            // Make sure the hook handler function delegate is not prematurely garbage collected since
            // only MIL has a reference to it.
            GC.KeepAlive(FrameDecodingEndFunctionDelegate);

            // Free the decoding user data handle.
            DecodingFrameEndUserHookDataHandle.Free();

            MIL.MseqFree(MilDecompressContext);

            // Wait for a key to end.
            Console.WriteLine("Press <Enter> to end.");
            Console.ReadKey();

            // Release defaults.
            MIL.MappFreeDefault(MilApplication, MilSystem, MilDisplay, MilDigitizer, MilImageDisp);

            return(0);
        }
Ejemplo n.º 11
0
        static void Main(string[] args)
        {
            MIL_ID MilApplication = MIL.M_NULL;                             // Application identifier.
            MIL_ID MilSystem      = MIL.M_NULL;                             // System identifier.
            MIL_ID MilDisplay     = MIL.M_NULL;                             // Display identifier.
            MIL_ID MilGraphicList = MIL.M_NULL;                             // graphic list identifier.

            MIL_ID[] MilSourceImages = new MIL_ID[NUM_IMAGES_TO_REGISTER];  // Source images buffer identifiers.
            MIL_ID   MilMosaicImage  = MIL.M_NULL;                          // Mosaic image buffer identifier.
            MIL_ID   MilRegContext   = MIL.M_NULL;                          // Registration context identifier.
            MIL_ID   MilRegResult    = MIL.M_NULL;                          // Registration result identifier.
            MIL_INT  Result          = 0;                                   // Result of the registration.
            MIL_INT  MosaicSizeX     = 0;                                   // Size of the mosaic.
            MIL_INT  MosaicSizeY     = 0;
            MIL_INT  MosaicSizeBand  = 0;                                   // Characteristics of mosaic image.
            MIL_INT  MosaicType      = 0;

            string[] ImageFilesSource = new string[NUM_IMAGES_TO_REGISTER];

            // Allocate defaults
            MIL.MappAllocDefault(MIL.M_DEFAULT, ref MilApplication, ref MilSystem, ref MilDisplay, MIL.M_NULL, MIL.M_NULL);

            // Load source image names.
            for (int i = 0; i < NUM_IMAGES_TO_REGISTER; i++)
            {
                ImageFilesSource[i] = String.Format(IMAGE_FILES_SOURCE, i);
            }

            // Print module name.
            Console.Write("\nREGISTRATION MODULE:\n");
            Console.Write("---------------------\n\n");

            // Print comment.
            Console.Write("This program will make a mosaic from many source images.\n");
            Console.Write("Press <Enter> to continue.\n\n");
            Console.ReadKey();

            // Restore the source images.
            for (int i = 0; i < NUM_IMAGES_TO_REGISTER; i++)
            {
                MIL.MbufRestore(ImageFilesSource[i], MilSystem, ref MilSourceImages[i]);
            }

            // Display the source images.
            for (int i = 0; i < NUM_IMAGES_TO_REGISTER; i++)
            {
                MIL.MdispSelect(MilDisplay, MilSourceImages[i]);

                // Pause to show each image.
                Console.Write("image {0}.\n", i);
                Console.Write("Press <Enter> to continue.\n\n");
                Console.ReadKey();
            }

            // Allocate a graphic list to hold the subpixel annotations to draw.
            MIL.MgraAllocList(MilSystem, MIL.M_DEFAULT, ref MilGraphicList);
            MIL.MdispControl(MilDisplay, MIL.M_ASSOCIATED_GRAPHIC_LIST_ID, MilGraphicList);

            // Allocate a new empty registration context.
            MIL.MregAlloc(MilSystem, MIL.M_CORRELATION, MIL.M_DEFAULT, ref MilRegContext);

            // Allocate a new empty registration result buffer.
            MIL.MregAllocResult(MilSystem, MIL.M_DEFAULT, ref MilRegResult);

            // Set the transformation type to translation.
            MIL.MregControl(MilRegContext, MIL.M_CONTEXT, MIL.M_TRANSFORMATION_TYPE, MIL.M_TRANSLATION);

            // By default, each image will be registered with the previous in the list
            // No need to set other location parameters.

            // Set range to 100% in order to search all possible translations.
            MIL.MregControl(MilRegContext, MIL.M_CONTEXT, MIL.M_LOCATION_DELTA, 100);

            // Calculate the registration on the images.
            MIL.MregCalculate(MilRegContext, MilSourceImages, MilRegResult, NUM_IMAGES_TO_REGISTER, MIL.M_DEFAULT);

            // Verify if registration is successful.
            MIL.MregGetResult(MilRegResult, MIL.M_GENERAL, MIL.M_RESULT + MIL.M_TYPE_MIL_INT, ref Result);
            if (Result == MIL.M_SUCCESS)
            {
                // Get the size of the required mosaic buffer.
                MIL.MregGetResult(MilRegResult, MIL.M_GENERAL, MIL.M_MOSAIC_SIZE_X + MIL.M_TYPE_MIL_INT, ref MosaicSizeX);
                MIL.MregGetResult(MilRegResult, MIL.M_GENERAL, MIL.M_MOSAIC_SIZE_Y + MIL.M_TYPE_MIL_INT, ref MosaicSizeY);

                // The mosaic type will be the same as the source images.
                MIL.MbufInquire(MilSourceImages[0], MIL.M_SIZE_BAND, ref MosaicSizeBand);
                MIL.MbufInquire(MilSourceImages[0], MIL.M_TYPE, ref MosaicType);

                // Allocate mosaic image.
                MIL.MbufAllocColor(MilSystem, MosaicSizeBand, MosaicSizeX, MosaicSizeY, MosaicType, MIL.M_IMAGE + MIL.M_PROC + MIL.M_DISP, ref MilMosaicImage);

                // Compose the mosaic from the source images.
                MIL.MregTransformImage(MilRegResult, MilSourceImages, MilMosaicImage, NUM_IMAGES_TO_REGISTER, MIL.M_BILINEAR + MIL.M_OVERSCAN_CLEAR, MIL.M_DEFAULT);

                // Display the mosaic image and prepare for overlay annotations.
                MIL.MdispSelect(MilDisplay, MilMosaicImage);
                MIL.MgraColor(MIL.M_DEFAULT, MIL.M_RGB888(0, 0xFF, 0));

                // Pause to show the mosaic.
                Console.Write("mosaic image.\n");
                Console.Write("Press <Enter> to continue.\n\n");
                Console.ReadKey();

                // Draw the box of all source images in the mosaic.
                MIL.MregDraw(MIL.M_DEFAULT, MilRegResult, MilGraphicList, MIL.M_DRAW_BOX, MIL.M_ALL, MIL.M_DEFAULT);

                // Draw a cross at the center of each image in the mosaic.
                for (int i = 0; i < NUM_IMAGES_TO_REGISTER; i++)
                {
                    // Coordinates of the center of the source image.
                    double SourcePosX = 0.5 * (double)MIL.MbufInquire(MilSourceImages[i], MIL.M_SIZE_X, MIL.M_NULL);
                    double SourcePosY = 0.5 * (double)MIL.MbufInquire(MilSourceImages[i], MIL.M_SIZE_Y, MIL.M_NULL);

                    // Transform the coordinates to the mosaic.
                    double MosaicPosX = 0;
                    double MosaicPosY = 0;
                    MIL.MregTransformCoordinate(MilRegResult, i, MIL.M_MOSAIC, SourcePosX, SourcePosY, ref MosaicPosX, ref MosaicPosY, MIL.M_DEFAULT);
                    int MosaicPosXMilInt = (int)(MosaicPosX + 0.5);
                    int MosaicPosYMilInt = (int)(MosaicPosY + 0.5);

                    // Draw the cross in the mosaic.
                    MIL.MgraLine(MIL.M_DEFAULT, MilGraphicList, MosaicPosXMilInt - 4, MosaicPosYMilInt, MosaicPosXMilInt + 4, MosaicPosYMilInt);
                    MIL.MgraLine(MIL.M_DEFAULT, MilGraphicList, MosaicPosXMilInt, MosaicPosYMilInt - 4, MosaicPosXMilInt, MosaicPosYMilInt + 4);
                }

                Console.Write("The bounding boxes and the center of all source images\n");
                Console.Write("have been drawn in the mosaic.\n");
            }
            else
            {
                Console.Write("Error: Registration was not successful.\n");
            }

            // Pause to show results.
            Console.Write("\nPress <Enter> to end.\n\n");
            Console.ReadKey();

            // Free all allocations.
            MIL.MgraFree(MilGraphicList);
            if (MilMosaicImage != MIL.M_NULL)
            {
                MIL.MbufFree(MilMosaicImage);
            }

            MIL.MregFree(MilRegContext);
            MIL.MregFree(MilRegResult);

            for (int i = 0; i < NUM_IMAGES_TO_REGISTER; i++)
            {
                MIL.MbufFree(MilSourceImages[i]);
            }

            // Free defaults.
            MIL.MappFreeDefault(MilApplication, MilSystem, MilDisplay, MIL.M_NULL, MIL.M_NULL);
        }
Ejemplo n.º 12
0
        static void Main(string[] args)
        {
            MIL_ID MilApplication = MIL.M_NULL;          // Application identifier.
            MIL_ID MilSystem      = MIL.M_NULL;          // System identifier.
            MIL_ID MilDisplay     = MIL.M_NULL;          // Display identifier.
            MIL_ID MilDigitizer   = MIL.M_NULL;          // Digitizer identifier.
            MIL_ID MilImage       = MIL.M_NULL;          // Image identifier.

            // Allocate defaults
            MIL.MappAllocDefault(MIL.M_DEFAULT, ref MilApplication, ref MilSystem, ref MilDisplay, MIL.M_NULL, MIL.M_NULL);

            // If the system have a digitizer, use it.
            if (MIL.MsysInquire(MilSystem, MIL.M_DIGITIZER_NUM, MIL.M_NULL) > 0)
            {
                MIL.MdigAlloc(MilSystem, MIL.M_DEFAULT, "M_DEFAULT", MIL.M_DEFAULT, ref MilDigitizer);
                MIL.MbufAllocColor(MilSystem,
                                   MIL.MdigInquire(MilDigitizer, MIL.M_SIZE_BAND, MIL.M_NULL),
                                   MIL.MdigInquire(MilDigitizer, MIL.M_SIZE_X, MIL.M_NULL),
                                   MIL.MdigInquire(MilDigitizer, MIL.M_SIZE_Y, MIL.M_NULL),
                                   8 + MIL.M_UNSIGNED,
                                   MIL.M_IMAGE + MIL.M_DISP + MIL.M_PROC + MIL.M_GRAB,
                                   ref MilImage);
                MIL.MbufClear(MilImage, 0);
            }
            else
            {
                // Restore a static image.
                MIL.MbufRestore(IMAGE_FILE, MilSystem, ref MilImage);
            }

            // Change display window title.
            MIL.MdispControl(MilDisplay, MIL.M_TITLE, WINDOW_TITLE);

            // Display the image buffer.
            MIL.MdispSelect(MilDisplay, MilImage);

            // Draw text and graphics annotations in the display overlay.
            OverlayDraw(MilDisplay);

            // If the system supports it, grab continuously in the displayed image.
            if (MilDigitizer != MIL.M_NULL)
            {
                MIL.MdigGrabContinuous(MilDigitizer, MilImage);
            }

            // Pause to show the image.
            Console.Write("\nOVERLAY ANNOTATIONS:\n");
            Console.Write("--------------------\n\n");
            Console.Write("Displaying an image with overlay annotations.\n");
            Console.Write("Press <Enter> to continue.\n\n");
            Console.ReadKey();

            // Stop the continuous grab and free digitizer if needed.
            if (MilDigitizer != MIL.M_NULL)
            {
                MIL.MdigHalt(MilDigitizer);
                MIL.MdigFree(MilDigitizer);

                // Pause to show the result.
                Console.Write("Displaying the last grabbed image.\n");
                Console.Write("Press <Enter> to end.\n\n");
                Console.ReadKey();
            }

            // Free image.
            MIL.MbufFree(MilImage);

            // Free default allocations.
            MIL.MappFreeDefault(MilApplication, MilSystem, MilDisplay, MIL.M_NULL, MIL.M_NULL);
        }
Ejemplo n.º 13
0
        static void GrabDeinterlace(MIL_ID MilSystem)
        {
            MIL_ID MilDigitizer          = MIL.M_NULL; /* Digitizer identifier.           */
            MIL_ID MilDisplay            = MIL.M_NULL; /* Display identifier.             */
            MIL_ID MilDisplayImage       = MIL.M_NULL; /* Image buffer identifier.        */
            MIL_ID MilDeinterlaceContext = MIL.M_NULL; /* Deinterlace context identifier. */

            MIL_ID[] MilGrabImages     = new MIL_ID[NUM_GRAB_IMAGES];
            MIL_ID[] MilPreviousImages = new MIL_ID[MOTION_DETECT_NUM_FRAMES];
            MIL_INT  ImageSizeBand     = 0;
            MIL_INT  ImageWidth        = 0;
            MIL_INT  ImageHeight       = 0;;
            int      i = 0;
            int      CurrentGrabIndex = 0;
            int      NextGrabIndex    = 0;

            /* Try to allocate a digitizer. */
            MIL.MdigAlloc(MilSystem, MIL.M_DEFAULT, "M_DEFAULT", MIL.M_DEFAULT, ref MilDigitizer);
            if (MilDigitizer == MIL.M_NULL)
            {
                return;
            }

            /* Inquire characteristics of the digitizer. */
            MIL.MdigInquire(MilDigitizer, MIL.M_SIZE_BAND, ref ImageSizeBand);
            MIL.MdigInquire(MilDigitizer, MIL.M_SIZE_X, ref ImageWidth);
            MIL.MdigInquire(MilDigitizer, MIL.M_SIZE_Y, ref ImageHeight);

            /* Allocate grab images. */
            for (i = 0; i < NUM_GRAB_IMAGES; i++)
            {
                MIL.MbufAllocColor(MilSystem,
                                   ImageSizeBand,
                                   ImageWidth,
                                   ImageHeight,
                                   8 + MIL.M_UNSIGNED,
                                   MIL.M_IMAGE + MIL.M_GRAB + MIL.M_PROC,
                                   ref MilGrabImages[i]);
            }

            /* Allocate a deinterlacing context. */
            MIL.MimAlloc(MilSystem, MIL.M_DEINTERLACE_CONTEXT, MIL.M_DEFAULT, ref MilDeinterlaceContext);

            /* Allocate new display and display image. */
            MIL.MbufAllocColor(MilSystem,
                               ImageSizeBand,
                               ImageWidth,
                               ImageHeight,
                               8 + MIL.M_UNSIGNED,
                               MIL.M_IMAGE + MIL.M_GRAB + MIL.M_DISP + MIL.M_PROC,
                               ref MilDisplayImage);
            MIL.MdispAlloc(MilSystem,
                           MIL.M_DEFAULT,
                           "M_DEFAULT",
                           MIL.M_DEFAULT,
                           ref MilDisplay);
            MIL.MbufClear(MilDisplayImage, 0);
            MIL.MdispSelect(MilDisplay, MilDisplayImage);

            /* Print a message. */
            Console.Write("Normal live grab is displayed.\n");
            Console.Write("Press <Enter> to continue.\n\n");

            /* Grab continuously on display and wait for a key press. */
            MIL.MdigGrabContinuous(MilDigitizer, MilDisplayImage);
            Console.ReadKey();

            /* Halt continuous grab. */
            MIL.MdigHalt(MilDigitizer);

            /* Configure the Deinterlace context for the appropriate live deinterlacing method. */
            MIL.MimControl(MilDeinterlaceContext, MIL.M_DEINTERLACE_TYPE, GRAB_DEINTERLACE_METHOD);
            if (GRAB_DEINTERLACE_METHOD == MIL.M_ADAPTIVE_DISCARD || GRAB_DEINTERLACE_METHOD == MIL.M_ADAPTIVE_AVERAGE)
            {
                MIL.MimControl(MilDeinterlaceContext, MIL.M_MOTION_DETECT_NUM_FRAMES, MOTION_DETECT_NUM_FRAMES);
                MIL.MimControl(MilDeinterlaceContext, MIL.M_MOTION_DETECT_THRESHOLD, MOTION_DETECT_THRESHOLD);
            }

            /* Set the digitizer to asynchronous grab. */
            MIL.MdigControl(MilDigitizer, MIL.M_GRAB_MODE, MIL.M_ASYNCHRONOUS);

            /* Send the first grab to the digitizer. */
            MIL.MdigGrab(MilDigitizer, MilGrabImages[0]);
            CurrentGrabIndex = 0;
            NextGrabIndex    = 1;

            /* Print a message. */
            Console.Write("Deinterlaced live grab is displayed.\n");
            Console.Write("Press <Enter> to stop.\n\n");

            /* Grab and process. */
            while (!Console.KeyAvailable)
            {
                /* Send the next grab command to the digitizer. This will block until the current grab is finished. */
                MIL.MdigGrab(MilDigitizer, MilGrabImages[NextGrabIndex]);

                if ((GRAB_DEINTERLACE_METHOD != MIL.M_ADAPTIVE_DISCARD) && (GRAB_DEINTERLACE_METHOD != MIL.M_ADAPTIVE_AVERAGE))
                {
                    /* Deinterlace the current grabbed image. */
                    MIL.MimDeinterlace(MilDeinterlaceContext, ref MilGrabImages[CurrentGrabIndex], ref MilDisplayImage, 1, 1, MIL.M_DEFAULT);
                }
                else
                {
                    /* Build the table of the last MOTION_DETECT_NUM_FRAMES grabbed frames. */
                    for (i = 0; i < MOTION_DETECT_NUM_FRAMES; i++)
                    {
                        int PreviousGrabIndex = NextGrabIndex - MOTION_DETECT_NUM_FRAMES + i;
                        if (PreviousGrabIndex < 0)
                        {
                            PreviousGrabIndex += NUM_GRAB_IMAGES;
                        }
                        MilPreviousImages[i] = MilGrabImages[PreviousGrabIndex];
                    }

                    /* Deinterlace the previous grabbed images. */
                    MIL.MimDeinterlace(MilDeinterlaceContext, MilPreviousImages, ref MilDisplayImage, MOTION_DETECT_NUM_FRAMES, 1, MIL.M_DEFAULT);
                }

                /* Increment grab index. */
                CurrentGrabIndex = NextGrabIndex;
                NextGrabIndex    = (NextGrabIndex + 1) % NUM_GRAB_IMAGES;
            }
            Console.ReadKey();

            /* Display the last grabbed image. */
            Console.Write("Last deinterlaced image displayed.\n");
            Console.Write("Press <Enter> to end.\n\n");
            Console.ReadKey();

            /* Free objects. */
            MIL.MimFree(MilDeinterlaceContext);
            MIL.MbufFree(MilDisplayImage);
            MIL.MdispFree(MilDisplay);
            for (i = 0; i < NUM_GRAB_IMAGES; i++)
            {
                MIL.MbufFree(MilGrabImages[i]);
            }
            MIL.MdigFree(MilDigitizer);
        }
Ejemplo n.º 14
0
        // Main function.
        // --------------
        static void Main(string[] args)
        {
            MIL_ID  MilApplication        = MIL.M_NULL; /* Application identifier.         */
            MIL_ID  MilSystem             = MIL.M_NULL; /* System identifier.              */
            MIL_ID  MilDisplay            = MIL.M_NULL; /* Display identifier.             */
            MIL_ID  MilDisplayImage       = MIL.M_NULL; /* Image buffer identifier.        */
            MIL_ID  MilSourceImage        = MIL.M_NULL; /* Image buffer identifier.        */
            MIL_ID  MilDeinterlaceContext = MIL.M_NULL; /* Deinterlace context identifier. */
            MIL_INT ImageSizeBand         = 0;
            MIL_INT ImageWidth            = 0;
            MIL_INT ImageHeight           = 0;
            MIL_INT ImageType             = 0;

            /* Allocate defaults. */
            MIL.MappAllocDefault(MIL.M_DEFAULT, ref MilApplication, ref MilSystem, ref MilDisplay, MIL.M_NULL, MIL.M_NULL);

            /* Restore the source image. */
            MIL.MbufRestore(IMAGE_FILE, MilSystem, ref MilSourceImage);

            /* Allocate a display buffers and show the source image. */
            MIL.MbufInquire(MilSourceImage, MIL.M_SIZE_BAND, ref ImageSizeBand);
            MIL.MbufInquire(MilSourceImage, MIL.M_SIZE_X, ref ImageWidth);
            MIL.MbufInquire(MilSourceImage, MIL.M_SIZE_Y, ref ImageHeight);
            MIL.MbufInquire(MilSourceImage, MIL.M_TYPE, ref ImageType);
            MIL.MbufAllocColor(MilSystem, ImageSizeBand, ImageWidth, ImageHeight, ImageType, MIL.M_IMAGE + MIL.M_PROC + MIL.M_DISP, ref MilDisplayImage);
            MIL.MbufCopy(MilSourceImage, MilDisplayImage);
            MIL.MdispSelect(MilDisplay, MilDisplayImage);

            /* Allocate a deinterlacing context. */
            MIL.MimAlloc(MilSystem, MIL.M_DEINTERLACE_CONTEXT, MIL.M_DEFAULT, ref MilDeinterlaceContext);

            /* Print a message. */
            Console.Write("\nDEINTERLACING:\n");
            Console.Write("----------------\n\n");
            Console.Write("This image has been grabbed using an interlaced camera.\n");
            Console.Write("Press <Enter> to continue.\n\n");
            Console.ReadKey();

            /* Deinterlace using MIL.M_DISCARD. */
            MIL.MimControl(MilDeinterlaceContext, MIL.M_DEINTERLACE_TYPE, MIL.M_DISCARD);
            MIL.MimDeinterlace(MilDeinterlaceContext, ref MilSourceImage, ref MilDisplayImage, 1, 1, MIL.M_DEFAULT);

            /* Display message. */
            Console.Write("The image has been deinterlaced using the DISCARD algorithm.\n");
            Console.Write("Press <Enter> to continue.\n\n");
            Console.ReadKey();

            /* Free objects. */
            MIL.MbufFree(MilSourceImage);
            MIL.MbufFree(MilDisplayImage);
            MIL.MdispFree(MilDisplay);
            MIL.MimFree(MilDeinterlaceContext);

            /* If the system has a digitizer, use it to do live deinterlacing. */
            if (MIL.MsysInquire(MilSystem, MIL.M_DIGITIZER_NUM, MIL.M_NULL) > 0)
            {
                GrabDeinterlace(MilSystem);
            }

            /* Free objects. */
            MIL.MappFreeDefault(MilApplication, MilSystem, MIL.M_NULL, MIL.M_NULL, MIL.M_NULL);
        }
Ejemplo n.º 15
0
        public void Grab_Image()
        {
            //변수 선언
            MIL_INT Image_Size     = 450;
            MIL_INT Buf_Define     = 25;
            MIL_ID  MilApplication = MIL.M_NULL;
            MIL_ID  MilSystem      = MIL.M_NULL;
            MIL_ID  MilDisplay     = MIL.M_NULL;
            MIL_ID  MilDigiti      = MIL.M_NULL;

            MIL_ID[] Milimage        = new MIL_ID[25];
            string[] FileName        = new string[25];
            String[] strPathFileName = new String[25];
            Image[]  Img             = new Image[25];
            String   File_temp       = string.Empty;

            //ALLOC 설정
            MIL.MappAlloc(MIL.M_DEFAULT, ref MilApplication);
            MIL.MsysAlloc(MIL.M_SYSTEM_SOLIOS, MIL.M_DEV0, MIL.M_DEFAULT, ref MilSystem);

            //DCF상에서 450 * 25 사이즈에 대하여 영상획득하게 설정되어 있습니다. 바꾸시길 원하시면 DCF상에서 바꾸시고 소스상에서
            //MIL_INT Image_Size = 450; MIL_INT Buf_Define = 25; 값들을 변경하여 주시면 됩니다.
            //제가 원한사이즈는 4096 * 11250 ( 450 사이즈에 대하여 25번 GRAB하였습니다.)

            for (int i = 0; i < Buf_Define; i++)
            {
                MIL.MbufAllocColor(MilSystem, 3, 4096, Image_Size, 8 + MIL.M_UNSIGNED, MIL.M_IMAGE + MIL.M_GRAB + MIL.M_DISP, ref Milimage[i]);
            }

            MIL.MdispAlloc(MilSystem, MIL.M_DEFAULT, "M_DEFAULT", MIL.M_DEFAULT, ref MilDisplay);
            MIL.MdigAlloc(MilSystem, MIL.M_DEFAULT, "scan.dcf", MIL.M_DEFAULT, ref MilDigiti);
            MIL.MdigControl(MilDigiti, MIL.M_CAMERALINK_CC3_SOURCE, MIL.M_GRAB_EXPOSURE);
            SaveFileDialog SaveFile = new SaveFileDialog();

            //파일저장 경로 설정 -> 윈도우폼으로 저장경로 설정
            SaveFile.DefaultExt = "jpg";
            SaveFile.Filter     = "*.jpg|*.jpg| *.mim|*.mim| *.tif|*.tif";
            if (SaveFile.ShowDialog() == DialogResult.OK)
            {
                File_temp = SaveFile.FileName;
            }

            //위에 경로에 대하여 이미지 저장
            for (int i = 0; i < Buf_Define; i++)
            {
                MIL.MbufClear(Milimage[i], 0);
                MIL.MdispSelect(MilDisplay, Milimage[i]);
                MIL.MdigGrab(MilDigiti, Milimage[i]);
            }

            //Filename changed.
            //File_temp
            for (int j = 0; j < Buf_Define; j++)
            {
                FileName[j] = File_temp.Replace(".jpg", "_" + j + ".jpg");
                MIL.MbufExport(FileName[j], MIL.M_JPEG_LOSSY, Milimage[j]);
            }

            //ALLOC 해제
            for (int i = 0; i < Buf_Define; i++)
            {
                MIL.MbufFree(Milimage[i]);
            }

            MIL.MdigFree(MilDigiti);
            MIL.MdispFree(MilDisplay);
            MIL.MsysFree(MilSystem);
        }
Ejemplo n.º 16
0
        //**************************************************************************
        //
        // Name:         MilApplication()
        //
        // Synopsis:     This function is the core of the MIL application that
        //               is executed when the "Start" menu item of this
        //               Windows forms program is selected. See main() in the
        //               program.cs file for the program's entry point.
        //
        //               It uses MIL to display a welcoming message in the
        //               specified user window and to grab in it (if it is supported)
        //               using the target system.
        //
        //**************************************************************************
        private void MilApplication(IntPtr UserWindowHandle)
        {
            // MIL variables
            MIL_ID  MilApplication = MIL.M_NULL; // MIL Application identifier.
            MIL_ID  MilSystem      = MIL.M_NULL; // MIL System identifier.
            MIL_ID  MilDisplay     = MIL.M_NULL; // MIL Display identifier.
            MIL_ID  MilDigitizer   = MIL.M_NULL; // MIL Digitizer identifier.
            MIL_ID  MilImage       = MIL.M_NULL; // MIL Image buffer identifier.
            MIL_INT BufSizeX       = DEFAULT_IMAGE_SIZE_X;
            MIL_INT BufSizeY       = DEFAULT_IMAGE_SIZE_Y;
            MIL_INT BufSizeBand    = DEFAULT_IMAGE_SIZE_BAND;

            // Allocate a MIL application.
            MIL.MappAlloc(MIL.M_NULL, MIL.M_DEFAULT, ref MilApplication);

            // Allocate a MIL system.
            MIL.MsysAlloc(MIL.M_DEFAULT, "M_DEFAULT", MIL.M_DEFAULT, MIL.M_DEFAULT, ref MilSystem);

            // Allocate a MIL display.
            MIL.MdispAlloc(MilSystem, MIL.M_DEFAULT, "M_DEFAULT", MIL.M_WINDOWED, ref MilDisplay);

            // Allocate a MIL digitizer, if supported, and set the target image size.
            if (MIL.MsysInquire(MilSystem, MIL.M_DIGITIZER_NUM, MIL.M_NULL) > 0)
            {
                MIL.MdigAlloc(MilSystem, MIL.M_DEFAULT, "M_DEFAULT", MIL.M_DEFAULT, ref MilDigitizer);
                MIL.MdigInquire(MilDigitizer, MIL.M_SIZE_X, ref BufSizeX);
                MIL.MdigInquire(MilDigitizer, MIL.M_SIZE_Y, ref BufSizeY);
                MIL.MdigInquire(MilDigitizer, MIL.M_SIZE_BAND, ref BufSizeBand);

                // Resize the display window
                if ((BufSizeX > DEFAULT_IMAGE_SIZE_X) || (BufSizeY > DEFAULT_IMAGE_SIZE_Y))
                {
                    FromHandle(UserWindowHandle).Size = new Size((int)BufSizeX, (int)BufSizeY);
                }
            }

            // Allocate a MIL buffer.
            long Attributes = MIL.M_IMAGE + MIL.M_DISP;

            if (MilDigitizer != MIL.M_NULL)
            {
                // Add M_GRAB attribute if a digitizer is allocated.
                Attributes |= MIL.M_GRAB;
            }
            MIL.MbufAllocColor(MilSystem, BufSizeBand, BufSizeX, BufSizeY, 8 + MIL.M_UNSIGNED, Attributes, ref MilImage);

            // Clear the buffer.
            MIL.MbufClear(MilImage, 0);

            // Select the MIL buffer to be displayed in the user-specified window.
            MIL.MdispSelectWindow(MilDisplay, MilImage, UserWindowHandle);

            // Print a string in the image buffer using MIL.
            // Note: When a MIL buffer is modified using a MIL command, the display
            // automatically updates the window passed to MIL.MdispSelectWindow().

            MIL.MgraFont(MIL.M_DEFAULT, MIL.M_FONT_DEFAULT_LARGE);
            MIL.MgraText(MIL.M_DEFAULT, MilImage, (BufSizeX / 8) * 2, BufSizeY / 2, " Welcome to MIL !!! ");
            MIL.MgraRect(MIL.M_DEFAULT, MilImage, ((BufSizeX / 8) * 2) - 60, (BufSizeY / 2) - 80, ((BufSizeX / 8) * 2) + 370, (BufSizeY / 2) + 100);
            MIL.MgraRect(MIL.M_DEFAULT, MilImage, ((BufSizeX / 8) * 2) - 40, (BufSizeY / 2) - 60, ((BufSizeX / 8) * 2) + 350, (BufSizeY / 2) + 80);
            MIL.MgraRect(MIL.M_DEFAULT, MilImage, ((BufSizeX / 8) * 2) - 20, (BufSizeY / 2) - 40, ((BufSizeX / 8) * 2) + 330, (BufSizeY / 2) + 60);

            // Open a message box to wait for a key press.
            MessageBox.Show("\"Welcome to MIL !!!\" was printed", "MIL application example", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

            // Grab in the user window if supported.
            if (MilDigitizer != MIL.M_NULL)
            {
                // Grab continuously.
                MIL.MdigGrabContinuous(MilDigitizer, MilImage);

                // Open a message box to wait for a key press.
                MessageBox.Show("Continuous grab in progress", "MIL application example", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                // Stop continuous grab.
                MIL.MdigHalt(MilDigitizer);
            }

            // Remove the MIL buffer from the display.
            MIL.MdispSelect(MilDisplay, MIL.M_NULL);

            // Free allocated objects.
            MIL.MbufFree(MilImage);

            if (MilDigitizer != MIL.M_NULL)
            {
                MIL.MdigFree(MilDigitizer);
            }

            MIL.MdispFree(MilDisplay);
            MIL.MsysFree(MilSystem);
            MIL.MappFree(MilApplication);
        }
Ejemplo n.º 17
0
        // Main function.
        // --------------
        static void Main(string[] args)
        {
            MIL_ID MilApplication       = MIL.M_NULL;
            MIL_ID MilRemoteApplication = MIL.M_NULL;   // Remote Application identifier if running on a remote computer
            MIL_ID MilSystem            = MIL.M_NULL;
            MIL_ID MilDigitizer         = MIL.M_NULL;
            MIL_ID MilDisplay           = MIL.M_NULL;
            MIL_ID MilImageDisp         = MIL.M_NULL;

            MIL_ID[]       MilGrabImages      = new MIL_ID[NB_GRAB_IMAGE_MAX];
            MIL_ID         MilCompressedImage = MIL.M_NULL;
            ConsoleKeyInfo Selection          = new ConsoleKeyInfo('1', ConsoleKey.D1, false, false, false);

            int            NbFrames          = 0;
            int            n                 = 0;
            int            NbFramesReplayed  = 0;
            double         FrameRate         = 0;
            double         TimeWait          = 0;
            double         TotalReplay       = 0;
            double         GrabScale         = GRAB_SCALE;
            HookDataObject UserHookData      = new HookDataObject();
            MIL_INT        LicenseModules    = 0;
            MIL_INT        FrameCount        = 0;
            MIL_INT        FrameMissed       = 0;
            MIL_INT        CompressAttribute = 0;

            // Allocate defaults.
            MIL.MappAllocDefault(MIL.M_DEFAULT, ref MilApplication, ref MilSystem, ref MilDisplay, ref MilDigitizer, MIL.M_NULL);

            // Allocate an image and display it.
            MIL.MbufAllocColor(MilSystem,
                               MIL.MdigInquire(MilDigitizer, MIL.M_SIZE_BAND, MIL.M_NULL),
                               (MIL_INT)(MIL.MdigInquire(MilDigitizer, MIL.M_SIZE_X) * GrabScale),
                               (MIL_INT)(MIL.MdigInquire(MilDigitizer, MIL.M_SIZE_Y) * GrabScale),
                               8 + MIL.M_UNSIGNED,
                               MIL.M_IMAGE + MIL.M_GRAB + MIL.M_DISP,
                               ref MilImageDisp);

            MIL.MbufClear(MilImageDisp, 0x0);
            MIL.MdispSelect(MilDisplay, MilImageDisp);

            // Grab continuously on display at the specified scale.
            MIL.MdigControl(MilDigitizer, MIL.M_GRAB_SCALE, GrabScale);
            MIL.MdigGrabContinuous(MilDigitizer, MilImageDisp);

            // Print a message
            Console.WriteLine();
            Console.WriteLine("SEQUENCE ACQUISITION:");
            Console.WriteLine("--------------------");
            Console.WriteLine();

            // Inquire MIL licenses.
            MIL.MsysInquire(MilSystem, MIL.M_OWNER_APPLICATION, ref MilRemoteApplication);
            MIL.MappInquire(MilRemoteApplication, MIL.M_LICENSE_MODULES, ref LicenseModules);

            // If sequence is saved to disk, select between grabbing an
            // uncompressed, JPEG or JPEG2000 sequence.
            if (SAVE_SEQUENCE_TO_DISK && ((LicenseModules & (MIL.M_LICENSE_JPEGSTD | MIL.M_LICENSE_JPEG2000)) != 0))
            {
                Console.WriteLine("Choose the sequence format:");
                Console.WriteLine("1) Uncompressed images.");
                if ((LicenseModules & MIL.M_LICENSE_JPEGSTD) != 0)
                {
                    Console.WriteLine("2) Compressed images with a lossy JPEG algorithm.");
                }
                if ((LicenseModules & MIL.M_LICENSE_JPEG2000) != 0)
                {
                    Console.WriteLine("3) Compressed images with a lossy JPEG 2000 algorithm.");
                }
                Selection = Console.ReadKey();
            }
            else
            {
                Console.WriteLine("Press <Enter> to record images.");
                Console.ReadKey();
            }


            // Set the buffer attribute.
            switch (Selection.Key)
            {
            case ConsoleKey.NumPad1:
            case ConsoleKey.D1:
            case ConsoleKey.Enter:
                Console.WriteLine();
                Console.WriteLine("Recording uncompressed images...");
                Console.WriteLine();
                CompressAttribute = MIL.M_NULL;
                break;

            case ConsoleKey.NumPad2:
            case ConsoleKey.D2:
                Console.WriteLine();
                Console.WriteLine("Recording JPEG images...");
                Console.WriteLine();
                CompressAttribute = MIL.M_COMPRESS + MIL.M_JPEG_LOSSY;
                break;

            case ConsoleKey.NumPad3:
            case ConsoleKey.D3:
                Console.WriteLine();
                Console.WriteLine("Recording JPEG 2000 images...");
                Console.WriteLine();
                CompressAttribute = MIL.M_COMPRESS + MIL.M_JPEG2000_LOSSY;
                break;

            default:
                Console.WriteLine();
                Console.WriteLine("Invalid selection !.");
                Console.WriteLine();
                Console.WriteLine("Using uncompressed images.");
                Console.WriteLine();
                CompressAttribute = MIL.M_NULL;
                while (Console.KeyAvailable)
                {
                    Console.ReadKey();
                }
                break;
            }

            // Allocate a compressed buffer if required.
            if (CompressAttribute != MIL.M_NULL)
            {
                MIL.MbufAllocColor(MilSystem,
                                   MIL.MdigInquire(MilDigitizer, MIL.M_SIZE_BAND, MIL.M_NULL),
                                   (int)(MIL.MdigInquire(MilDigitizer, MIL.M_SIZE_X, MIL.M_NULL) * GrabScale),
                                   (int)(MIL.MdigInquire(MilDigitizer, MIL.M_SIZE_Y, MIL.M_NULL) * GrabScale),
                                   8 + MIL.M_UNSIGNED,
                                   MIL.M_IMAGE + CompressAttribute,
                                   ref MilCompressedImage);

                MIL.MbufControl(MilCompressedImage, MIL.M_Q_FACTOR, COMPRESSION_Q_FACTOR);
            }

            // Allocate the grab buffers to hold the sequence buffering.
            MIL.MappControl(MIL.M_DEFAULT, MIL.M_ERROR, MIL.M_PRINT_DISABLE);
            for (NbFrames = 0, n = 0; n < NB_GRAB_IMAGE_MAX; n++)
            {
                MIL.MbufAllocColor(MilSystem,
                                   MIL.MdigInquire(MilDigitizer, MIL.M_SIZE_BAND, MIL.M_NULL),
                                   (int)(MIL.MdigInquire(MilDigitizer, MIL.M_SIZE_X, MIL.M_NULL) * GrabScale),
                                   (int)(MIL.MdigInquire(MilDigitizer, MIL.M_SIZE_Y, MIL.M_NULL) * GrabScale),
                                   8 + MIL.M_UNSIGNED,
                                   MIL.M_IMAGE + MIL.M_GRAB,
                                   ref MilGrabImages[n]);

                if (MilGrabImages[n] != MIL.M_NULL)
                {
                    NbFrames++;
                    MIL.MbufClear(MilGrabImages[n], 0xFF);
                }
                else
                {
                    break;
                }
            }
            MIL.MappControl(MIL.M_DEFAULT, MIL.M_ERROR, MIL.M_PRINT_ENABLE);

            // Free buffers to leave some space for possible temporary buffers.
            for (n = 0; n < 2 && NbFrames > 0; n++)
            {
                NbFrames--;
                MIL.MbufFree(MilGrabImages[NbFrames]);
            }

            // Halt continuous grab.
            MIL.MdigHalt(MilDigitizer);

            // Open the AVI file if required.
            if (SAVE_SEQUENCE_TO_DISK)
            {
                Console.WriteLine("Saving the sequence to an AVI file...");
                Console.WriteLine();
                MIL.MbufExportSequence(SEQUENCE_FILE, MIL.M_DEFAULT, MIL.M_NULL, MIL.M_NULL, MIL.M_DEFAULT, MIL.M_OPEN);
            }

            // Initialize User's archiving function hook data structure.
            UserHookData.MilSystem          = MilSystem;
            UserHookData.MilDisplay         = MilDisplay;
            UserHookData.MilImageDisp       = MilImageDisp;
            UserHookData.MilCompressedImage = MilCompressedImage;
            UserHookData.SaveSequenceToDisk = SAVE_SEQUENCE_TO_DISK;
            UserHookData.NbGrabbedFrames    = 0;
            UserHookData.NbArchivedFrames   = 0;

            // get a handle to the DigHookUserData object in the managed heap, we will use this
            // handle to get the object back in the callback function
            GCHandle UserHookDataHandle = GCHandle.Alloc(UserHookData);
            MIL_DIG_HOOK_FUNCTION_PTR UserHookFunctionDelegate = new MIL_DIG_HOOK_FUNCTION_PTR(ArchiveFunction);

            // Acquire the sequence. The processing hook function will
            // be called for each image grabbed to archive and display it.
            // If sequence is not saved to disk, stop after NbFrames.
            MIL.MdigProcess(MilDigitizer, MilGrabImages, NbFrames, SAVE_SEQUENCE_TO_DISK ? MIL.M_START : MIL.M_SEQUENCE, MIL.M_DEFAULT, UserHookFunctionDelegate, GCHandle.ToIntPtr(UserHookDataHandle));

            // Wait for a key press.
            Console.WriteLine("Press <Enter> to continue.");
            Console.WriteLine();
            Console.ReadKey(true);

            // Stop the sequence acquisition.
            MIL.MdigProcess(MilDigitizer, MilGrabImages, NbFrames, MIL.M_STOP, MIL.M_DEFAULT, UserHookFunctionDelegate, GCHandle.ToIntPtr(UserHookDataHandle));

            // Free the GCHandle when no longer used
            UserHookDataHandle.Free();

            // Read and print final statistics.
            MIL.MdigInquire(MilDigitizer, MIL.M_PROCESS_FRAME_COUNT, ref FrameCount);
            MIL.MdigInquire(MilDigitizer, MIL.M_PROCESS_FRAME_RATE, ref FrameRate);
            MIL.MdigInquire(MilDigitizer, MIL.M_PROCESS_FRAME_MISSED, ref FrameMissed);

            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("{0} frames archived ({1} missed), at {2:0.0} frames/sec ({3:0.0}ms/frame).", UserHookData.NbArchivedFrames, FrameMissed, FrameRate, 1000.0 / FrameRate);

            // Sequence file closing if required.
            if (SAVE_SEQUENCE_TO_DISK)
            {
                MIL.MbufExportSequence(SEQUENCE_FILE, MIL.M_DEFAULT, MIL.M_NULL, MIL.M_NULL, FrameRate, MIL.M_CLOSE);
            }

            // Playback the sequence until a key is pressed.
            if (UserHookData.NbArchivedFrames > 0)
            {
                do
                {
                    // If sequence must be loaded.
                    if (SAVE_SEQUENCE_TO_DISK)
                    {
                        // Inquire information about the sequence.
                        Console.WriteLine();
                        Console.WriteLine("Playing back sequence from the AVI file...");
                        Console.WriteLine();
                        Console.WriteLine("Press <Enter> to end.");
                        Console.WriteLine();
                        Console.WriteLine();
                        MIL.MbufDiskInquire(SEQUENCE_FILE, MIL.M_NUMBER_OF_IMAGES, ref FrameCount);
                        MIL.MbufDiskInquire(SEQUENCE_FILE, MIL.M_FRAME_RATE, ref FrameRate);
                        MIL.MbufDiskInquire(SEQUENCE_FILE, MIL.M_COMPRESSION_TYPE, ref CompressAttribute);

                        // Open the sequence file.
                        MIL.MbufImportSequence(SEQUENCE_FILE, MIL.M_DEFAULT, MIL.M_NULL, MIL.M_NULL, MIL.M_NULL, MIL.M_NULL, MIL.M_NULL, MIL.M_OPEN);
                    }

                    // Copy the images to the screen respecting the sequence frame rate.
                    TotalReplay      = 0.0;
                    NbFramesReplayed = 0;
                    for (n = 0; n < FrameCount; n++)
                    {
                        // Reset the time.
                        MIL.MappTimer(MIL.M_DEFAULT, MIL.M_TIMER_RESET, MIL.M_NULL);

                        // If image was saved to disk.
                        if (SAVE_SEQUENCE_TO_DISK)
                        {
                            // Load image directly to the display.
                            MIL.MbufImportSequence(SEQUENCE_FILE, MIL.M_DEFAULT, MIL.M_LOAD, MIL.M_NULL, ref MilImageDisp, n, 1, MIL.M_READ);
                            NbFramesReplayed++;
                            Console.Write("Frame #{0}             \r", NbFramesReplayed);
                        }
                        else
                        {
                            // Copy the grabbed image to the display.
                            MIL.MbufCopy(MilGrabImages[n], MilImageDisp);
                            NbFramesReplayed++;
                            Console.Write("Frame #{0}             \r", NbFramesReplayed);
                        }


                        // Check for a pressed key to exit.
                        if (Console.KeyAvailable && (n >= (NB_GRAB_IMAGE_MAX - 1)))
                        {
                            Console.ReadKey(true);
                            break;
                        }

                        // Wait to have a proper frame rate.
                        MIL.MappTimer(MIL.M_DEFAULT, MIL.M_TIMER_READ, ref TimeWait);
                        TotalReplay += TimeWait;
                        TimeWait     = (1 / FrameRate) - TimeWait;
                        MIL.MappTimer(MIL.M_DEFAULT, MIL.M_TIMER_WAIT, ref TimeWait);
                        TotalReplay += (TimeWait > 0) ? TimeWait : 0.0;
                    }

                    // Close the sequence file.
                    if (SAVE_SEQUENCE_TO_DISK)
                    {
                        MIL.MbufImportSequence(SEQUENCE_FILE, MIL.M_DEFAULT, MIL.M_NULL, MIL.M_NULL, MIL.M_NULL, MIL.M_NULL, MIL.M_NULL, MIL.M_CLOSE);
                    }

                    // Print statistics.
                    Console.WriteLine();
                    Console.WriteLine();
                    Console.WriteLine("{0} frames replayed, at a frame rate of {1:0.0} frames/sec ({2:0.0} ms/frame).", NbFramesReplayed, n / TotalReplay, 1000.0 * TotalReplay / n);
                    Console.WriteLine();
                    Console.WriteLine("Press <Enter> to end (or any other key to playback again).");
                    Console.WriteLine();
                }while (Console.ReadKey(true).Key != ConsoleKey.Enter);
            }

            // Free all allocated buffers.
            MIL.MbufFree(MilImageDisp);
            for (n = 0; n < NbFrames; n++)
            {
                MIL.MbufFree(MilGrabImages[n]);
            }

            if (MilCompressedImage != MIL.M_NULL)
            {
                MIL.MbufFree(MilCompressedImage);
            }

            // Free defaults.
            MIL.MappFreeDefault(MilApplication, MilSystem, MilDisplay, MilDigitizer, MIL.M_NULL);
        }