public int Init(int camIndex = 0) { try { //1.初始化默认的appID和sysID MIL.MappAllocDefault(MIL.M_DEFAULT, ref appID, ref sysID, MIL.M_NULL, MIL.M_NULL, MIL.M_NULL); //2.初始化digID,用于CameraLink控制相机 MIL_INT digNum = MIL.MsysInquire(sysID, MIL.M_DIGITIZER_NUM, MIL.M_NULL);//获取Cameralink数量 if (digNum < camIndex) { throw new Exception($"Camera {camIndex} not exits! Please check !"); } MIL.MdigAlloc(sysID, camIndex, dfc, MIL.M_DEFAULT, ref digID);//从DFC文件中加载相机配置,第三个参数就是DFC文件的路径 //3.相机配置保存在DFC文件中,现在可以从digID中获取到相机的配置 MIL.MdigInquire(digID, MIL.M_SIZE_X, ref width); //获取相机宽度 MIL.MdigInquire(digID, MIL.M_SIZE_Y, ref height); //获取相机高度 //MIL.MdigInquire(digID, MIL.M_MODEL_IMAGE_ATTRIBUTE, ref imgAttribute);//用于下一步分配相机帧buffer的参数 imgAttribute = MIL.M_GRAB | MIL.M_IMAGE | MIL.M_DISP | MIL.M_PROC; //4.分配buffer来存储相机帧数据 MIL.MbufAlloc2d(sysID, width, height, 8 + MIL.M_UNSIGNED, imgAttribute, ref imgID); //4.初始化时,开启控制串口 //comport.Open(); } catch (Exception e) { throw e; } return(0); }
static void SimulateGrabFromCamera(MIL_ID SourceImage, MIL_ID FocusImage, MIL_INT Iteration, MIL_ID AnnotationDisplay) { int NbSmoothNeeded = 0; // Number of smooths needed. MIL_INT BufType = 0; // Buffer type. MIL_INT BufSizeX = 0; // Buffer size X. MIL_INT BufSizeY = 0; // Buffer size Y. int Smooth = 0; // Smooth index. MIL_ID TempBuffer = MIL.M_NULL; // Temporary buffer. MIL_ID SourceOwnerSystem = MIL.M_NULL; // Owner system of the source buffer. // Compute number of smooths needed to simulate focus. NbSmoothNeeded = (int)Math.Abs(Iteration - FOCUS_BEST_POSITION); // Buffer inquires. BufType = MIL.MbufInquire(FocusImage, MIL.M_TYPE, MIL.M_NULL); BufSizeX = MIL.MbufInquire(FocusImage, MIL.M_SIZE_X, MIL.M_NULL); BufSizeY = MIL.MbufInquire(FocusImage, MIL.M_SIZE_Y, MIL.M_NULL); if (NbSmoothNeeded == 0) { // Directly copy image source to destination. MIL.MbufCopy(SourceImage, FocusImage); } else if (NbSmoothNeeded == 1) { // Directly convolve image from source to destination. MIL.MimConvolve(SourceImage, FocusImage, MIL.M_SMOOTH); } else { SourceOwnerSystem = (MIL_ID)MIL.MbufInquire(SourceImage, MIL.M_OWNER_SYSTEM, MIL.M_NULL); // Allocate temporary buffer. MIL.MbufAlloc2d(SourceOwnerSystem, BufSizeX, BufSizeY, BufType, MIL.M_IMAGE + MIL.M_PROC, ref TempBuffer); // Perform first smooth. MIL.MimConvolve(SourceImage, TempBuffer, MIL.M_SMOOTH); // Perform smooths. for (Smooth = 1; Smooth < NbSmoothNeeded - 1; Smooth++) { MIL.MimConvolve(TempBuffer, TempBuffer, MIL.M_SMOOTH); } // Perform last smooth. MIL.MimConvolve(TempBuffer, FocusImage, MIL.M_SMOOTH); // Free temporary buffer. MIL.MbufFree(TempBuffer); } // Draw position cursor. DrawCursor(AnnotationDisplay, Iteration); }
public int ReloadModel(int iCamNo, ref CVisionPatternData pSData) { if (pSData.m_bIsModel == false) { return(GenerateErrorCode(ERR_VISION_PATTERN_NONE)); } MIL_ID m_MilImage = MIL.M_NULL; // Image Load... string strLoadFileName = pSData.m_strFilePath + pSData.m_strFileName; MIL.MbufRestore(strLoadFileName, m_MilSystem, ref m_MilImage); //Draw할 Rec을 생성한다. Rectangle pRec = new Rectangle(pSData.m_rectModel.X - pSData.m_rectModel.Width / 2, pSData.m_rectModel.Y - pSData.m_rectModel.Height / 2, pSData.m_rectModel.Width, pSData.m_rectModel.Height); // Allocate a normalized grayscale model. MIL.MpatAllocModel(m_MilSystem, m_MilImage, pRec.X, pRec.Y, pRec.Width, pRec.Height, MIL.M_NORMALIZED, ref pSData.m_milModel); // Model Image Save (Image View Save용) MIL.MbufAlloc2d(m_MilSystem, pRec.Width, pRec.Height, MIL.M_UNSIGNED + 8, MIL.M_IMAGE + MIL.M_PROC + MIL.M_DISP, ref pSData.m_ModelImage); MIL.MbufCopyColor2d(m_MilImage, pSData.m_ModelImage, MIL.M_ALL_BANDS, pRec.X, pRec.Y, MIL.M_ALL_BANDS, 0, 0, pRec.Width, pRec.Height); if (pSData.m_milModel == MIL.M_NULL) { return(GenerateErrorCode(ERR_VISION_PATTERN_NONE)); } MIL.MpatAllocResult(m_MilSystem, MIL.M_DEFAULT, ref m_SearchResult); // Set the search accuracy to high. MIL.MpatSetAccuracy(pSData.m_milModel, MIL.M_HIGH); MIL.MpatSetAcceptance(pSData.m_milModel, pSData.m_dAcceptanceThreshold); // Acceptance Threshold Setting MIL.MpatSetCertainty(pSData.m_milModel, pSData.m_dAcceptanceThreshold); // Set Certainty Threshold MIL.MpatSetCenter(pSData.m_milModel, // Pattern Mark에서 Offset 설정함. (double)pSData.m_pointReference.X, (double)pSData.m_pointReference.Y); // Set the search model speed to high. MIL.MpatSetSpeed(pSData.m_milModel, MIL.M_HIGH); // Preprocess the model. MIL.MpatPreprocModel(m_MilImage, pSData.m_milModel, MIL.M_DEFAULT); return(SUCCESS); }
/// <summary> /// 현재 Grab하는 Image를 저장함. /// </summary> /// <param name="strPath"></param> /// <returns></returns> public bool SaveImage(string strPath) { MIL_ID pSaveImage = MIL.M_NULL; MIL.MbufAlloc2d(m_pMilSystemID, m_recImage.Width, m_recImage.Height, MIL.M_UNSIGNED + 8, MIL.M_IMAGE + MIL.M_PROC + MIL.M_DISP, ref pSaveImage); MIL.MbufCopy(m_MilImage, pSaveImage); MIL.MbufExport(strPath, MIL.M_BMP, pSaveImage); MIL.MbufFree(pSaveImage); return(true); }
/// <summary> /// 현재 Grab하는 Image를 저장함. /// </summary> /// <param name="strPath"></param> /// <returns></returns> public bool SaveImage(MIL_ID pImage, string strPath) { MIL_ID pSaveImage = MIL.M_NULL; // Inquire overlay size. MIL_INT iWidth = MIL.MbufInquire(pImage, MIL.M_SIZE_X, MIL.M_NULL); MIL_INT iHeight = MIL.MbufInquire(pImage, MIL.M_SIZE_Y, MIL.M_NULL); MIL.MbufAlloc2d(m_pMilSystemID, iWidth, iHeight, MIL.M_UNSIGNED + 8, MIL.M_IMAGE + MIL.M_PROC + MIL.M_DISP, ref pSaveImage); MIL.MbufCopy(pImage, pSaveImage); MIL.MbufExport(strPath, MIL.M_BMP, pSaveImage); return(true); }
/// <summary> /// SelectCamera: 카메라의 영상의 크기로 Byte array 크기를 할당하고, /// Mil 변수에 영상을 할당한다. /// </summary> /// <param name="pCamera"></param> /// <returns></returns> public int SelectCamera(MVisionCamera pCamera) { if (pCamera == null) { return(GenerateErrorCode(ERR_VISION_CAMERA_NON_USEFUL)); } Size CameraPixelSize; // View의 Camera 주소에 객체를 대입한다. m_pCamera = pCamera; // Camera Pixel Size 대입 CameraPixelSize = m_pCamera.GetCameraPixelSize(); m_CameraWidth = CameraPixelSize.Width; m_CameraHeight = CameraPixelSize.Height; if (m_CameraWidth == 0 || m_CameraHeight == 0) { return(GenerateErrorCode(ERR_VISION_CAMERA_IMAGE_SIZE_FAIL)); } // image byte 변수 m_ImgBits = new Byte[m_CameraWidth * m_CameraHeight]; // set source image size Rect size m_recImage.X = 0; m_recImage.Y = 0; m_recImage.Width = m_CameraWidth; m_recImage.Height = m_CameraHeight; // MIL Buffer 초기화 if (m_MilImage != MIL.M_NULL) { MIL.MbufFree(m_MilImage); } MIL.MbufAlloc2d(m_pMilSystemID, m_recImage.Width, m_recImage.Height, MIL.M_UNSIGNED + 8, MIL.M_IMAGE + MIL.M_PROC + MIL.M_DISP, ref m_MilImage); MIL.MbufClear(m_MilImage, 0); return(SUCCESS); }
//**************************************************************************** // Main. //**************************************************************************** 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 MilDisplayImage = MIL.M_NULL; // Display image identifier. MIL_ID MilModelImage = MIL.M_NULL; // Model image identifier. // Allocate defaults. MIL.MappAllocDefault(MIL.M_DEFAULT, ref MilApplication, ref MilSystem, ref MilDisplay, ref MilDigitizer, ref MilDisplayImage); // Allocate a model image buffer. MIL.MbufAlloc2d(MilSystem, MIL.MbufInquire(MilDisplayImage, MIL.M_SIZE_X, MIL.M_NULL), MIL.MbufInquire(MilDisplayImage, MIL.M_SIZE_Y, MIL.M_NULL), 8, MIL.M_IMAGE + MIL.M_PROC, ref MilModelImage); Console.Write("\nMODEL TRACKING:\n"); Console.Write("---------------\n\n"); // Get the model image. GetModelImage(MilSystem, MilDisplay, MilDigitizer, MilDisplayImage, MilModelImage); if (RUN_PAT_TRACKING_EXAMPLE == MIL.M_YES) { // Finds the model using pattern matching. MpatTrackingExample(MilSystem, MilDisplay, MilDigitizer, MilDisplayImage, MilModelImage); } if (RUN_MOD_TRACKING_EXAMPLE == MIL.M_YES) { // Finds the model using geometric model finder. MmodTrackingExample(MilSystem, MilDisplay, MilDigitizer, MilDisplayImage, MilModelImage); } // Free allocated buffers. MIL.MbufFree(MilModelImage); // Free defaults. MIL.MappFreeDefault(MilApplication, MilSystem, MilDisplay, MilDigitizer, MilDisplayImage); }
// Main function: // -------------- static void Main(string[] args) { MIL_ID MilApplication = MIL.M_NULL; // Application identifier. MIL_ID MilRemoteApplication = MIL.M_NULL; // Remote Application identifier if running on a remote computer MIL_ID MilSystem = MIL.M_NULL; // System identifier. MIL_ID MilDisplay = MIL.M_NULL; // Display identifier. MIL_ID MilImage = MIL.M_NULL; // Image buffer identifiers. MIL_ID MilOrgImage = MIL.M_NULL; THREAD_PARAM TParTopLeft = new THREAD_PARAM(); // Parameters passed to top left thread. THREAD_PARAM TParBotLeft = new THREAD_PARAM(); // Parameters passed to bottom left thread. THREAD_PARAM TParTopRight = new THREAD_PARAM(); // Parameters passed to top right thread. THREAD_PARAM TParBotRight = new THREAD_PARAM(); // Parameters passed to bottom right thread. double Time = 0.0; // Timer variables. double FramesPerSecond = 0.0; MIL_INT LicenseModules = 0; // List of available MIL modules. // Allocate defaults. MIL.MappAllocDefault(MIL.M_DEFAULT, ref MilApplication, ref MilSystem, ref MilDisplay, MIL.M_NULL, MIL.M_NULL); // Allocate and display the main image buffer. MIL.MbufAlloc2d(MilSystem, IMAGE_WIDTH * 2, IMAGE_HEIGHT * 2, 8 + MIL.M_UNSIGNED, MIL.M_IMAGE + MIL.M_PROC + MIL.M_DISP, ref MilImage); MIL.MbufClear(MilImage, 0); MIL.MdispSelect(MilDisplay, MilImage); // Allocate an image buffer to keep the original. MIL.MbufAlloc2d(MilSystem, IMAGE_WIDTH, IMAGE_HEIGHT, 8 + MIL.M_UNSIGNED, MIL.M_IMAGE + MIL.M_PROC, ref MilOrgImage); // Allocate a destination child buffer for each thread. MIL.MbufChild2d(MilImage, 0, 0, IMAGE_WIDTH, IMAGE_HEIGHT, ref TParTopLeft.SrcImage); MIL.MbufChild2d(MilImage, 0, IMAGE_HEIGHT, IMAGE_WIDTH, IMAGE_HEIGHT, ref TParBotLeft.DstImage); MIL.MbufChild2d(MilImage, IMAGE_WIDTH, 0, IMAGE_WIDTH, IMAGE_HEIGHT, ref TParTopRight.SrcImage); MIL.MbufChild2d(MilImage, IMAGE_WIDTH, IMAGE_HEIGHT, IMAGE_WIDTH, IMAGE_HEIGHT, ref TParBotRight.DstImage); // Allocate synchronization events. MIL.MthrAlloc(MilSystem, MIL.M_EVENT, MIL.M_DEFAULT, MIL.M_NULL, MIL.M_NULL, ref TParTopLeft.DoneEvent); MIL.MthrAlloc(MilSystem, MIL.M_EVENT, MIL.M_DEFAULT, MIL.M_NULL, MIL.M_NULL, ref TParBotLeft.DoneEvent); MIL.MthrAlloc(MilSystem, MIL.M_EVENT, MIL.M_DEFAULT, MIL.M_NULL, MIL.M_NULL, ref TParTopRight.DoneEvent); MIL.MthrAlloc(MilSystem, MIL.M_EVENT, MIL.M_DEFAULT, MIL.M_NULL, MIL.M_NULL, ref TParBotRight.DoneEvent); // Inquire MIL licenses. MIL.MsysInquire(MilSystem, MIL.M_OWNER_APPLICATION, ref MilRemoteApplication); MIL.MappInquire(MilRemoteApplication, MIL.M_LICENSE_MODULES, ref LicenseModules); // Initialize remaining thread parameters. TParTopLeft.System = MilSystem; TParTopLeft.OrgImage = MilOrgImage; TParTopLeft.DstImage = TParTopLeft.SrcImage; TParTopLeft.ReadyEvent = TParBotLeft.DoneEvent; TParTopLeft.NumberOfIteration = 0; TParTopLeft.Radius = 0; TParTopLeft.Exit = 0; TParTopLeft.LicenseModules = LicenseModules; TParTopLeft.SlaveThreadParam = TParBotLeft; TParBotLeft.System = MilSystem; TParBotLeft.OrgImage = 0; TParBotLeft.SrcImage = TParTopLeft.DstImage; TParBotLeft.ReadyEvent = TParTopLeft.DoneEvent; TParBotLeft.NumberOfIteration = 0; TParBotLeft.Radius = 0; TParBotLeft.Exit = 0; TParBotLeft.LicenseModules = LicenseModules; TParBotLeft.SlaveThreadParam = null; TParTopRight.System = MilSystem; TParTopRight.OrgImage = MilOrgImage; TParTopRight.DstImage = TParTopRight.SrcImage; TParTopRight.ReadyEvent = TParBotRight.DoneEvent; TParTopRight.NumberOfIteration = 0; TParTopRight.Radius = 0; TParTopRight.Exit = 0; TParTopRight.LicenseModules = LicenseModules; TParTopRight.SlaveThreadParam = TParBotRight; TParBotRight.System = MilSystem; TParBotRight.OrgImage = 0; TParBotRight.SrcImage = TParTopRight.DstImage; TParBotRight.ReadyEvent = TParTopRight.DoneEvent; TParBotRight.NumberOfIteration = 0; TParBotRight.Radius = 0; TParBotRight.Exit = 0; TParBotRight.LicenseModules = LicenseModules; TParBotRight.SlaveThreadParam = null; // Initialize the original image to process. MIL.MbufLoad(IMAGE_FILE, MilOrgImage); // Start the 4 threads. MIL_THREAD_FUNCTION_PTR TopThreadDelegate = new MIL_THREAD_FUNCTION_PTR(TopThread); MIL_THREAD_FUNCTION_PTR BotLeftThreadDelegate = new MIL_THREAD_FUNCTION_PTR(BotLeftThread); MIL_THREAD_FUNCTION_PTR BotRightThreadDelegate = new MIL_THREAD_FUNCTION_PTR(BotRightThread); GCHandle TParTopLeftHandle = GCHandle.Alloc(TParTopLeft); GCHandle TParBotLeftHandle = GCHandle.Alloc(TParBotLeft); GCHandle TParTopRightHandle = GCHandle.Alloc(TParTopRight); GCHandle TParBotRightHandle = GCHandle.Alloc(TParBotRight); MIL.MthrAlloc(MilSystem, MIL.M_THREAD, MIL.M_DEFAULT, TopThreadDelegate, GCHandle.ToIntPtr(TParTopLeftHandle), ref TParTopLeft.Id); MIL.MthrAlloc(MilSystem, MIL.M_THREAD, MIL.M_DEFAULT, BotLeftThreadDelegate, GCHandle.ToIntPtr(TParBotLeftHandle), ref TParBotLeft.Id); MIL.MthrAlloc(MilSystem, MIL.M_THREAD, MIL.M_DEFAULT, TopThreadDelegate, GCHandle.ToIntPtr(TParTopRightHandle), ref TParTopRight.Id); MIL.MthrAlloc(MilSystem, MIL.M_THREAD, MIL.M_DEFAULT, BotRightThreadDelegate, GCHandle.ToIntPtr(TParBotRightHandle), ref TParBotRight.Id); // Start the timer. MIL.MappTimer(MIL.M_DEFAULT, MIL.M_TIMER_RESET + MIL.M_SYNCHRONOUS, MIL.M_NULL); // Set events to start operation of top left and top right threads. MIL.MthrControl(TParTopLeft.ReadyEvent, MIL.M_EVENT_SET, MIL.M_SIGNALED); MIL.MthrControl(TParTopRight.ReadyEvent, MIL.M_EVENT_SET, MIL.M_SIGNALED); // Report that the threads are started and wait for a key press to stop them. Console.Write("\nMULTI-THREADING:\n"); Console.Write("----------------\n\n"); Console.Write("4 threads running...\n"); Console.Write("Press <Enter> to stop.\n\n"); Console.ReadKey(); // Signal the threads to exit. TParTopLeft.Exit = 1; TParTopRight.Exit = 1; // Wait for all threads to terminate. MIL.MthrWait(TParTopLeft.Id, MIL.M_THREAD_END_WAIT); MIL.MthrWait(TParBotLeft.Id, MIL.M_THREAD_END_WAIT); MIL.MthrWait(TParTopRight.Id, MIL.M_THREAD_END_WAIT); MIL.MthrWait(TParBotRight.Id, MIL.M_THREAD_END_WAIT); // Stop the timer and calculate the number of frames per second processed. MIL.MappTimer(MIL.M_DEFAULT, MIL.M_TIMER_READ + MIL.M_SYNCHRONOUS, ref Time); FramesPerSecond = (TParTopLeft.NumberOfIteration + TParBotLeft.NumberOfIteration + TParTopRight.NumberOfIteration + TParBotRight.NumberOfIteration) / Time; // Print statistics. Console.Write("Top left iterations done: {0,4}.\n", TParTopLeft.NumberOfIteration); Console.Write("Bottom left iterations done: {0,4}.\n", TParBotLeft.NumberOfIteration); Console.Write("Top right iterations done: {0,4}.\n", TParTopRight.NumberOfIteration); Console.Write("Bottom right iterations done: {0,4}.\n\n", TParBotRight.NumberOfIteration); Console.Write("Processing speed for the 4 threads: {0:0.0} Images/Sec.\n\n", FramesPerSecond); Console.Write("Press <Enter> to end.\n\n"); Console.ReadKey(); // Free threads. MIL.MthrFree(TParTopLeft.Id); MIL.MthrFree(TParBotLeft.Id); MIL.MthrFree(TParTopRight.Id); MIL.MthrFree(TParBotRight.Id); // Free events. MIL.MthrFree(TParTopLeft.DoneEvent); MIL.MthrFree(TParBotLeft.DoneEvent); MIL.MthrFree(TParTopRight.DoneEvent); MIL.MthrFree(TParBotRight.DoneEvent); // Free buffers. MIL.MbufFree(TParTopLeft.SrcImage); MIL.MbufFree(TParTopRight.SrcImage); MIL.MbufFree(TParBotLeft.DstImage); MIL.MbufFree(TParBotRight.DstImage); MIL.MbufFree(MilOrgImage); MIL.MbufFree(MilImage); // Free the GCHandles TParTopLeftHandle.Free(); TParBotLeftHandle.Free(); TParTopRightHandle.Free(); TParBotRightHandle.Free(); // Free defaults. MIL.MappFreeDefault(MilApplication, MilSystem, MilDisplay, MIL.M_NULL, MIL.M_NULL); }
// Main to test the custom 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_INT ReturnValue = 0; // Return value of the function. // Allocate default application, system, display and image. MIL.MappAllocDefault(MIL.M_DEFAULT, ref MilApplication, ref MilSystem, ref MilDisplay, MIL.M_NULL, MIL.M_NULL); // Load source image into a Host memory image buffer. MIL.MbufAlloc2d(MilSystem, MIL.MbufDiskInquire(IMAGE_FILE, MIL.M_SIZE_X), MIL.MbufDiskInquire(IMAGE_FILE, MIL.M_SIZE_Y), 8 + MIL.M_UNSIGNED, MIL.M_IMAGE + MIL.M_DISP + MIL.M_HOST_MEMORY, ref MilImage); MIL.MbufLoad(IMAGE_FILE, MilImage); // Display the image. MIL.MdispSelect(MilDisplay, MilImage); // Pause. Console.WriteLine(); Console.WriteLine("MIL FUNCTION DEVELOPER'S TOOLKIT:"); Console.WriteLine("----------------------------------"); Console.WriteLine(); Console.WriteLine("This example creates a custom MIL function that processes"); Console.WriteLine("an image using its data pointer directly."); Console.WriteLine(); Console.WriteLine("Target image was loaded."); Console.WriteLine("Press a key to continue."); Console.WriteLine(); Console.ReadKey(); // Run the custom function only if the target system's memory is local and accessible. if (MIL.MsysInquire(MilSystem, MIL.M_LOCATION, MIL.M_NULL) == MIL.M_LOCAL) { // Process the image directly with the custom MIL function. ReturnValue = AddConstant(MilImage, MilImage, 0x40); // Print a conclusion message. if (ReturnValue == MIL.M_NULL) { Console.WriteLine("The white level of the image was augmented."); } else { Console.WriteLine("An error was returned by the Slave function."); } } else { // Print that the example don't run remotely. Console.WriteLine("This example doesn't run with Distributed MIL."); } // Wait for a key to terminate. Console.WriteLine("Press a key to terminate."); Console.WriteLine(); Console.ReadKey(); // Free all allocations. MIL.MbufFree(MilImage); MIL.MappFreeDefault(MilApplication, MilSystem, MilDisplay, MIL.M_NULL, MIL.M_NULL); }
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); }
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); }
private static void InteractivityExample(MIL_ID MilSystem, MIL_ID MilDisplay) { MIL_ID MilImage = MIL.M_NULL; // Image buffer identifier. MIL_ID MilGraphicsList = MIL.M_NULL; // Graphics list identifier. MIL_ID MilGraphicsContext = MIL.M_NULL; // Graphics context identifier. MIL_ID MilBinImage = MIL.M_NULL; // Binary image buffer identifier. MIL_ID MilBlobFeatureList = MIL.M_NULL; // Feature list identifier. MIL_ID MilBlobResult = MIL.M_NULL; // Blob result buffer identifier. MIL_INT SizeX = 0; // Size X of the source buffer. MIL_INT SizeY = 0; // Size Y of the source buffer. MIL_INT RegionLabel = 0; // Label value of the region. STestParameters DataStructure = new STestParameters(); // Hook function data structure. // Restore the source image. MIL.MbufRestore(IMAGE_FILE, MilSystem, ref MilImage); // Display the buffer. MIL.MdispSelect(MilDisplay, MilImage); // Allocate a graphics list to hold the subpixel annotations. MIL.MgraAllocList(MilSystem, MIL.M_DEFAULT, ref MilGraphicsList); // Associate the graphics list to the display for annotations. MIL.MdispControl(MilDisplay, MIL.M_ASSOCIATED_GRAPHIC_LIST_ID, MilGraphicsList); // Allocate a graphics context for the draw operations. MIL.MgraAlloc(MilSystem, ref MilGraphicsContext); // Enable the interactive mode. MIL.MdispControl(MilDisplay, MIL.M_GRAPHIC_LIST_INTERACTIVE, MIL.M_ENABLE); // Add a selectable rectangular region. MIL.MgraRectAngle(MilGraphicsContext, MilGraphicsList, RECTANGLE_POSITION_X, RECTANGLE_POSITION_Y, RECTANGLE_WIDTH, RECTANGLE_HEIGHT, RECTANGLE_ANGLE, MIL.M_CENTER_AND_DIMENSION); // Retrieve the label of the rectangle graphic. MIL.MgraInquireList(MilGraphicsList, MIL.M_LIST, MIL.M_DEFAULT, MIL.M_LAST_LABEL, ref RegionLabel); // Disable the selectable mode for the next annotations to the graphics list. MIL.MgraControl(MilGraphicsContext, MIL.M_SELECTABLE, MIL.M_DISABLE); // Allocate a binary image buffer for fast processing. MIL.MbufInquire(MilImage, MIL.M_SIZE_X, ref SizeX); MIL.MbufInquire(MilImage, MIL.M_SIZE_Y, ref SizeY); MIL.MbufAlloc2d(MilSystem, SizeX, SizeY, 1 + MIL.M_UNSIGNED, MIL.M_IMAGE + MIL.M_PROC, ref MilBinImage); // Binarize the source image. MIL.MimBinarize(MilImage, MilBinImage, MIL.M_FIXED + MIL.M_LESS, IMAGE_THRESHOLD_VALUE, MIL.M_NULL); // Allocate a blob feature list and a blob result. MIL.MblobAllocFeatureList(MilSystem, ref MilBlobFeatureList); MIL.MblobAllocResult(MilSystem, ref MilBlobResult); // Select the blob features to calculate (Center Of Gravity and Box). MIL.MblobSelectFeature(MilBlobFeatureList, MIL.M_CENTER_OF_GRAVITY); MIL.MblobSelectFeature(MilBlobFeatureList, MIL.M_BOX); // Programmatically initialize the selected state of the rectangle region. MIL.MgraControlList(MilGraphicsList, MIL.M_GRAPHIC_LABEL(RegionLabel), MIL.M_DEFAULT, MIL.M_GRAPHIC_SELECTED, MIL.M_TRUE); // Perform and display a first count of the number of objects // within the initial region. CountObjects(MilDisplay, MilGraphicsList, MilGraphicsContext, MilBinImage, MilBlobFeatureList, MilBlobResult); // Initialize the hook data structure, then associate the hook function to // the "MIL.M_GRAPHIC_MODIFIED" event. The hook function will be called // with any region interaction by the user. DataStructure.MilDisplay = MilDisplay; DataStructure.MilGraphicsList = MilGraphicsList; DataStructure.MilGraphicsContext = MilGraphicsContext; DataStructure.MilBinImage = MilBinImage; DataStructure.RegionLabel = RegionLabel; DataStructure.MilBlobFeatureList = MilBlobFeatureList; DataStructure.MilBlobResult = MilBlobResult; GCHandle DataStructureHandle = GCHandle.Alloc(DataStructure); MIL_GRA_HOOK_FUNCTION_PTR HookHandlerDelegate = new MIL_GRA_HOOK_FUNCTION_PTR(HookHandler); MIL.MgraHookFunction(MilGraphicsList, MIL.M_GRAPHIC_MODIFIED, HookHandlerDelegate, GCHandle.ToIntPtr(DataStructureHandle)); if (MIL.MdispInquire(MilDisplay, MIL.M_DISPLAY_TYPE, MIL.M_NULL) != MIL.M_AUXILIARY) { Console.WriteLine("You can try using your mouse to interactively modify the"); Console.WriteLine("displayed region, such as moving, resizing, or rotating the"); Console.WriteLine("region. If you do so, the results and annotations will be"); Console.WriteLine("immediately updated\n"); Console.WriteLine(); } else { Console.WriteLine("***NOTE: This example does not implement the interactivity"); Console.WriteLine(" with an auxiliary display."); Console.WriteLine(); } Console.WriteLine("Press <Enter> to exit."); Console.ReadKey(); MIL.MgraHookFunction(MilGraphicsList, MIL.M_GRAPHIC_MODIFIED + MIL.M_UNHOOK, HookHandlerDelegate, GCHandle.ToIntPtr(DataStructureHandle)); DataStructureHandle.Free(); // Free all allocations. MIL.MblobFree(MilBlobResult); MIL.MblobFree(MilBlobFeatureList); MIL.MbufFree(MilBinImage); MIL.MgraFree(MilGraphicsContext); MIL.MgraFree(MilGraphicsList); MIL.MbufFree(MilImage); }
private static void FixturedMeasurementExample(MIL_ID MilSystem, MIL_ID MilDisplay) { MIL_ID MilSourceImage = MIL.M_NULL; // Source image buffer identifier. MIL_ID MilImage = MIL.M_NULL; // Image buffer identifier. MIL_ID MilModContext = MIL.M_NULL; // Model finder context identifier. MIL_ID MilModResult = MIL.M_NULL; // Model finder result identifier. MIL_ID MilFixturingOffset = MIL.M_NULL; // Fixturing object identifier. MIL_ID StripeMarker = MIL.M_NULL; // Stripe marker identifier. MIL_ID MilGraphicList = MIL.M_NULL; // Graphic list identifier. double StripeWidth = 0.0; // Stripe width. double PositionX = 0.0; // Occurrence position X. double PositionY = 0.0; // Occurrence position Y. MIL_INT SizeX = 0; // Source image size X. MIL_INT SizeY = 0; // Source image size Y. MIL_INT NbOccurrences = 0; // Number of found occurrences. MIL_INT NbStripes = 0; // Number of found stripes. MIL_INT Index = 0; // Occurrence index. // Restore the source image. MIL.MbufRestore(FIXTURED_MEAS_IMAGE_FILE, MilSystem, ref MilSourceImage); MIL.MbufInquire(MilSourceImage, MIL.M_SIZE_X, ref SizeX); MIL.MbufInquire(MilSourceImage, MIL.M_SIZE_Y, ref SizeY); // Allocate, then compute the source image luminance. MIL.MbufAlloc2d(MilSystem, SizeX, SizeY, 8 + MIL.M_UNSIGNED, MIL.M_IMAGE + MIL.M_PROC + MIL.M_DISP, ref MilImage); MIL.MimConvert(MilSourceImage, MilImage, MIL.M_RGB_TO_L); // Allocate a graphic list to hold the subpixel annotations to draw. MIL.MgraAllocList(MilSystem, MIL.M_DEFAULT, ref MilGraphicList); // Select the image to the display. MIL.MdispSelect(MilDisplay, MilImage); // Associate the graphic list to the display. MIL.MdispControl(MilDisplay, MIL.M_ASSOCIATED_GRAPHIC_LIST_ID, MilGraphicList); // Allocate a stripe marker. MIL.MmeasAllocMarker(MilSystem, MIL.M_STRIPE, MIL.M_DEFAULT, ref StripeMarker); // Set inputs units to world in order to fixture the region. MIL.MmeasSetMarker(StripeMarker, MIL.M_SEARCH_REGION_INPUT_UNITS, MIL.M_WORLD, MIL.M_NULL); // Calibrate the destination image to receive the world units annotations. MIL.McalUniform(MilImage, 0.0, 0.0, 1.0, 1.0, 0.0, MIL.M_DEFAULT); // Specify the stripe characteristics. MIL.MmeasSetMarker(StripeMarker, MIL.M_BOX_ORIGIN, FIXTURED_MEAS_BOX_OFFSET_X, FIXTURED_MEAS_BOX_OFFSET_Y); MIL.MmeasSetMarker(StripeMarker, MIL.M_POLARITY, FIXTURED_STRIPE_POLARITY_LEFT, FIXTURED_STRIPE_POLARITY_RIGHT); MIL.MmeasSetMarker(StripeMarker, MIL.M_SEARCH_REGION_CLIPPING, MIL.M_ENABLE, MIL.M_NULL); // Specify the search region size and position. MIL.MmeasSetMarker(StripeMarker, MIL.M_BOX_SIZE, FIXTURED_MEAS_BOX_WIDTH, FIXTURED_MEAS_BOX_HEIGHT); // Draw the contour of the measurement region. MIL.MgraColor(MIL.M_DEFAULT, MIL.M_COLOR_BLUE); MIL.MgraControl(MIL.M_DEFAULT, MIL.M_INPUT_UNITS, MIL.M_WORLD); MIL.MmeasDraw(MIL.M_DEFAULT, StripeMarker, MilGraphicList, MIL.M_DRAW_SEARCH_REGION, MIL.M_DEFAULT, MIL.M_MARKER); MIL.MgraControl(MIL.M_DEFAULT, MIL.M_INPUT_UNITS, MIL.M_PIXEL); Console.Write("A measurement stripe marker (in blue) is defined.\n"); // Define model to further fixture the measurement marker. MIL.MmodAlloc(MilSystem, MIL.M_GEOMETRIC, MIL.M_DEFAULT, ref MilModContext); MIL.MmodAllocResult(MilSystem, MIL.M_DEFAULT, ref MilModResult); MIL.MmodDefine(MilModContext, MIL.M_IMAGE, MilImage, FIXTURED_MODEL_OFFSET_X, FIXTURED_MODEL_OFFSET_Y, FIXTURED_MODEL_SIZE_X, FIXTURED_MODEL_SIZE_Y); MIL.MmodControl(MilModContext, MIL.M_DEFAULT, MIL.M_NUMBER, MIL.M_ALL); MIL.MmodControl(MilModContext, MIL.M_CONTEXT, MIL.M_SPEED, MIL.M_VERY_HIGH); // Preprocess the model. MIL.MmodPreprocess(MilModContext, MIL.M_DEFAULT); // Display the model. MIL.MgraColor(MIL.M_DEFAULT, MIL.M_COLOR_GREEN); MIL.MmodDraw(MIL.M_DEFAULT, MilModContext, MilGraphicList, MIL.M_DRAW_BOX + MIL.M_DRAW_POSITION, MIL.M_DEFAULT, MIL.M_ORIGINAL); Console.Write("A Model Finder model (in green) is defined to\n"); Console.Write("further fixture the measurement operation.\n\n"); Console.Write("The stripe marker determines the gap between\n"); Console.Write("the fuse connectors. Model Finder tracks the\n"); Console.Write("fuses while the attached fixturing automatically\n"); Console.Write("relocates the marker relative to the found fuses.\n"); Console.Write("Press <Enter> to continue.\n\n"); Console.ReadKey(); // Allocate a fixture object. MIL.McalAlloc(MilSystem, MIL.M_FIXTURING_OFFSET, MIL.M_DEFAULT, ref MilFixturingOffset); // Learn the relative offset of the model. MIL.McalFixture(MIL.M_NULL, MilFixturingOffset, MIL.M_LEARN_OFFSET, MIL.M_MODEL_MOD, MilModContext, 0, MIL.M_DEFAULT, MIL.M_DEFAULT, MIL.M_DEFAULT); // Find the location of the fixtures using Model Finder. MIL.MmodFind(MilModContext, MilImage, MilModResult); // Display and retrieve the number of occurrences found. MIL.MgraClear(MIL.M_DEFAULT, MilGraphicList); MIL.MmodDraw(MIL.M_DEFAULT, MilModResult, MilGraphicList, MIL.M_DRAW_POSITION + MIL.M_DRAW_BOX, MIL.M_DEFAULT, MIL.M_DEFAULT); MIL.MmodGetResult(MilModResult, MIL.M_DEFAULT, MIL.M_NUMBER + MIL.M_TYPE_MIL_INT, ref NbOccurrences); Console.Write("Locating the parts: {0} occurrences are found.\n", NbOccurrences); Console.Write("Press <Enter> to continue.\n\n"); Console.ReadKey(); Console.Write("The measurement tool is moved relative to each piece.\n"); Console.Write("A graphic list is used to display the results with\n"); Console.Write("subpixel annotations.\n\n"); // Clear the annotations. MIL.MgraClear(MIL.M_DEFAULT, MilGraphicList); for (Index = 0; Index < NbOccurrences; Index++) { // Display the found model occurrence position. MIL.MgraColor(MIL.M_DEFAULT, MIL.M_COLOR_GREEN); MIL.MmodDraw(MIL.M_DEFAULT, MilModResult, MilGraphicList, MIL.M_DRAW_POSITION, Index, MIL.M_DEFAULT); MIL.MmodGetResult(MilModResult, Index, MIL.M_POSITION_X + MIL.M_TYPE_MIL_DOUBLE, ref PositionX); MIL.MmodGetResult(MilModResult, Index, MIL.M_POSITION_Y + MIL.M_TYPE_MIL_DOUBLE, ref PositionY); MIL.MgraText(MIL.M_DEFAULT, MilGraphicList, PositionX - 20, PositionY, Index.ToString()); // Apply a fixture offset to the implicit 1:1 calibration of the target image. MIL.McalFixture(MilImage, MilFixturingOffset, MIL.M_MOVE_RELATIVE, MIL.M_RESULT_MOD, MilModResult, Index, MIL.M_DEFAULT, MIL.M_DEFAULT, MIL.M_DEFAULT); // Find the stripe and measure its width and angle. MIL.MmeasFindMarker(MIL.M_DEFAULT, MilImage, StripeMarker, MIL.M_POSITION + MIL.M_STRIPE_WIDTH); // Get the number of found results. MIL.MmeasGetResult(StripeMarker, MIL.M_NUMBER + MIL.M_TYPE_MIL_INT, ref NbStripes, MIL.M_NULL); if (NbStripes == 1) { // Get the stripe width. MIL.MmeasGetResult(StripeMarker, MIL.M_STRIPE_WIDTH, ref StripeWidth, MIL.M_NULL); // Draw the contour of the found measurement region. MIL.MgraColor(MIL.M_DEFAULT, MIL.M_COLOR_BLUE); MIL.MmeasDraw(MIL.M_DEFAULT, StripeMarker, MilGraphicList, MIL.M_DRAW_SEARCH_REGION, MIL.M_DEFAULT, MIL.M_RESULT); // Draw a cross on the center, left edge and right edge of the found stripe. MIL.MgraColor(MIL.M_DEFAULT, MIL.M_COLOR_RED); MIL.MmeasDraw(MIL.M_DEFAULT, StripeMarker, MilGraphicList, MIL.M_DRAW_WIDTH, MIL.M_DEFAULT, MIL.M_RESULT); // Print the result. Console.Write("The gap (in red) of occurrence {0} is {1:#.##} pixels wide.\n", Index, StripeWidth); } else { Console.Write("The gap of occurrence {0} could not be measured.\n", Index); } } Console.Write("Press <Enter> to end.\n"); Console.ReadKey(); // Free all allocations. MIL.MgraFree(MilGraphicList); MIL.MmeasFree(StripeMarker); MIL.MmodFree(MilModContext); MIL.MmodFree(MilModResult); MIL.McalFree(MilFixturingOffset); MIL.MbufFree(MilImage); MIL.MbufFree(MilSourceImage); }
const double MIN_HEIGHT_THRESHOLD = -1.0; // in mm static void CalibratedCameraExample(MIL_ID MilSystem, MIL_ID MilDisplay) { MIL_ID MilOverlayImage = MIL.M_NULL; // Overlay image buffer identifier. MIL_ID MilImage = MIL.M_NULL; // Image buffer identifier (for processing). MIL_ID MilCalibration = MIL.M_NULL; // Calibration context. MIL_ID DepthMapId = MIL.M_NULL; // Image buffer identifier (for results). MIL_ID LaserId = MIL.M_NULL; // 3dmap laser profiling context identifier. MIL_ID ScanId = MIL.M_NULL; // 3dmap result buffer identifier. MIL_INT CalibrationStatus = 0; // Used to ensure if McalGrid() worked. MIL_INT SizeX = 0; // Width of grabbed images. MIL_INT SizeY = 0; // Height of grabbed images. MIL_INT NumberOfImages = 0; // Number of frames for scanned objects. MIL_INT n = 0; // Counter. double FrameRate = 0.0; // Number of grabbed frames per second (in AVI). double StartTime = 0.0; // Time at the beginning of each iteration. double EndTime = 0.0; // Time after processing for each iteration. double WaitTime = 0.0; // Time to wait for next frame. double Volume = 0.0; // Volume of scanned object. Console.WriteLine(); Console.WriteLine("3D PROFILING AND VOLUME ANALYSIS:"); Console.WriteLine("---------------------------------"); Console.WriteLine(); Console.WriteLine("This program generates fully corrected 3d data of a scanned"); Console.WriteLine("cookie and computes its volume.The laser profiling system uses"); Console.WriteLine("a 3d-calibrated camera."); Console.WriteLine(); // Load grid image for camera calibration. MIL.MbufRestore(GRID_FILENAME, MilSystem, ref MilImage); // Select display. MIL.MdispSelect(MilDisplay, MilImage); Console.WriteLine("Calibrating the camera..."); Console.WriteLine(); MIL.MbufInquire(MilImage, MIL.M_SIZE_X, ref SizeX); MIL.MbufInquire(MilImage, MIL.M_SIZE_Y, ref SizeY); // Allocate calibration context in 3D mode. MIL.McalAlloc(MilSystem, MIL.M_TSAI_BASED, MIL.M_DEFAULT, ref MilCalibration); // Calibrate the camera. MIL.McalGrid(MilCalibration, MilImage, 0.0, 0.0, 0.0, GRID_NB_ROWS, GRID_NB_COLS, GRID_ROW_SPACING, GRID_COL_SPACING, MIL.M_DEFAULT, MIL.M_CHESSBOARD_GRID); MIL.McalInquire(MilCalibration, MIL.M_CALIBRATION_STATUS + MIL.M_TYPE_MIL_INT, ref CalibrationStatus); if (CalibrationStatus != MIL.M_CALIBRATED) { MIL.McalFree(MilCalibration); MIL.MbufFree(MilImage); Console.WriteLine("Camera calibration failed."); Console.WriteLine("Press <Enter> to end."); Console.WriteLine(); Console.ReadKey(); return; } // Prepare for overlay annotations. MIL.MdispControl(MilDisplay, MIL.M_OVERLAY, MIL.M_ENABLE); MIL.MdispInquire(MilDisplay, MIL.M_OVERLAY_ID, ref MilOverlayImage); MIL.MgraColor(MIL.M_DEFAULT, MIL.M_COLOR_GREEN); // Draw camera calibration points. MIL.McalDraw(MIL.M_DEFAULT, MilCalibration, MilOverlayImage, MIL.M_DRAW_IMAGE_POINTS, MIL.M_DEFAULT, MIL.M_DEFAULT); Console.WriteLine("The camera was calibrated using a chessboard grid."); Console.WriteLine(); Console.WriteLine("Press <Enter> to continue."); Console.WriteLine(); Console.ReadKey(); // Disable overlay. MIL.MdispControl(MilDisplay, MIL.M_OVERLAY, MIL.M_DISABLE); // Load laser line image. MIL.MbufLoad(LASERLINE_FILENAME, MilImage); // Allocate 3dmap objects. MIL.M3dmapAlloc(MilSystem, MIL.M_LASER, MIL.M_CALIBRATED_CAMERA_LINEAR_MOTION, ref LaserId); MIL.M3dmapAllocResult(MilSystem, MIL.M_LASER_DATA, MIL.M_DEFAULT, ref ScanId); // Set laser line extraction options. MIL.M3dmapControl(LaserId, MIL.M_DEFAULT, MIL.M_PEAK_WIDTH, MAX_LINE_WIDTH_2); MIL.M3dmapControl(LaserId, MIL.M_DEFAULT, MIL.M_MIN_INTENSITY, MIN_INTENSITY_2); // Calibrate laser profiling context. MIL.M3dmapAddScan(LaserId, ScanId, MilImage, MIL.M_NULL, MIL.M_NULL, MIL.M_DEFAULT, MIL.M_DEFAULT); MIL.M3dmapCalibrate(LaserId, ScanId, MilCalibration, MIL.M_DEFAULT); Console.WriteLine("The laser profiling system has been calibrated using the image"); Console.WriteLine("of one laser line."); Console.WriteLine(); Console.WriteLine("Press <Enter> to continue."); Console.WriteLine(); Console.ReadKey(); // Empty all result buffer contents. // It will now be reused for extracting 3d points. MIL.M3dmapAddScan(MIL.M_NULL, ScanId, MIL.M_NULL, MIL.M_NULL, MIL.M_NULL, MIL.M_DEFAULT, MIL.M_RESET); // Set speed of scanned object (speed in mm/frame is constant). MIL.M3dmapControl(LaserId, MIL.M_DEFAULT, MIL.M_SCAN_SPEED, CONVEYOR_SPEED); // Inquire characteristics of the input sequence. MIL.MbufDiskInquire(OBJECT2_SEQUENCE_FILE, MIL.M_NUMBER_OF_IMAGES, ref NumberOfImages); MIL.MbufDiskInquire(OBJECT2_SEQUENCE_FILE, MIL.M_FRAME_RATE, ref FrameRate); // Open the object sequence file for reading. MIL.MbufImportSequence(OBJECT2_SEQUENCE_FILE, MIL.M_DEFAULT, MIL.M_NULL, MIL.M_NULL, MIL.M_NULL, MIL.M_NULL, MIL.M_NULL, MIL.M_OPEN); Console.WriteLine("The cookie is being scanned to generate 3d data."); Console.WriteLine(); // Read and process all images in the input sequence. MIL.MappTimer(MIL.M_DEFAULT, MIL.M_TIMER_READ + MIL.M_SYNCHRONOUS, ref StartTime); for (n = 0; n < NumberOfImages; n++) { // Read image from sequence. MIL.MbufImportSequence(OBJECT2_SEQUENCE_FILE, MIL.M_DEFAULT, MIL.M_LOAD, MIL.M_NULL, ref MilImage, MIL.M_DEFAULT, 1, MIL.M_READ); // Analyze the image to extract laser line and correct its depth. MIL.M3dmapAddScan(LaserId, ScanId, MilImage, MIL.M_NULL, MIL.M_NULL, MIL.M_DEFAULT, MIL.M_DEFAULT); // Wait to have a proper frame rate, if necessary. MIL.MappTimer(MIL.M_DEFAULT, MIL.M_TIMER_READ + MIL.M_SYNCHRONOUS, ref EndTime); WaitTime = (1.0 / FrameRate) - (EndTime - StartTime); if (WaitTime > 0) { MIL.MappTimer(MIL.M_DEFAULT, MIL.M_TIMER_WAIT, ref WaitTime); } MIL.MappTimer(MIL.M_DEFAULT, MIL.M_TIMER_READ + MIL.M_SYNCHRONOUS, ref StartTime); } // Close the object sequence file. MIL.MbufImportSequence(OBJECT2_SEQUENCE_FILE, MIL.M_DEFAULT, MIL.M_NULL, MIL.M_NULL, MIL.M_NULL, MIL.M_NULL, MIL.M_NULL, MIL.M_CLOSE); // Allocate image for the fully corrected depth map. MIL.MbufAlloc2d(MilSystem, DEPTH_MAP_SIZE_X, DEPTH_MAP_SIZE_Y, 16 + MIL.M_UNSIGNED, MIL.M_IMAGE + MIL.M_PROC + MIL.M_DISP, ref DepthMapId); // Set fully corrected depth map generation parameters. MIL.M3dmapControl(ScanId, MIL.M_DEFAULT, MIL.M_FILL_MODE, MIL.M_X_THEN_Y); MIL.M3dmapControl(ScanId, MIL.M_DEFAULT, MIL.M_FILL_SHARP_ELEVATION, MIL.M_MIN); MIL.M3dmapControl(ScanId, MIL.M_DEFAULT, MIL.M_FILL_SHARP_ELEVATION_DEPTH, GAP_DEPTH); MIL.M3dmapControl(ScanId, MIL.M_DEFAULT, MIL.M_PIXEL_SIZE_X, SCALE_X); MIL.M3dmapControl(ScanId, MIL.M_DEFAULT, MIL.M_PIXEL_SIZE_Y, SCALE_Y); MIL.M3dmapControl(ScanId, MIL.M_DEFAULT, MIL.M_GRAY_LEVEL_SIZE_Z, SCALE_Z); MIL.M3dmapControl(ScanId, MIL.M_DEFAULT, MIL.M_WORLD_POS_X, WORLD_OFFSET_X); MIL.M3dmapControl(ScanId, MIL.M_DEFAULT, MIL.M_WORLD_POS_Y, WORLD_OFFSET_Y); MIL.M3dmapControl(ScanId, MIL.M_DEFAULT, MIL.M_WORLD_POS_Z, WORLD_OFFSET_Z); // Get fully corrected depth map from accumulated information in the result buffer. MIL.M3dmapExtract(ScanId, DepthMapId, MIL.M_NULL, MIL.M_CORRECTED_DEPTH_MAP, MIL.M_DEFAULT, MIL.M_DEFAULT); // Remove noise. // Set all small values to 0, so that all remaining non-zeros are part of the cookie. MIL.MimClip(DepthMapId, DepthMapId, MIL.M_LESS, (MIN_HEIGHT_THRESHOLD - WORLD_OFFSET_Z) / SCALE_Z, MIL.M_NULL, 0.0, MIL.M_NULL); // Compute the volume of the cookie. MIL.M3dmapStat(DepthMapId, MIL.M_NULL, MIL.M_NULL, MIL.M_NULL, MIL.M_VOLUME, MIL.M_DEFAULT, MIL.M_DEFAULT, ref Volume); Console.WriteLine("Fully corrected 3d data of the cookie is displayed."); Console.WriteLine(); // Try to allocate D3D display. IntPtr DispHandle; DispHandle = MdepthD3DAlloc(DepthMapId, MIL.M_NULL, D3D_DISPLAY_SIZE_X, D3D_DISPLAY_SIZE_Y, SCALE_X, SCALE_Y, -SCALE_Z, MIL.M_DEFAULT, MIL.M_DEFAULT, MIL.M_DEFAULT, IntPtr.Zero); if (DispHandle != IntPtr.Zero) { // Hide Mil Display. MIL.MdispControl(MilDisplay, MIL.M_WINDOW_SHOW, MIL.M_DISABLE); MdispD3DShow(DispHandle); Console.WriteLine("D3D display controls:"); Console.WriteLine(" .Left click\tmove object"); Console.WriteLine(" .Right click\trotate object"); Console.WriteLine(" .Scroll wheel\tzoom"); Console.WriteLine(" .R\t\tstart/stop animation"); Console.WriteLine(" .P\t\tenable/disable point cloud"); Console.WriteLine(); } else { MIL.MdispControl(MilDisplay, MIL.M_VIEW_MODE, MIL.M_AUTO_SCALE); MIL.MdispSelect(MilDisplay, DepthMapId); } Console.WriteLine("Volume of the cookie is {0,4:0.0} cm^3.", -Volume / 1000.0); Console.WriteLine(); Console.WriteLine("Press <Enter> to end."); Console.WriteLine(); Console.ReadKey(); if (DispHandle != IntPtr.Zero) { MdispD3DHide(DispHandle); MdispD3DFree(DispHandle); } // Free all allocations. MIL.M3dmapFree(ScanId); MIL.M3dmapFree(LaserId); MIL.McalFree(MilCalibration); MIL.MbufFree(DepthMapId); MIL.MbufFree(MilImage); }
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 Mil4CornerArray = MIL.M_NULL; // Coefficients buffer identifier. MIL_ID MilLutX = MIL.M_NULL; // Lut buffer identifier. MIL_ID MilLutY = MIL.M_NULL; // Lut buffer identifier. MIL_ID ChildWindow = MIL.M_NULL; // Child Image identifier. float[] FourCornerMatrix = new float[12] { 0.0F, // X coordinate of quadrilateral's 1st corner 0.0F, // Y coordinate of quadrilateral's 1st corner 456.0F, // X coordinate of quadrilateral's 2nd corner 62.0F, // Y coordinate of quadrilateral's 2nd corner 333.0F, // X coordinate of quadrilateral's 3rd corner 333.0F, // Y coordinate of quadrilateral's 3rd corner 100.0F, // X coordinate of quadrilateral's 4th corner 500.0F, // Y coordinate of quadrilateral's 4th corner 0.0F, // X coordinate of rectangle's top-left corner 0.0F, // Y coordinate of rectangle's top-left corner 511.0F, // X coordinate of rectangle's bottom-right corner 511.0F }; // Y coordinate of rectangle's bottom-right corner int Precision = FIXED_POINT_PRECISION; int Interpolation = MIL.M_NEAREST_NEIGHBOR; short[] MilLutXPtr, MilLutYPtr; int OffsetX = 0; MIL_INT ImageWidth = 0; MIL_INT ImageHeight = 0; MIL_INT ImageType = 0; int i = 0; int j = 0; double FramesPerSecond = 0.0; double Time = 0.0; double NbLoop = 0.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_X, ref ImageWidth); MIL.MbufInquire(MilSourceImage, MIL.M_SIZE_Y, ref ImageHeight); MIL.MbufInquire(MilSourceImage, MIL.M_TYPE, ref ImageType); MIL.MbufAlloc2d(MilSystem, ImageWidth, ImageHeight, ImageType, MIL.M_IMAGE + MIL.M_PROC + MIL.M_DISP, ref MilDisplayImage); MIL.MbufCopy(MilSourceImage, MilDisplayImage); MIL.MdispSelect(MilDisplay, MilDisplayImage); // Print a message. Console.Write("\nWARPING:\n"); Console.Write("--------\n\n"); Console.Write("This image will be warped using different methods.\n"); Console.Write("Press <Enter> to continue.\n\n"); Console.ReadKey(); // Four-corner LUT warping //------------------------- // Allocate 2 LUT buffers. MIL.MbufAlloc2d(MilSystem, ImageWidth, ImageHeight, 16 + MIL.M_SIGNED, MIL.M_LUT, ref MilLutX); MIL.MbufAlloc2d(MilSystem, ImageWidth, ImageHeight, 16 + MIL.M_SIGNED, MIL.M_LUT, ref MilLutY); // Allocate the coefficient buffer. MIL.MbufAlloc2d(MilSystem, 12, 1, 32 + MIL.M_FLOAT, MIL.M_ARRAY, ref Mil4CornerArray); // Put warp values into the coefficient buffer. MIL.MbufPut1d(Mil4CornerArray, 0, 12, FourCornerMatrix); // Generate LUT buffers. MIL.MgenWarpParameter(Mil4CornerArray, MilLutX, MilLutY, MIL.M_WARP_4_CORNER + Precision, MIL.M_DEFAULT, 0.0, 0.0); // Clear the destination. MIL.MbufClear(MilDisplayImage, 0); // Warp the image. MIL.MimWarp(MilSourceImage, MilDisplayImage, MilLutX, MilLutY, MIL.M_WARP_LUT + Precision, Interpolation); // Print a message. Console.Write("The image was warped from an arbitrary quadrilateral to a square.\n"); Console.Write("Press <Enter> to continue.\n\n"); Console.ReadKey(); // Sinusoidal LUT warping //------------------------ // Allocate user-defined LUTs. MilLutXPtr = new short[ImageHeight * ImageWidth]; MilLutYPtr = new short[ImageHeight * ImageWidth]; // Fill the LUT with a sinusoidal waveforms with a 6-bit precision. for (j = 0; j < ImageHeight; j++) { for (i = 0; i < ImageWidth; i++) { MilLutYPtr[i + (j * ImageWidth)] = (short)FLOAT_TO_FIXED_POINT(((j) + (int)((20 * Math.Sin(0.03 * i))))); MilLutXPtr[i + (j * ImageWidth)] = (short)FLOAT_TO_FIXED_POINT(((i) + (int)((20 * Math.Sin(0.03 * j))))); } } // Put the values into the LUT buffers. MIL.MbufPut2d(MilLutX, 0, 0, ImageWidth, ImageHeight, MilLutXPtr); MIL.MbufPut2d(MilLutY, 0, 0, ImageWidth, ImageHeight, MilLutYPtr); // Clear the destination. MIL.MbufClear(MilDisplayImage, 0); // Warp the image. MIL.MimWarp(MilSourceImage, MilDisplayImage, MilLutX, MilLutY, MIL.M_WARP_LUT + Precision, Interpolation); // wait for a key Console.Write("The image was warped on two sinusoidal waveforms.\n"); Console.Write("Press <Enter> to continue.\n\n"); Console.ReadKey(); // Continuous spherical LUT warping //-------------------------------- // Allocate temporary buffer. MIL.MbufFree(MilSourceImage); MIL.MbufAlloc2d(MilSystem, ImageWidth * 2, ImageHeight, ImageType, MIL.M_IMAGE + MIL.M_PROC, ref MilSourceImage); // Reload the image. MIL.MbufLoad(IMAGE_FILE, MilSourceImage); // Fill the LUTs with a sphere pattern with a 6-bit precision. GenerateSphericLUT(ImageWidth, ImageHeight, MilLutXPtr, MilLutYPtr); MIL.MbufPut2d(MilLutX, 0, 0, ImageWidth, ImageHeight, MilLutXPtr); MIL.MbufPut2d(MilLutY, 0, 0, ImageWidth, ImageHeight, MilLutYPtr); // Duplicate the buffer to allow wrap around in the warping. MIL.MbufCopy(MilSourceImage, MilDisplayImage); MIL.MbufChild2d(MilSourceImage, ImageWidth, 0, ImageWidth, ImageHeight, ref ChildWindow); MIL.MbufCopy(MilDisplayImage, ChildWindow); MIL.MbufFree(ChildWindow); // Clear the destination. MIL.MbufClear(MilDisplayImage, 0); // Print a message and start the timer. Console.Write("The image is continuously warped on a sphere.\n"); Console.Write("Press <Enter> to stop.\n\n"); MIL.MappTimer(MIL.M_DEFAULT, MIL.M_TIMER_RESET + MIL.M_SYNCHRONOUS, MIL.M_NULL); // Warp the image continuously. while (!Console.KeyAvailable) { // Create a child in the buffer containing the two images. MIL.MbufChild2d(MilSourceImage, OffsetX, 0, ImageWidth, ImageHeight, ref ChildWindow); // Warp the child in the window. MIL.MimWarp(ChildWindow, MilDisplayImage, MilLutX, MilLutY, MIL.M_WARP_LUT + Precision, Interpolation); // Update the offset (shift the window to the right). OffsetX += ROTATION_STEP; // Reset the offset if the child is outside the buffer. if (OffsetX > ImageWidth - 1) { OffsetX = 0; } // Free the child. MIL.MbufFree(ChildWindow); NbLoop++; // Calculate and print the number of frames per second processed. MIL.MappTimer(MIL.M_DEFAULT, MIL.M_TIMER_READ + MIL.M_SYNCHRONOUS, ref Time); FramesPerSecond = NbLoop / Time; Console.Write("Processing speed: {0:0} Images/Sec.\r", FramesPerSecond); YieldToGUI(); } Console.ReadKey(); // Free objects. MIL.MbufFree(MilLutX); MIL.MbufFree(MilLutY); MIL.MbufFree(Mil4CornerArray); MIL.MbufFree(MilSourceImage); MIL.MbufFree(MilDisplayImage); MIL.MappFreeDefault(MilApplication, MilSystem, MilDisplay, MIL.M_NULL, MIL.M_NULL); }
// Find defects in corrected depth map, compute max deviation and draw contours. static void PerformBlobAnalysis(MIL_ID MilSystem, MIL_ID MilDisplay, MIL_ID MilOverlayImage, MIL_ID MilDepthMap) { MIL_ID MilBinImage = MIL.M_NULL; // Binary image buffer identifier. MIL_ID MilBlobFeatureList = MIL.M_NULL; // Feature list identifier. MIL_ID MilBlobResult = MIL.M_NULL; // Blob result buffer identifier. MIL_INT SizeX = 0; // Width of depth map. MIL_INT SizeY = 0; // Height of depth map. MIL_INT TotalBlobs = 0; // Total number of blobs. MIL_INT n = 0; // Counter. MIL_INT[] MinPixels = null; // Maximum height of defects. double DefectThreshold = 0.0; // A gray level below it is a defect. double[] CogX = null; // X coordinate of center of gravity. double[] CogY = null; // Y coordinate of center of gravity. // Get size of depth map. MIL.MbufInquire(MilDepthMap, MIL.M_SIZE_X, ref SizeX); MIL.MbufInquire(MilDepthMap, MIL.M_SIZE_Y, ref SizeY); // Allocate a binary image buffer for fast processing. MIL.MbufAlloc2d(MilSystem, SizeX, SizeY, 1 + MIL.M_UNSIGNED, MIL.M_IMAGE + MIL.M_PROC, ref MilBinImage); // Binarize image. DefectThreshold = (EXPECTED_HEIGHT - DEFECT_THRESHOLD) * SCALE_FACTOR; MIL.MimBinarize(MilDepthMap, MilBinImage, MIL.M_FIXED + MIL.M_LESS_OR_EQUAL, DefectThreshold, MIL.M_NULL); // Remove small particles. MIL.MimOpen(MilBinImage, MilBinImage, MIN_BLOB_RADIUS, MIL.M_BINARY); // Allocate a feature list. MIL.MblobAllocFeatureList(MilSystem, ref MilBlobFeatureList); // Enable the Center Of Gravity and Min Pixel features calculation. MIL.MblobSelectFeature(MilBlobFeatureList, MIL.M_CENTER_OF_GRAVITY); MIL.MblobSelectFeature(MilBlobFeatureList, MIL.M_MIN_PIXEL); // Allocate a blob result buffer. MIL.MblobAllocResult(MilSystem, ref MilBlobResult); // Calculate selected features for each blob. MIL.MblobCalculate(MilBinImage, MilDepthMap, MilBlobFeatureList, MilBlobResult); // Get the total number of selected blobs. MIL.MblobGetNumber(MilBlobResult, ref TotalBlobs); Console.WriteLine("Number of defects: {0}", TotalBlobs); // Read and print the blob characteristics. CogX = new double[TotalBlobs]; CogY = new double[TotalBlobs]; MinPixels = new MIL_INT[TotalBlobs]; if (CogX != null && CogY != null && MinPixels != null) { // Get the results. MIL.MblobGetResult(MilBlobResult, MIL.M_CENTER_OF_GRAVITY_X, CogX); MIL.MblobGetResult(MilBlobResult, MIL.M_CENTER_OF_GRAVITY_Y, CogY); MIL.MblobGetResult(MilBlobResult, MIL.M_MIN_PIXEL + MIL.M_TYPE_MIL_INT, MinPixels); // Draw the defects. MIL.MgraColor(MIL.M_DEFAULT, MIL.M_COLOR_RED); MIL.MblobDraw(MIL.M_DEFAULT, MilBlobResult, MilOverlayImage, MIL.M_DRAW_BLOBS, MIL.M_INCLUDED_BLOBS, MIL.M_DEFAULT); MIL.MgraColor(MIL.M_DEFAULT, MIL.M_COLOR_WHITE); // Print the depth of each blob. for (n = 0; n < TotalBlobs; n++) { double DepthOfDefect; string DepthString; // Write the depth of the defect in the overlay. DepthOfDefect = EXPECTED_HEIGHT - (MinPixels[n] / SCALE_FACTOR); DepthString = string.Format("{0:0.00} mm", DepthOfDefect); Console.WriteLine("Defect #{0}: depth ={1,5:0.00} mm", n, DepthOfDefect); Console.WriteLine(); MIL.MgraText(MIL.M_DEFAULT, MilOverlayImage, CogX[n] + TEXT_H_OFFSET_1, CogY[n] + TEXT_V_OFFSET_1, "Defect depth"); MIL.MgraText(MIL.M_DEFAULT, MilOverlayImage, CogX[n] + TEXT_H_OFFSET_2, CogY[n] + TEXT_V_OFFSET_2, DepthString); } } else { Console.WriteLine("Error: Not enough memory."); Console.WriteLine(); } // Free all allocations. MIL.MblobFree(MilBlobResult); MIL.MblobFree(MilBlobFeatureList); MIL.MbufFree(MilBinImage); }
static void MmodTrackingExample(MIL_ID MilSystem, MIL_ID MilDisplay, MIL_ID MilDigitizer, MIL_ID MilDisplayImage, MIL_ID MilModelImage) { MIL_ID[] MilImage = new MIL_ID[2] { MIL.M_NULL, MIL.M_NULL }; // Processing image buffer identifiers. MIL_ID SearchContext = MIL.M_NULL; // Search context identifier. MIL_ID Result = MIL.M_NULL; // Result identifier. double DrawColor = DRAW_COLOR; // Model drawing color. MIL_INT Found = 0; // Number of models found. int NbFindDone = 0; // Number of loops to find model done. double OrgX = 0.0; // Original center of model. double OrgY = 0.0; double[] Score = new double[MODEL_MAX_OCCURRENCES]; // Model correlation score. double[] x = new double[MODEL_MAX_OCCURRENCES]; // Model X position. double[] y = new double[MODEL_MAX_OCCURRENCES]; // Model Y position. double[] Angle = new double[MODEL_MAX_OCCURRENCES]; // Model occurrence angle. double[] Scale = new double[MODEL_MAX_OCCURRENCES]; // Model occurrence scale. double Time = 0.0; // Timer. // Print a start message. Console.Write("\nGEOMETRIC MODEL FINDER (scale and rotation independent):\n"); Console.Write("--------------------------------------------------------\n\n"); // Display model image. MIL.MbufCopy(MilModelImage, MilDisplayImage); // Allocate a context and define a geometric model. MIL.MmodAlloc(MilSystem, MIL.M_GEOMETRIC, MIL.M_DEFAULT, ref SearchContext); MIL.MmodDefine(SearchContext, MIL.M_IMAGE, MilModelImage, (double)MODEL_POS_X_INIT(MilModelImage) - (MODEL_WIDTH / 2), (double)MODEL_POS_Y_INIT(MilModelImage) - (MODEL_HEIGHT / 2), MODEL_WIDTH, MODEL_HEIGHT); // Allocate result. MIL.MmodAllocResult(MilSystem, MIL.M_DEFAULT, ref Result); // Draw a box around the model. MIL.MgraColor(MIL.M_DEFAULT, DrawColor); MIL.MmodDraw(MIL.M_DEFAULT, SearchContext, MilDisplayImage, MIL.M_DRAW_BOX, MIL.M_DEFAULT, MIL.M_ORIGINAL); // Set speed to VERY HIGH for fast but less precise search. MIL.MmodControl(SearchContext, MIL.M_CONTEXT, MIL.M_SPEED, MIL.M_VERY_HIGH); // Set minimum acceptance for the search. MIL.MmodControl(SearchContext, MIL.M_DEFAULT, MIL.M_ACCEPTANCE, MODEL_MIN_MATCH_SCORE); // Preprocess model. MIL.MmodPreprocess(SearchContext, MIL.M_DEFAULT); // Inquire about center of model. MIL.MmodInquire(SearchContext, MIL.M_DEFAULT, MIL.M_ORIGINAL_X, ref OrgX); MIL.MmodInquire(SearchContext, MIL.M_DEFAULT, MIL.M_ORIGINAL_Y, ref OrgY); // Print the original position. Console.Write("The Geometric target model was defined.\n"); Console.Write("Model dimensions: {0} x {1}.\n", MODEL_WIDTH, MODEL_HEIGHT); Console.Write("Model center: X={0:0.00}, Y={0:0.00}.\n", OrgX, OrgY); Console.Write("Model is scale and rotation independent.\n"); Console.Write("Press <Enter> to continue.\n\n"); Console.ReadKey(); // Allocate 2 grab buffers. MIL.MbufAlloc2d(MilSystem, MIL.MbufInquire(MilModelImage, MIL.M_SIZE_X, MIL.M_NULL), MIL.MbufInquire(MilModelImage, MIL.M_SIZE_Y, MIL.M_NULL), 8, MIL.M_IMAGE + MIL.M_GRAB + MIL.M_PROC, ref MilImage[0]); MIL.MbufAlloc2d(MilSystem, MIL.MbufInquire(MilModelImage, MIL.M_SIZE_X, MIL.M_NULL), MIL.MbufInquire(MilModelImage, MIL.M_SIZE_Y, MIL.M_NULL), 8, MIL.M_IMAGE + MIL.M_GRAB + MIL.M_PROC, ref MilImage[1]); // Grab continuously grab and perform the find operation using double buffering. Console.Write("\nContinuously finding the Geometric Model.\n"); Console.Write("Press a <Enter> to stop.\n\n"); // Grab a first target image into first buffer (done twice for timer reset accuracy). MIL.MdigControl(MilDigitizer, MIL.M_GRAB_MODE, MIL.M_ASYNCHRONOUS); MIL.MdigGrab(MilDigitizer, MilImage[NbFindDone % 2]); MIL.MdigGrab(MilDigitizer, MilImage[NbFindDone % 2]); MIL.MappTimer(MIL.M_DEFAULT, MIL.M_TIMER_RESET, ref Time); // Loop, processing one buffer while grabbing the other. do { // Grab a target image into the other buffer. MIL.MdigGrab(MilDigitizer, MilImage[(NbFindDone + 1) % 2]); // Read the time. MIL.MappTimer(MIL.M_DEFAULT, MIL.M_TIMER_READ, ref Time); // Find model. MIL.MmodFind(SearchContext, MilImage[NbFindDone % 2], Result); // Get the number of occurrences found. MIL.MmodGetResult(Result, MIL.M_DEFAULT, MIL.M_NUMBER + MIL.M_TYPE_MIL_INT, ref Found); // Print a message based on the score. if ((Found >= 1) && (Found < MODEL_MAX_OCCURRENCES)) { // Get results. MIL.MmodGetResult(Result, MIL.M_DEFAULT, MIL.M_POSITION_X, x); MIL.MmodGetResult(Result, MIL.M_DEFAULT, MIL.M_POSITION_Y, y); MIL.MmodGetResult(Result, MIL.M_DEFAULT, MIL.M_SCALE, Scale); MIL.MmodGetResult(Result, MIL.M_DEFAULT, MIL.M_ANGLE, Angle); MIL.MmodGetResult(Result, MIL.M_DEFAULT, MIL.M_SCORE, Score); // Draw a box and a cross where the model was found and print the results. MIL.MmodDraw(MIL.M_DEFAULT, Result, MilImage[NbFindDone % 2], MIL.M_DRAW_BOX + MIL.M_DRAW_POSITION + MIL.M_DRAW_EDGES, MIL.M_DEFAULT, MIL.M_DEFAULT); Console.Write("Found: X={0,6:0.0}, Y={1,6:0.0}, Angle={2,6:0.0}, Scale={3,5:0.00}, Score={4,5:0.0}% ({5,5:0.0} fps).\r", x[0], y[0], Angle[0], Scale[0], Score[0], (NbFindDone + 1) / Time); } else { // Print the "not found" message. Console.Write("Not found! (score<{0,5:0.0}%) ({1,5:0.0} fps).\r", MODEL_MIN_MATCH_SCORE, (NbFindDone + 1) / Time); } // Copy target image to the display. MIL.MbufCopy(MilImage[NbFindDone % 2], MilDisplayImage); // Increment the counter. NbFindDone++; }while (!Console.KeyAvailable); Console.ReadKey(); Console.Write("\n\n"); // Wait for the end of last grab. MIL.MdigGrabWait(MilDigitizer, MIL.M_GRAB_END); // Free all allocations. MIL.MmodFree(Result); MIL.MmodFree(SearchContext); MIL.MbufFree(MilImage[1]); MIL.MbufFree(MilImage[0]); }
//**************************************************************************** // Tracking object with pattern matching module. //**************************************************************************** static void MpatTrackingExample(MIL_ID MilSystem, MIL_ID MilDisplay, MIL_ID MilDigitizer, MIL_ID MilDisplayImage, MIL_ID MilModelImage) { MIL_ID[] MilImage = new MIL_ID[2] { MIL.M_NULL, MIL.M_NULL }; // Processing image buffer identifiers. MIL_ID Model = MIL.M_NULL; // Model identifier. MIL_ID Result = MIL.M_NULL; // Result identifier. double DrawColor = DRAW_COLOR; // Model drawing color. MIL_INT Found = 0; // Number of found models. int NbFindDone = 0; // Number of loops to find model done. double OrgX = 0.0; // Original center of model. double OrgY = 0.0; double x = 0.0; // Result variables. double y = 0.0; double Score = 0.0; double Time = 0.0; // Timer. // Print a start message. Console.Write("\nGRAYSCALE PATTERN MATCHING:\n"); Console.Write("---------------------------\n\n"); // Display the model image. MIL.MbufCopy(MilModelImage, MilDisplayImage); // Allocate normalized grayscale type model. MIL.MpatAllocModel(MilSystem, MilModelImage, MODEL_POS_X_INIT(MilModelImage) - (MODEL_WIDTH / 2), MODEL_POS_Y_INIT(MilModelImage) - (MODEL_HEIGHT / 2), MODEL_WIDTH, MODEL_HEIGHT, MIL.M_NORMALIZED, ref Model); // Allocate result. MIL.MpatAllocResult(MilSystem, 1, ref Result); // Draw box around the model. MIL.MgraColor(MIL.M_DEFAULT, DrawColor); MIL.MpatDraw(MIL.M_DEFAULT, Model, MilDisplayImage, MIL.M_DRAW_BOX, MIL.M_DEFAULT, MIL.M_ORIGINAL); // Set minimum acceptance for search. MIL.MpatSetAcceptance(Model, MODEL_MIN_MATCH_SCORE); // Set speed. MIL.MpatSetSpeed(Model, MIL.M_HIGH); // Set accuracy. MIL.MpatSetAccuracy(Model, MIL.M_LOW); // Preprocess model. MIL.MpatPreprocModel(MilModelImage, Model, MIL.M_DEFAULT); // Inquire about center of model. MIL.MpatInquire(Model, MIL.M_ORIGINAL_X, ref OrgX); MIL.MpatInquire(Model, MIL.M_ORIGINAL_Y, ref OrgY); // Print the original position. Console.Write("A Grayscale Model was defined.\n"); Console.Write("Model dimensions: {0} x {1}.\n", MODEL_WIDTH, MODEL_HEIGHT); Console.Write("Model center: X={0:0.00}, Y={0:0.00}.\n", OrgX, OrgY); Console.Write("Model is scale and rotation dependant.\n"); Console.Write("Press <Enter> to continue.\n\n"); Console.ReadKey(); // Allocate 2 grab buffers. MIL.MbufAlloc2d(MilSystem, MIL.MbufInquire(MilModelImage, MIL.M_SIZE_X, MIL.M_NULL), MIL.MbufInquire(MilModelImage, MIL.M_SIZE_Y, MIL.M_NULL), 8, MIL.M_IMAGE + MIL.M_GRAB + MIL.M_PROC, ref MilImage[0]); MIL.MbufAlloc2d(MilSystem, MIL.MbufInquire(MilModelImage, MIL.M_SIZE_X, MIL.M_NULL), MIL.MbufInquire(MilModelImage, MIL.M_SIZE_Y, MIL.M_NULL), 8, MIL.M_IMAGE + MIL.M_GRAB + MIL.M_PROC, ref MilImage[1]); // Grab continuously and perform the find operation using double buffering. Console.Write("\nContinuously finding the Grayscale model.\n"); Console.Write("Press <Enter> to stop.\n\n"); // Grab a first target image into first buffer (done twice for timer reset accuracy). MIL.MdigControl(MilDigitizer, MIL.M_GRAB_MODE, MIL.M_ASYNCHRONOUS); MIL.MdigGrab(MilDigitizer, MilImage[NbFindDone % 2]); MIL.MdigGrab(MilDigitizer, MilImage[NbFindDone % 2]); MIL.MappTimer(MIL.M_DEFAULT, MIL.M_TIMER_RESET, ref Time); // Loop, processing one buffer while grabbing the other. do { // Grab a target image into the other buffer. MIL.MdigGrab(MilDigitizer, MilImage[(NbFindDone + 1) % 2]); // Read the time. MIL.MappTimer(MIL.M_DEFAULT, MIL.M_TIMER_READ, ref Time); // Find model. MIL.MpatFindModel(MilImage[NbFindDone % 2], Model, Result); // Get results. MIL.MpatGetNumber(Result, ref Found); MIL.MpatGetResult(Result, MIL.M_POSITION_X, ref x); MIL.MpatGetResult(Result, MIL.M_POSITION_Y, ref y); MIL.MpatGetResult(Result, MIL.M_SCORE, ref Score); // Print a message based upon the score. if (Found > 0) { // Draw a box around the model and print the results. MIL.MpatDraw(MIL.M_DEFAULT, Result, MilImage[NbFindDone % 2], MIL.M_DRAW_BOX + MIL.M_DRAW_POSITION, MIL.M_DEFAULT, MIL.M_DEFAULT); Console.Write("Found: X={0,7:0.00}, Y={1,7:0.00}, Score={2,5:0.0}% ({3:0.0} fps). \r", x, y, Score, (NbFindDone + 1) / Time); } else { // Print the "not found" message. Console.Write("Not found ! (score<{0,5:0.0}%) ({1:0.0} fps). \r", MODEL_MIN_MATCH_SCORE, (NbFindDone + 1) / Time); } // Copy target image to the display. MIL.MbufCopy(MilImage[NbFindDone % 2], MilDisplayImage); // Increment find count NbFindDone++; }while (!Console.KeyAvailable); Console.ReadKey(); Console.Write("\n\n"); // Wait for end of last grab. MIL.MdigGrabWait(MilDigitizer, MIL.M_GRAB_END); // Free all allocated objects. MIL.MpatFree(Result); MIL.MpatFree(Model); MIL.MbufFree(MilImage[1]); MIL.MbufFree(MilImage[0]); }
// Main function. static void Main(string[] args) { MIL_ID MilApplication = 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]; int MilGrabBufferListSize = 0; MIL_INT ProcessFrameCount = 0; double ProcessFrameRate = 0; HookDataStruct UserHookData = new HookDataStruct(); // Allocate defaults. MIL.MappAllocDefault(MIL.M_DEFAULT, ref MilApplication, ref MilSystem, ref MilDisplay, ref MilDigitizer, ref MilImageDisp); // 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.MbufAlloc2d(MilSystem, 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 (int n = 0; n < 2 && MilGrabBufferListSize > 0; n++) { MilGrabBufferListSize--; MIL.MbufFree(MilGrabBufferList[MilGrabBufferListSize]); } // Print a message. Console.WriteLine(); Console.WriteLine("MULTIPLE BUFFERED PROCESSING."); Console.WriteLine("-----------------------------"); Console.WriteLine(); Console.Write("Press <Enter> to start processing.\r"); // Grab continuously on the display and wait for a key press. MIL.MdigGrabContinuous(MilDigitizer, MilImageDisp); Console.ReadKey(); // Halt continuous grab. MIL.MdigHalt(MilDigitizer); // Initialize the user's processing function data structure. UserHookData.MilDigitizer = MilDigitizer; UserHookData.MilImageDisp = MilImageDisp; UserHookData.ProcessedImageCount = 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 hUserData = GCHandle.Alloc(UserHookData); MIL_DIG_HOOK_FUNCTION_PTR ProcessingFunctionPtr = new MIL_DIG_HOOK_FUNCTION_PTR(ProcessingFunction); // Start the processing. The processing function is called with every frame grabbed. MIL.MdigProcess(MilDigitizer, MilGrabBufferList, MilGrabBufferListSize, MIL.M_START, MIL.M_DEFAULT, ProcessingFunctionPtr, GCHandle.ToIntPtr(hUserData)); // Here the main() is free to perform other tasks while the processing is executing. // --------------------------------------------------------------------------------- // Print a message and wait for a key press after a minimum number of frames. Console.WriteLine("Press <Enter> to stop. "); Console.WriteLine(); Console.ReadKey(); // Stop the processing. MIL.MdigProcess(MilDigitizer, MilGrabBufferList, MilGrabBufferListSize, MIL.M_STOP, MIL.M_DEFAULT, ProcessingFunctionPtr, GCHandle.ToIntPtr(hUserData)); // Free the GCHandle when no longer used hUserData.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(); Console.WriteLine(); Console.WriteLine("{0} frames grabbed at {1:0.0} frames/sec ({2:0.0} ms/frame).", ProcessFrameCount, ProcessFrameRate, 1000.0 / ProcessFrameRate); Console.WriteLine("Press <Enter> to end."); Console.WriteLine(); Console.ReadKey(); // Free the grab buffers. while (MilGrabBufferListSize > 0) { MIL.MbufFree(MilGrabBufferList[--MilGrabBufferListSize]); } // Release defaults. MIL.MappFreeDefault(MilApplication, MilSystem, MilDisplay, MilDigitizer, MilImageDisp); }
public bool RegisterMarkModel(int iCamNo, ref CVisionPatternData pSData) { // 0 위치를 화면의 중앙으로 설정함. pSData.m_rectModel.X = m_pDisplay[iCamNo].GetImageWidth() / 2; pSData.m_rectModel.Y = m_pDisplay[iCamNo].GetImageHeight() / 2; MIL_ID m_MilImage = m_pDisplay[iCamNo].GetImage(); MIL_ID m_DisplayGraph = m_pDisplay[iCamNo].GetViewGraph(); //Draw할 Rec을 생성한다. Rectangle pRec = new Rectangle(pSData.m_rectModel.X - pSData.m_rectModel.Width / 2, pSData.m_rectModel.Y - pSData.m_rectModel.Height / 2, pSData.m_rectModel.Width, pSData.m_rectModel.Height); // Allocate a normalized grayscale model. MIL.MpatAllocModel(m_MilSystem, m_MilImage, pRec.X, pRec.Y, pRec.Width, pRec.Height, MIL.M_NORMALIZED, ref pSData.m_milModel); // Model Image Save (Image View Save용) MIL.MbufAlloc2d(m_MilSystem, pRec.Width, pRec.Height, MIL.M_UNSIGNED + 8, MIL.M_IMAGE + MIL.M_PROC + MIL.M_DISP, ref pSData.m_ModelImage); MIL.MbufCopyColor2d(m_MilImage, pSData.m_ModelImage, MIL.M_ALL_BANDS, pRec.X, pRec.Y, MIL.M_ALL_BANDS, 0, 0, pRec.Width, pRec.Height); if (pSData.m_milModel == MIL.M_NULL) { return(false); } MIL.MpatAllocResult(m_MilSystem, MIL.M_DEFAULT, ref m_SearchResult); // Set the search accuracy to high. MIL.MpatSetAccuracy(pSData.m_milModel, MIL.M_HIGH); MIL.MpatSetAcceptance(pSData.m_milModel, pSData.m_dAcceptanceThreshold); // Acceptance Threshold Setting MIL.MpatSetCertainty(pSData.m_milModel, pSData.m_dAcceptanceThreshold); // Set Certainty Threshold MIL.MpatSetCenter(pSData.m_milModel, // Pattern Mark에서 Offset 설정함. (double)pSData.m_pointReference.X, (double)pSData.m_pointReference.Y); // Set the search model speed to high. MIL.MpatSetSpeed(pSData.m_milModel, MIL.M_HIGH); //================================================================================================ //// Angle 설정 //MIL.MpatSetAngle(pSData.m_milModel, MIL.M_SEARCH_ANGLE_MODE, MIL.M_ENABLE); //MIL.MpatSetAngle(pSData.m_milModel, MIL.M_SEARCH_ANGLE_DELTA_NEG, 3.0); //MIL.MpatSetAngle(pSData.m_milModel, MIL.M_SEARCH_ANGLE_DELTA_POS, 3.0); //MIL.MpatSetAngle(pSData.m_milModel, MIL.M_SEARCH_ANGLE_ACCURACY, 0.25); //================================================================================================ // Preprocess the model. MIL.MpatPreprocModel(m_MilImage, pSData.m_milModel, MIL.M_DEFAULT); // Draw a box around the model in the model image. MIL.MpatDraw(MIL.M_DEFAULT, pSData.m_milModel, m_DisplayGraph, MIL.M_DRAW_BOX, MIL.M_DEFAULT, MIL.M_ORIGINAL); // Save Image Bitmap return(true); }
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 MilSubImage = MIL.M_NULL; // Sub-image buffer identifier. MIL_ID MilFontSubImage = MIL.M_NULL; // Font display sub image. MIL_ID MilOverlayImage = MIL.M_NULL; // Overlay image. MIL_ID OcrFont = MIL.M_NULL; // OCR font identifier. MIL_ID OcrResult = MIL.M_NULL; // OCR result buffer identifier. double Score = 0; // Reading score. MIL_INT SizeX = 0; // Source image size x. MIL_INT SizeY = 0; // Source image size y. MIL_INT Type = 0; // Source image type. StringBuilder ReadString = new StringBuilder(STRING_LENGTH); // Characters to read. Console.Write("\nOCR MODULE (SEMI font reading):\n"); Console.Write("-------------------------------\n\n"); // Allocate defaults. MIL.MappAllocDefault(MIL.M_DEFAULT, ref MilApplication, ref MilSystem, ref MilDisplay, MIL.M_NULL, MIL.M_NULL); // Load and display the source image into a new image buffer. MIL.MbufAlloc2d(MilSystem, MIL.MbufDiskInquire(CHAR_IMAGE_FILE, MIL.M_SIZE_X, ref SizeX), MIL.MbufDiskInquire(CHAR_IMAGE_FILE, MIL.M_SIZE_Y, ref SizeY) * 3 / 2, MIL.MbufDiskInquire(CHAR_IMAGE_FILE, MIL.M_TYPE, ref Type), MIL.M_IMAGE + MIL.M_PROC + MIL.M_DISP, ref MilImage); MIL.MbufClear(MilImage, 0); MIL.MbufLoad(CHAR_IMAGE_FILE, MilImage); MIL.MdispSelect(MilDisplay, MilImage); // Restrict the region of the image where to read the string. MIL.MbufChild2d(MilImage, READ_REGION_POS_X, READ_REGION_POS_Y, READ_REGION_WIDTH, READ_REGION_HEIGHT, ref MilSubImage); // Define the bottom of the image as the region where to copy the font representation. MIL.MbufChild2d(MilImage, 50, SizeY + 10, SizeX - 100, (SizeY / 3) - 10, ref MilFontSubImage); // Restore the OCR character font from disk. MIL.MocrRestoreFont(FONT_FILE_IN, MIL.M_RESTORE, MilSystem, ref OcrFont); /* Show the font representation. */ MIL.MocrCopyFont(MilFontSubImage, OcrFont, MIL.M_COPY_FROM_FONT + MIL.M_ALL_CHAR, ""); // Pause to show the original image. Console.Write("The SEMI string at the top will be read using the font displayed at the bottom.\n\n"); Console.Write("Calibrating SEMI font...\n\n"); // Calibrate the OCR font. MIL.MocrCalibrateFont(MilSubImage, OcrFont, STRING_CALIBRATION, CHAR_SIZE_X_MIN, CHAR_SIZE_X_MAX, CHAR_SIZE_X_STEP, CHAR_SIZE_Y_MIN, CHAR_SIZE_Y_MAX, CHAR_SIZE_Y_STEP, MIL.M_DEFAULT); // Set the user-specific character constraints for each string position. MIL.MocrSetConstraint(OcrFont, 0, MIL.M_LETTER); // A to Z only MIL.MocrSetConstraint(OcrFont, 1, MIL.M_DIGIT, "9"); // 9 only MIL.MocrSetConstraint(OcrFont, 2, MIL.M_DIGIT); // 0 to 9 only MIL.MocrSetConstraint(OcrFont, 3, MIL.M_DIGIT); // 0 to 9 only MIL.MocrSetConstraint(OcrFont, 4, MIL.M_DIGIT); // 0 to 9 only MIL.MocrSetConstraint(OcrFont, 5, MIL.M_DIGIT); // 0 to 9 only MIL.MocrSetConstraint(OcrFont, 6, MIL.M_DIGIT); // 0 to 9 only MIL.MocrSetConstraint(OcrFont, 7, MIL.M_DEFAULT, "-"); // - only MIL.MocrSetConstraint(OcrFont, 8, MIL.M_LETTER, "M"); // M only MIL.MocrSetConstraint(OcrFont, 9, MIL.M_LETTER, "X"); // X only MIL.MocrSetConstraint(OcrFont, 10, MIL.M_LETTER, "ABCDEFGH"); // SEMI checksum MIL.MocrSetConstraint(OcrFont, 11, MIL.M_DIGIT, "01234567"); // SEMI checksum // Pause before the read operation. Console.Write("Press <Enter> to continue.\n\n"); Console.ReadKey(); // Allocate an OCR result buffer. MIL.MocrAllocResult(MilSystem, MIL.M_DEFAULT, ref OcrResult); // Read the string. MIL.MocrReadString(MilSubImage, OcrFont, OcrResult); // Get the string and its reading score. MIL.MocrGetResult(OcrResult, MIL.M_STRING, ReadString); MIL.MocrGetResult(OcrResult, MIL.M_STRING_SCORE, ref Score); // Print the result. Console.Write("\nThe string read is: \"{0}\" (score: {1:P1}).\n\n", ReadString.ToString(), Score / 100); // Draw the string in the overlay under the reading region. 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 MilOverlayImage); MIL.MgraFont(MIL.M_DEFAULT, MIL.M_FONT_DEFAULT_LARGE); MIL.MgraColor(MIL.M_DEFAULT, MIL.M_COLOR_YELLOW); MIL.MgraText(MIL.M_DEFAULT, MilOverlayImage, READ_REGION_POS_X + (READ_REGION_WIDTH / 4), READ_REGION_POS_Y + READ_REGION_HEIGHT + 50, ReadString.ToString()); // Save the calibrated font if the reading score was sufficiently high. if (Score > READ_SCORE_MIN) { MIL.MocrSaveFont(FONT_FILE_OUT, MIL.M_SAVE, OcrFont); Console.Write("Read successful, calibrated OCR font was saved to disk.\n"); } else { Console.Write("Error: Read score too low, calibrated OCR font not saved.\n"); } Console.Write("Press <Enter> to end.\n\n\n"); Console.ReadKey(); // Clear the overlay. MIL.MdispControl(MilDisplay, MIL.M_OVERLAY_CLEAR, MIL.M_DEFAULT); // Free all allocations. MIL.MocrFree(OcrFont); MIL.MocrFree(OcrResult); MIL.MbufFree(MilSubImage); MIL.MbufFree(MilFontSubImage); MIL.MbufFree(MilImage); MIL.MappFreeDefault(MilApplication, MilSystem, MilDisplay, MIL.M_NULL, MIL.M_NULL); }
static void DepthCorrectionExample(MIL_ID MilSystem, MIL_ID MilDisplay) { MIL_ID MilOverlayImage = MIL.M_NULL; // Overlay image buffer identifier. MIL_ID MilImage = MIL.M_NULL; // Image buffer identifier (for processing). MIL_ID MilDepthMap = MIL.M_NULL; // Image buffer identifier (for results). MIL_ID MilLaser = MIL.M_NULL; // 3dmap laser profiling context identifier. MIL_ID MilScan = MIL.M_NULL; // 3dmap result buffer identifier. MIL_INT SizeX = 0; // Width of grabbed images. MIL_INT SizeY = 0; // Height of grabbed images. MIL_INT NbReferencePlanes = 0; // Number of reference planes of known heights. MIL_INT NbObjectImages = 0; // Number of frames for scanned objects. MIL_INT n = 0; // Counter. double FrameRate = 0.0; // Number of grabbed frames per second (in AVI). double StartTime = 0.0; // Time at the beginning of each iteration. double EndTime = 0.0; // Time after processing for each iteration. double WaitTime = 0.0; // Time to wait for next frame. // Inquire characteristics of the input sequences. MIL.MbufDiskInquire(REFERENCE_PLANES_SEQUENCE_FILE, MIL.M_SIZE_X, ref SizeX); MIL.MbufDiskInquire(REFERENCE_PLANES_SEQUENCE_FILE, MIL.M_SIZE_Y, ref SizeY); MIL.MbufDiskInquire(REFERENCE_PLANES_SEQUENCE_FILE, MIL.M_NUMBER_OF_IMAGES, ref NbReferencePlanes); MIL.MbufDiskInquire(REFERENCE_PLANES_SEQUENCE_FILE, MIL.M_FRAME_RATE, ref FrameRate); MIL.MbufDiskInquire(OBJECT_SEQUENCE_FILE, MIL.M_NUMBER_OF_IMAGES, ref NbObjectImages); // Allocate buffer to hold images. MIL.MbufAlloc2d(MilSystem, SizeX, SizeY, 8 + MIL.M_UNSIGNED, MIL.M_IMAGE + MIL.M_DISP + MIL.M_PROC, ref MilImage); MIL.MbufClear(MilImage, 0.0); Console.WriteLine(); Console.WriteLine("DEPTH ANALYSIS:"); Console.WriteLine("---------------"); Console.WriteLine(); Console.WriteLine("This program performs a surface inspection to detect depth"); Console.WriteLine("defects on a wood surface using a laser profiling system."); Console.WriteLine(); Console.WriteLine("Press <Enter> to continue."); Console.WriteLine(); Console.ReadKey(); // Select display. MIL.MdispSelect(MilDisplay, MilImage); // Prepare for overlay annotations. MIL.MdispControl(MilDisplay, MIL.M_OVERLAY, MIL.M_ENABLE); MIL.MdispInquire(MilDisplay, MIL.M_OVERLAY_ID, ref MilOverlayImage); MIL.MgraControl(MIL.M_DEFAULT, MIL.M_BACKGROUND_MODE, MIL.M_TRANSPARENT); MIL.MgraColor(MIL.M_DEFAULT, MIL.M_COLOR_WHITE); // Allocate 3dmap objects. MIL.M3dmapAlloc(MilSystem, MIL.M_LASER, MIL.M_DEPTH_CORRECTION, ref MilLaser); MIL.M3dmapAllocResult(MilSystem, MIL.M_LASER_DATA, MIL.M_DEFAULT, ref MilScan); // Set laser line extraction options. MIL.M3dmapControl(MilLaser, MIL.M_DEFAULT, MIL.M_PEAK_WIDTH, MAX_LINE_WIDTH); MIL.M3dmapControl(MilLaser, MIL.M_DEFAULT, MIL.M_MIN_INTENSITY, MIN_INTENSITY); // Open the calibration sequence file for reading. MIL.MbufImportSequence(REFERENCE_PLANES_SEQUENCE_FILE, MIL.M_DEFAULT, MIL.M_NULL, MIL.M_NULL, MIL.M_NULL, MIL.M_NULL, MIL.M_NULL, MIL.M_OPEN); // Read and process all images in the input sequence. MIL.MappTimer(MIL.M_DEFAULT, MIL.M_TIMER_READ + MIL.M_SYNCHRONOUS, ref StartTime); for (n = 0; n < NbReferencePlanes; n++) { string CalibString; // Read image from sequence. MIL.MbufImportSequence(REFERENCE_PLANES_SEQUENCE_FILE, MIL.M_DEFAULT, MIL.M_LOAD, MIL.M_NULL, ref MilImage, MIL.M_DEFAULT, 1, MIL.M_READ); // Annotate the image with the calibration height. MIL.MdispControl(MilDisplay, MIL.M_OVERLAY_CLEAR, MIL.M_DEFAULT); CalibString = string.Format("Reference plane {0}: {1:0.00} mm", n + 1, CORRECTED_DEPTHS[n]); MIL.MgraText(MIL.M_DEFAULT, MilOverlayImage, CALIB_TEXT_POS_X, CALIB_TEXT_POS_Y, CalibString); // Set desired corrected depth of next reference plane. MIL.M3dmapControl(MilLaser, MIL.M_DEFAULT, MIL.M_CORRECTED_DEPTH, CORRECTED_DEPTHS[n] * SCALE_FACTOR); // Analyze the image to extract laser line. MIL.M3dmapAddScan(MilLaser, MilScan, MilImage, MIL.M_NULL, MIL.M_NULL, MIL.M_DEFAULT, MIL.M_DEFAULT); // Wait to have a proper frame rate, if necessary. MIL.MappTimer(MIL.M_DEFAULT, MIL.M_TIMER_READ + MIL.M_SYNCHRONOUS, ref EndTime); WaitTime = (1.0 / FrameRate) - (EndTime - StartTime); if (WaitTime > 0) { MIL.MappTimer(MIL.M_DEFAULT, MIL.M_TIMER_WAIT, ref WaitTime); } MIL.MappTimer(MIL.M_DEFAULT, MIL.M_TIMER_READ + MIL.M_SYNCHRONOUS, ref StartTime); } // Close the calibration sequence file. MIL.MbufImportSequence(REFERENCE_PLANES_SEQUENCE_FILE, MIL.M_DEFAULT, MIL.M_NULL, MIL.M_NULL, MIL.M_NULL, MIL.M_NULL, MIL.M_NULL, MIL.M_CLOSE); // Calibrate the laser profiling context using reference planes of known heights. MIL.M3dmapCalibrate(MilLaser, MilScan, MIL.M_NULL, MIL.M_DEFAULT); Console.WriteLine("The laser profiling system has been calibrated using 4 reference"); Console.WriteLine("planes of known heights."); Console.WriteLine(); Console.WriteLine("Press <Enter> to continue."); Console.WriteLine(); Console.ReadKey(); Console.WriteLine("The wood surface is being scanned."); Console.WriteLine(); // Empty all result buffer contents. // It will now be reused for extracting corrected depths. MIL.M3dmapAddScan(MIL.M_NULL, MilScan, MIL.M_NULL, MIL.M_NULL, MIL.M_NULL, MIL.M_DEFAULT, MIL.M_RESET); // Open the object sequence file for reading. MIL.MbufDiskInquire(OBJECT_SEQUENCE_FILE, MIL.M_FRAME_RATE, ref FrameRate); MIL.MbufImportSequence(OBJECT_SEQUENCE_FILE, MIL.M_DEFAULT, MIL.M_NULL, MIL.M_NULL, MIL.M_NULL, MIL.M_NULL, MIL.M_NULL, MIL.M_OPEN); // Read and process all images in the input sequence. MIL.MappTimer(MIL.M_DEFAULT, MIL.M_TIMER_READ + MIL.M_SYNCHRONOUS, ref StartTime); MIL.MdispControl(MilDisplay, MIL.M_OVERLAY_CLEAR, MIL.M_DEFAULT); for (n = 0; n < NbObjectImages; n++) { // Read image from sequence. MIL.MbufImportSequence(OBJECT_SEQUENCE_FILE, MIL.M_DEFAULT, MIL.M_LOAD, MIL.M_NULL, ref MilImage, MIL.M_DEFAULT, 1, MIL.M_READ); // Analyze the image to extract laser line and correct its depth. MIL.M3dmapAddScan(MilLaser, MilScan, MilImage, MIL.M_NULL, MIL.M_NULL, MIL.M_DEFAULT, MIL.M_DEFAULT); // Wait to have a proper frame rate, if necessary. MIL.MappTimer(MIL.M_DEFAULT, MIL.M_TIMER_READ + MIL.M_SYNCHRONOUS, ref EndTime); WaitTime = (1.0 / FrameRate) - (EndTime - StartTime); if (WaitTime > 0) { MIL.MappTimer(MIL.M_DEFAULT, MIL.M_TIMER_WAIT, ref WaitTime); } MIL.MappTimer(MIL.M_DEFAULT, MIL.M_TIMER_READ + MIL.M_SYNCHRONOUS, ref StartTime); } // Close the object sequence file. MIL.MbufImportSequence(OBJECT_SEQUENCE_FILE, MIL.M_DEFAULT, MIL.M_NULL, MIL.M_NULL, MIL.M_NULL, MIL.M_NULL, MIL.M_NULL, MIL.M_CLOSE); // Allocate the image for a partially corrected depth map. MIL.MbufAlloc2d(MilSystem, SizeX, NbObjectImages, 16 + MIL.M_UNSIGNED, MIL.M_IMAGE + MIL.M_PROC + MIL.M_DISP, ref MilDepthMap); // Get partially corrected depth map from accumulated information in the result buffer. MIL.M3dmapExtract(MilScan, MilDepthMap, MIL.M_NULL, MIL.M_CORRECTED_DEPTH_MAP, MIL.M_DEFAULT, MIL.M_DEFAULT); // Show partially corrected depth map and find defects. SetupColorDisplay(MilSystem, MilDisplay, MIL.MbufInquire(MilDepthMap, MIL.M_SIZE_BIT, MIL.M_NULL)); // Display partially corrected depth map. MIL.MdispSelect(MilDisplay, MilDepthMap); MIL.MdispInquire(MilDisplay, MIL.M_OVERLAY_ID, ref MilOverlayImage); Console.WriteLine("The pseudo-color depth map of the surface is displayed."); Console.WriteLine(); Console.WriteLine("Press <Enter> to continue."); Console.WriteLine(); Console.ReadKey(); PerformBlobAnalysis(MilSystem, MilDisplay, MilOverlayImage, MilDepthMap); Console.WriteLine("Press <Enter> to continue."); Console.WriteLine(); Console.ReadKey(); // Disassociates display LUT and clear overlay. MIL.MdispLut(MilDisplay, MIL.M_DEFAULT); MIL.MdispControl(MilDisplay, MIL.M_OVERLAY_CLEAR, MIL.M_DEFAULT); // Free all allocations. MIL.M3dmapFree(MilScan); MIL.M3dmapFree(MilLaser); MIL.MbufFree(MilDepthMap); MIL.MbufFree(MilImage); }
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 MilImage = MIL.M_NULL; // Image buffer identifier. MIL_ID MilKernel = MIL.M_NULL; // Custom kernel identifier. int n = 0; double Time = 0.0; // Allocate defaults. MIL.MappAllocDefault(MIL.M_DEFAULT, ref MilApplication, ref MilSystem, ref MilDisplay, MIL.M_NULL, MIL.M_NULL); // Restore source image into an automatically allocated image buffers. MIL.MbufRestore(IMAGE_FILE, MilSystem, ref MilImage); MIL.MbufRestore(IMAGE_FILE, MilSystem, ref MilDisplayImage); // Zoom display to see the result of image processing better. MIL.MdispZoom(MilDisplay, ZOOM_VALUE, ZOOM_VALUE); // Display the image buffer. MIL.MdispSelect(MilDisplay, MilDisplayImage); // Pause to show the original image. Console.Write("\nIMAGE PROCESSING:\n"); Console.Write("-----------------\n\n"); Console.Write("This program performs a convolution on the displayed image.\n"); Console.Write("It uses a custom smoothing kernel.\n"); Console.Write("Press <Enter> to continue.\n\n"); Console.ReadKey(); // Allocate a MIL kernel. MIL.MbufAlloc2d(MilSystem, KERNEL_WIDTH, KERNEL_HEIGHT, KERNEL_DEPTH + MIL.M_UNSIGNED, MIL.M_KERNEL, ref MilKernel); // Put the custom data in it. MIL.MbufPut(MilKernel, KernelData); // Set a normalization (divide) factor to have a kernel with // a sum equal to one. MIL.MbufControlNeighborhood(MilKernel, MIL.M_NORMALIZATION_FACTOR, 16); // Convolve the image using the kernel. MIL.MimConvolve(MilImage, MilDisplayImage, MilKernel); // Now time the convolution (MimConvolve()): // Overscan calculation is disabled and a destination image that // is not displayed is used to have the real convolution time. Also the // function must be called once before the timing loop for more accurate // time (dll load, ...). MIL.MbufControlNeighborhood(MilKernel, MIL.M_OVERSCAN, MIL.M_DISABLE); MIL.MimConvolve(MilDisplayImage, MilImage, MilKernel); MIL.MappTimer(MIL.M_DEFAULT, MIL.M_TIMER_RESET + MIL.M_SYNCHRONOUS, MIL.M_NULL); for (n = 0; n < NB_LOOP; n++) { MIL.MimConvolve(MilDisplayImage, MilImage, MilKernel); } MIL.MappTimer(MIL.M_DEFAULT, MIL.M_TIMER_READ + MIL.M_SYNCHRONOUS, ref Time); // Pause to show the result. Console.Write("Convolve time: {0:0.000} ms.\n", Time * 1000 / NB_LOOP); Console.Write("Press <Enter> to terminate.\n"); Console.ReadKey(); // Free all allocations. MIL.MbufFree(MilKernel); MIL.MbufFree(MilImage); MIL.MbufFree(MilDisplayImage); MIL.MappFreeDefault(MilApplication, MilSystem, MilDisplay, MIL.M_NULL, MIL.M_NULL); }
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 MilGraphicList = MIL.M_NULL; // Graphic list identifier. MIL_ID MilBinImage = MIL.M_NULL; // Binary image buffer identifier. MIL_ID MilBlobResult = MIL.M_NULL; // Blob result buffer identifier. MIL_ID MilBlobFeatureList = MIL.M_NULL; // Feature list identifier. MIL_INT TotalBlobs = 0; // Total number of blobs. MIL_INT BlobsWithHoles = 0; // Number of blobs with holes. MIL_INT BlobsWithRoughHoles = 0; // Number of blobs with rough holes. MIL_INT n = 0; // Counter. MIL_INT SizeX = 0; // Size X of the source buffer MIL_INT SizeY = 0; // Size Y of the source buffer double[] CogX = null; // X coordinate of center of gravity. double[] CogY = null; // Y coordinate of center of gravity. // Allocate defaults. MIL.MappAllocDefault(MIL.M_DEFAULT, ref MilApplication, ref MilSystem, ref MilDisplay, MIL.M_NULL, MIL.M_NULL); // Restore source image into image buffer. MIL.MbufRestore(IMAGE_FILE, MilSystem, ref MilImage); // Allocate a graphic list to hold the subpixel annotations to draw. MIL.MgraAllocList(MilSystem, MIL.M_DEFAULT, ref MilGraphicList); // Associate the graphic list to the display. MIL.MdispControl(MilDisplay, MIL.M_ASSOCIATED_GRAPHIC_LIST_ID, MilGraphicList); // Display the buffer. MIL.MdispSelect(MilDisplay, MilImage); // Allocate a binary image buffer for fast processing. MIL.MbufInquire(MilImage, MIL.M_SIZE_X, ref SizeX); MIL.MbufInquire(MilImage, MIL.M_SIZE_Y, ref SizeY); MIL.MbufAlloc2d(MilSystem, SizeX, SizeY, 1 + MIL.M_UNSIGNED, MIL.M_IMAGE + MIL.M_PROC, ref MilBinImage); // Pause to show the original image. Console.Write("\nBLOB ANALYSIS:\n"); Console.Write("--------------\n\n"); Console.Write("This program determines the number of bolts, nuts and washers\n"); Console.Write("in the image and finds their center of gravity.\n"); Console.Write("Press <Enter> to continue.\n\n"); Console.ReadKey(); // Binarize image. MIL.MimBinarize(MilImage, MilBinImage, MIL.M_FIXED + MIL.M_GREATER_OR_EQUAL, IMAGE_THRESHOLD_VALUE, MIL.M_NULL); // Remove small particles and then remove small holes. MIL.MimOpen(MilBinImage, MilBinImage, MIN_BLOB_RADIUS, MIL.M_BINARY); MIL.MimClose(MilBinImage, MilBinImage, MIN_BLOB_RADIUS, MIL.M_BINARY); // Allocate a feature list. MIL.MblobAllocFeatureList(MilSystem, ref MilBlobFeatureList); // Enable the Area and Center Of Gravity feature calculation. MIL.MblobSelectFeature(MilBlobFeatureList, MIL.M_AREA); MIL.MblobSelectFeature(MilBlobFeatureList, MIL.M_CENTER_OF_GRAVITY); // Allocate a blob result buffer. MIL.MblobAllocResult(MilSystem, ref MilBlobResult); // Calculate selected features for each blob. MIL.MblobCalculate(MilBinImage, MIL.M_NULL, MilBlobFeatureList, MilBlobResult); // Exclude blobs whose area is too small. MIL.MblobSelect(MilBlobResult, MIL.M_EXCLUDE, MIL.M_AREA, MIL.M_LESS_OR_EQUAL, MIN_BLOB_AREA, MIL.M_NULL); // Get the total number of selected blobs. MIL.MblobGetNumber(MilBlobResult, ref TotalBlobs); Console.Write("There are {0} objects ", TotalBlobs); // Read and print the blob's center of gravity. CogX = new double[TotalBlobs]; CogY = new double[TotalBlobs]; if (CogX != null && CogY != null) { // Get the results. MIL.MblobGetResult(MilBlobResult, MIL.M_CENTER_OF_GRAVITY_X, CogX); MIL.MblobGetResult(MilBlobResult, MIL.M_CENTER_OF_GRAVITY_Y, CogY); // Print the center of gravity of each blob. Console.Write("and their centers of gravity are:\n"); for (n = 0; n < TotalBlobs; n++) { Console.Write("Blob #{0}: X={1,5:0.0}, Y={2,5:0.0}\n", n, CogX[n], CogY[n]); } } else { Console.Write("\nError: Not enough memory.\n"); } // Draw a cross at the center of gravity of each blob. MIL.MgraColor(MIL.M_DEFAULT, MIL.M_COLOR_RED); MIL.MblobDraw(MIL.M_DEFAULT, MilBlobResult, MilGraphicList, MIL.M_DRAW_CENTER_OF_GRAVITY, MIL.M_INCLUDED_BLOBS, MIL.M_DEFAULT); // Reverse what is considered to be the background so that // holes are seen as being blobs. MIL.MblobControl(MilBlobResult, MIL.M_FOREGROUND_VALUE, MIL.M_ZERO); // Add a feature to distinguish between types of holes.Since area // has already been added to the feature list, and the processing // mode has been changed, all blobs will be re-included and the area // of holes will be calculated automatically. MIL.MblobSelectFeature(MilBlobFeatureList, MIL.M_COMPACTNESS); // Calculate selected features for each blob. MIL.MblobCalculate(MilBinImage, MIL.M_NULL, MilBlobFeatureList, MilBlobResult); // Exclude small holes and large (the area around objects) holes. MIL.MblobSelect(MilBlobResult, MIL.M_EXCLUDE, MIL.M_AREA, MIL.M_OUT_RANGE, MIN_BLOB_AREA, MAX_BLOB_AREA); // Get the number of blobs with holes. MIL.MblobGetNumber(MilBlobResult, ref BlobsWithHoles); // Exclude blobs whose holes are compact (i.e.nuts). MIL.MblobSelect(MilBlobResult, MIL.M_EXCLUDE, MIL.M_COMPACTNESS, MIL.M_LESS_OR_EQUAL, MIN_COMPACTNESS, MIL.M_NULL); // Get the number of blobs with holes that are NOT compact. MIL.MblobGetNumber(MilBlobResult, ref BlobsWithRoughHoles); // Print results. Console.Write("\nIdentified objects:\n"); Console.Write("{0} bolts\n", TotalBlobs - BlobsWithHoles); Console.Write("{0} nuts\n", BlobsWithHoles - BlobsWithRoughHoles); Console.Write("{0} washers\n\n", BlobsWithRoughHoles); Console.Write("Press <Enter> to end.\n\n"); Console.ReadKey(); // Free all allocations. MIL.MgraFree(MilGraphicList); MIL.MblobFree(MilBlobResult); MIL.MblobFree(MilBlobFeatureList); MIL.MbufFree(MilBinImage); MIL.MbufFree(MilImage); MIL.MappFreeDefault(MilApplication, MilSystem, MilDisplay, MIL.M_NULL, MIL.M_NULL); }
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 MilOverlayImage = MIL.M_NULL; // Overlay image buffer identifier. MIL_ID MilSubImage00 = MIL.M_NULL; // Child buffer identifier. MIL_ID MilSubImage01 = MIL.M_NULL; // Child buffer identifier. MIL_ID MilSubImage10 = MIL.M_NULL; // Child buffer identifier. MIL_ID MilSubImage11 = MIL.M_NULL; // Child buffer identifier. MIL_ID MilTransformReal = MIL.M_NULL; // Real part of the transformed image. MIL_ID MilTransformIm = MIL.M_NULL; // Imaginary part of the transformed image. float[] ZeroVal = new float[1]; ZeroVal[0] = 0.0F; // Allocate defaults. MIL.MappAllocDefault(MIL.M_DEFAULT, ref MilApplication, ref MilSystem, ref MilDisplay, MIL.M_NULL, MIL.M_NULL); // Allocate a display buffer and clear it. MIL.MbufAlloc2d(MilSystem, IMAGE_WIDTH * 2, IMAGE_HEIGHT * 2, 8 + MIL.M_UNSIGNED, MIL.M_IMAGE + MIL.M_PROC + MIL.M_DISP, ref MilImage); MIL.MbufClear(MilImage, 0L); // Display the image buffer and prepare for overlay annotations. MIL.MdispSelect(MilDisplay, MilImage); MIL.MdispControl(MilDisplay, MIL.M_OVERLAY, MIL.M_ENABLE); MIL.MdispInquire(MilDisplay, MIL.M_OVERLAY_ID, ref MilOverlayImage); // Allocate child buffers in the 4 quadrants of the display image. MIL.MbufChild2d(MilImage, 0, 0, IMAGE_WIDTH, IMAGE_HEIGHT, ref MilSubImage00); MIL.MbufChild2d(MilImage, IMAGE_WIDTH, 0, IMAGE_WIDTH, IMAGE_HEIGHT, ref MilSubImage01); MIL.MbufChild2d(MilImage, 0, IMAGE_HEIGHT, IMAGE_WIDTH, IMAGE_HEIGHT, ref MilSubImage10); MIL.MbufChild2d(MilImage, IMAGE_WIDTH, IMAGE_HEIGHT, IMAGE_WIDTH, IMAGE_HEIGHT, ref MilSubImage11); // Allocate processing buffers. MIL.MbufAlloc2d(MilSystem, IMAGE_WIDTH, IMAGE_HEIGHT, 32 + MIL.M_FLOAT, MIL.M_IMAGE + MIL.M_PROC, ref MilTransformReal); MIL.MbufAlloc2d(MilSystem, IMAGE_WIDTH, IMAGE_HEIGHT, 32 + MIL.M_FLOAT, MIL.M_IMAGE + MIL.M_PROC, ref MilTransformIm); // Load a noisy image. MIL.MbufLoad(NOISY_IMAGE, MilSubImage00); // Print a message on the screen. Console.Write("\nFFT:\n"); Console.Write("----\n\n"); Console.Write("The frequency spectrum of a noisy image will be computed to remove the periodic noise.\n"); Console.Write("Press <Enter> to continue.\n\n"); Console.ReadKey(); // The image is Fourier transformed to obtain the magnitude of the // spectrum. This result will be used to design the filter. MIL.MimTransform(MilSubImage00, MIL.M_NULL, MilTransformReal, MilTransformIm, MIL.M_FFT, MIL.M_FORWARD + MIL.M_CENTER + MIL.M_MAGNITUDE + MIL.M_LOG_SCALE); MIL.MbufCopy(MilTransformReal, MilSubImage10); // Draw circles in the overlay around the points of interest. MIL.MbufCopy(MilTransformReal, MilSubImage11); MIL.MgraColor(MIL.M_DEFAULT, MIL.M_COLOR_YELLOW); MIL.MgraArc(MIL.M_DEFAULT, MilOverlayImage, X_NEGATIVE_FREQUENCY_POSITION, Y_FREQUENCY_POSITION + IMAGE_HEIGHT, CIRCLE_WIDTH, CIRCLE_WIDTH, 0, 360); MIL.MgraArc(MIL.M_DEFAULT, MilOverlayImage, X_POSITIVE_FREQUENCY_POSITION, Y_FREQUENCY_POSITION + IMAGE_HEIGHT, CIRCLE_WIDTH, CIRCLE_WIDTH, 0, 360); MIL.MgraArc(MIL.M_DEFAULT, MilOverlayImage, X_NEGATIVE_FREQUENCY_POSITION + IMAGE_WIDTH, Y_FREQUENCY_POSITION + IMAGE_HEIGHT, CIRCLE_WIDTH, CIRCLE_WIDTH, 0, 360); MIL.MgraArc(MIL.M_DEFAULT, MilOverlayImage, X_POSITIVE_FREQUENCY_POSITION + IMAGE_WIDTH, Y_FREQUENCY_POSITION + IMAGE_HEIGHT, CIRCLE_WIDTH, CIRCLE_WIDTH, 0, 360); // Put zero in the spectrum where the noise is located. MIL.MbufPut2d(MilSubImage11, X_NEGATIVE_FREQUENCY_POSITION, Y_FREQUENCY_POSITION, 1, 1, ZeroVal); MIL.MbufPut2d(MilSubImage11, X_POSITIVE_FREQUENCY_POSITION, Y_FREQUENCY_POSITION, 1, 1, ZeroVal); // Compute the Fast Fourier Transform of the image. MIL.MimTransform(MilSubImage00, MIL.M_NULL, MilTransformReal, MilTransformIm, MIL.M_FFT, MIL.M_FORWARD + MIL.M_CENTER); // Filter the image in the frequency domain. MIL.MbufPut2d(MilTransformReal, X_NEGATIVE_FREQUENCY_POSITION, Y_FREQUENCY_POSITION, 1, 1, ZeroVal); MIL.MbufPut2d(MilTransformReal, X_POSITIVE_FREQUENCY_POSITION, Y_FREQUENCY_POSITION, 1, 1, ZeroVal); MIL.MbufPut2d(MilTransformIm, X_NEGATIVE_FREQUENCY_POSITION, Y_FREQUENCY_POSITION, 1, 1, ZeroVal); MIL.MbufPut2d(MilTransformIm, X_POSITIVE_FREQUENCY_POSITION, Y_FREQUENCY_POSITION, 1, 1, ZeroVal); // Recover the image in the spatial domain. MIL.MimTransform(MilTransformReal, MilTransformIm, MilSubImage01, MIL.M_NULL, MIL.M_FFT, MIL.M_REVERSE + MIL.M_CENTER + MIL.M_SATURATION); // Print a message. Console.Write("The frequency components of the noise are located in the center of the circles.\n"); Console.Write("The noise was removed by setting these frequency components to zero.\n"); Console.Write("Press <Enter> to end.\n\n"); Console.ReadKey(); // Free buffers. MIL.MbufFree(MilSubImage00); MIL.MbufFree(MilSubImage01); MIL.MbufFree(MilSubImage10); MIL.MbufFree(MilSubImage11); MIL.MbufFree(MilImage); MIL.MbufFree(MilTransformReal); MIL.MbufFree(MilTransformIm); // Free defaults. MIL.MappFreeDefault(MilApplication, MilSystem, MilDisplay, MIL.M_NULL, MIL.M_NULL); }
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 MilImage = MIL.M_NULL; // Image buffer identifier. MIL_ID MilPosYImage = MIL.M_NULL; // Image buffer identifier. MIL_ID MilValImage = MIL.M_NULL; // Image buffer identifier. MIL_ID MilExtreme = MIL.M_NULL; // Result buffer identifier. double FrameRate = 0.0; int n = 0; double PreviousTime = 0.0; double StartTime = 0.0; double EndTime = 0.0; double TotalProcessTime = 0.0; double WaitTime = 0.0; MIL_INT SizeX = 0; MIL_INT SizeY = 0; MIL_INT NumberOfImages = 0; MIL_INT[] ExtremePosY = new MIL_INT[2]; ExtremePosY[0] = 0; ExtremePosY[1] = 0; // Allocate defaults. MIL.MappAllocDefault(MIL.M_DEFAULT, ref MilApplication, ref MilSystem, ref MilDisplay, MIL.M_NULL, MIL.M_NULL); // Inquire characteristics of the input sequence. MIL.MbufDiskInquire(SEQUENCE_FILE, MIL.M_SIZE_X, ref SizeX); MIL.MbufDiskInquire(SEQUENCE_FILE, MIL.M_SIZE_Y, ref SizeY); MIL.MbufDiskInquire(SEQUENCE_FILE, MIL.M_NUMBER_OF_IMAGES, ref NumberOfImages); MIL.MbufDiskInquire(SEQUENCE_FILE, MIL.M_FRAME_RATE, ref FrameRate); // Allocate buffers to hold images. MIL.MbufAlloc2d(MilSystem, SizeX, SizeY, 8 + MIL.M_UNSIGNED, MIL.M_IMAGE + MIL.M_PROC, ref MilImage); MIL.MbufAlloc2d(MilSystem, SizeX, SizeY, 8 + MIL.M_UNSIGNED, MIL.M_IMAGE + MIL.M_DISP, ref MilDisplayImage); MIL.MbufAlloc2d(MilSystem, SizeX, NumberOfImages, 16 + MIL.M_UNSIGNED, MIL.M_IMAGE + MIL.M_PROC, ref MilPosYImage); MIL.MbufAlloc2d(MilSystem, SizeX, NumberOfImages, 8 + MIL.M_UNSIGNED, MIL.M_IMAGE + MIL.M_PROC, ref MilValImage); // Select display. MIL.MdispSelect(MilDisplay, MilDisplayImage); // Print a message. Console.Write("\nEXTRACTING 3D IMAGE FROM A LASER LINE:\n"); Console.Write("--------------------------------------\n\n"); Console.Write("The position of a laser line is being extracted from an image\n"); Console.Write("to generate a depth image.\n\n"); // Open the sequence file for reading. 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); // The function must be called once before the timing loop for more accurate // time (dll load, ...). MIL.MimLocatePeak1d(MilImage, MilPosYImage, MilValImage, 0, MAX_LINE_WIDTH, MIN_INTENSITY, MIL.M_1D_COLUMNS + MIL.M_FIXED_POINT + NB_FIXED_POINT, MIL.M_DEFAULT); // Read and process all images in the input sequence. MIL.MappTimer(MIL.M_DEFAULT, MIL.M_TIMER_READ + MIL.M_SYNCHRONOUS, ref PreviousTime); TotalProcessTime = 0.0; for (n = 0; n < NumberOfImages; n++) { // Read image from sequence. MIL.MbufImportSequence(SEQUENCE_FILE, MIL.M_DEFAULT, MIL.M_LOAD, MIL.M_NULL, ref MilImage, MIL.M_DEFAULT, 1, MIL.M_READ); // Display the image. MIL.MbufCopy(MilImage, MilDisplayImage); // Locate the peak in each column of the image. MIL.MappTimer(MIL.M_DEFAULT, MIL.M_TIMER_READ + MIL.M_SYNCHRONOUS, ref StartTime); MIL.MimLocatePeak1d(MilImage, MilPosYImage, MilValImage, n, MAX_LINE_WIDTH, MIN_INTENSITY, MIL.M_1D_COLUMNS + MIL.M_FIXED_POINT + NB_FIXED_POINT, MIL.M_DEFAULT); MIL.MappTimer(MIL.M_DEFAULT, MIL.M_TIMER_READ + MIL.M_SYNCHRONOUS, ref EndTime); TotalProcessTime += EndTime - StartTime; // Wait to have a proper frame rate. WaitTime = (1.0 / FrameRate) - (EndTime - PreviousTime); if (WaitTime > 0) { MIL.MappTimer(MIL.M_DEFAULT, MIL.M_TIMER_WAIT, ref WaitTime); } MIL.MappTimer(MIL.M_DEFAULT, MIL.M_TIMER_READ + MIL.M_SYNCHRONOUS, ref PreviousTime); } // Close 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_CLOSE); Console.Write("{0} images processed in {1,7:0.00} s ({2,7:0.00} ms/image).\n", NumberOfImages, TotalProcessTime, TotalProcessTime / (double)NumberOfImages * 1000.0); // Pause to show the result. Console.Write("Press <Enter> to continue.\n\n"); Console.ReadKey(); Console.Write("The reconstructed images are being displayed.\n"); // Draw extracted peak position in each column of each image. for (n = 0; n < NumberOfImages; n++) { MIL.MbufClear(MilImage, 0); MIL.MimDraw(MIL.M_DEFAULT, MilPosYImage, MilValImage, MilImage, MIL.M_DRAW_PEAKS + MIL.M_1D_COLUMNS + MIL.M_LINES, (double)n, 1, MIL.M_FIXED_POINT + NB_FIXED_POINT); // Display the result image. MIL.MbufCopy(MilImage, MilDisplayImage); } // Pause to show the result. Console.Write("Press <Enter> to continue.\n\n"); Console.ReadKey(); // Try to allocate D3D display IntPtr DispHandle; DispHandle = MdepthD3DAlloc(MilPosYImage, MilValImage, D3D_DISPLAY_SIZE_X, D3D_DISPLAY_SIZE_Y, D3D_MESH_SCALING_X, D3D_MESH_SCALING_Y, D3D_MESH_SCALING_Z, MIL.M_DEFAULT, MIL.M_DEFAULT, MIL.M_DEFAULT, IntPtr.Zero); if (DispHandle != IntPtr.Zero) { Console.Write("The depth buffer is displayed using D3D.\n"); // Hide Mil Display MIL.MdispControl(MilDisplay, MIL.M_WINDOW_SHOW, MIL.M_DISABLE); MdispD3DShow(DispHandle); MdispD3DPrintHelp(DispHandle); // Pause to show the result. Console.Write("Press <Enter> to end.\n"); Console.ReadKey(); MdispD3DHide(DispHandle); MdispD3DFree(DispHandle); } else { Console.Write("The depth buffer is displayed using MIL.\n"); // Find the reMIL.Mapping for result buffers. MIL.MimAllocResult(MilSystem, MIL.M_DEFAULT, MIL.M_STAT_LIST, ref MilExtreme); MIL.MimStat(MilPosYImage, MilExtreme, MIL.M_MIN + MIL.M_MAX, MIL.M_NOT_EQUAL, 0xFFFF, MIL.M_NULL); MIL.MimGetResult(MilExtreme, MIL.M_MIN + MIL.M_TYPE_MIL_INT, ref ExtremePosY[0]); MIL.MimGetResult(MilExtreme, MIL.M_MAX + MIL.M_TYPE_MIL_INT, ref ExtremePosY[1]); MIL.MimFree(MilExtreme); // Free the display and reallocate a new one of the proper dimension for results. MIL.MbufFree(MilDisplayImage); MIL.MbufAlloc2d(MilSystem, (MIL_INT)((double)SizeX * (D3D_MESH_SCALING_X > 0 ? D3D_MESH_SCALING_X : -D3D_MESH_SCALING_X)), (MIL_INT)((double)NumberOfImages * D3D_MESH_SCALING_Y), 8 + MIL.M_UNSIGNED, MIL.M_IMAGE + MIL.M_PROC + MIL.M_DISP, ref MilDisplayImage); MIL.MdispSelect(MilDisplay, MilDisplayImage); // Display the height buffer. MIL.MimClip(MilPosYImage, MilPosYImage, MIL.M_GREATER, (double)ExtremePosY[1], MIL.M_NULL, (double)ExtremePosY[1], MIL.M_NULL); MIL.MimArith(MilPosYImage, (double)ExtremePosY[0], MilPosYImage, MIL.M_SUB_CONST); MIL.MimArith(MilPosYImage, ((ExtremePosY[1] - ExtremePosY[0]) / 255.0) + 1, MilPosYImage, MIL.M_DIV_CONST); MIL.MimResize(MilPosYImage, MilDisplayImage, MIL.M_FILL_DESTINATION, MIL.M_FILL_DESTINATION, MIL.M_BILINEAR); // Pause to show the result. Console.Write("Press <Enter> to end.\n"); Console.ReadKey(); } // Free all allocations. MIL.MbufFree(MilImage); MIL.MbufFree(MilDisplayImage); MIL.MbufFree(MilPosYImage); MIL.MbufFree(MilValImage); MIL.MappFreeDefault(MilApplication, MilSystem, MilDisplay, MIL.M_NULL, MIL.M_NULL); }
// Main function. static void Main(string[] args) { MIL_ID MilApplication = MIL.M_NULL; MIL_ID MilSystem = MIL.M_NULL; MIL_ID MilDigitizer = MIL.M_NULL; MIL_ID MilDisplay = MIL.M_NULL; MIL_ID[] MilImage = new MIL_ID[2]; MIL_ID MilImageDisp = MIL.M_NULL; MIL_ID Default = MIL.M_DEFAULT; int NbProc = 0; int n = 0; double Time = 0.0; StringBuilder Text = new StringBuilder("0", STRING_LENGTH_MAX); UserDataObject userObject = new UserDataObject(); // Allocate defaults. MIL.MappAllocDefault(MIL.M_DEFAULT, ref MilApplication, ref MilSystem, ref MilDisplay, ref MilDigitizer, ref MilImageDisp); // Allocate 2 grab buffers. for (n = 0; n < 2; n++) { MIL.MbufAlloc2d(MilSystem, 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 MilImage[n]); } // Hook a function to the start of each frame to print the current frame index. userObject.NbGrabStart = 0; GCHandle userObjectHandle = GCHandle.Alloc(userObject); MIL_DIG_HOOK_FUNCTION_PTR grabStartDelegate = new MIL_DIG_HOOK_FUNCTION_PTR(GrabStart); MIL.MdigHookFunction(MilDigitizer, MIL.M_GRAB_START, grabStartDelegate, GCHandle.ToIntPtr(userObjectHandle)); // Print a message. Console.WriteLine(); Console.WriteLine("DOUBLE BUFFERING ACQUISITION AND PROCESSING:"); Console.WriteLine("--------------------------------------------"); Console.WriteLine(); Console.WriteLine("Press <Enter> to stop."); Console.WriteLine(); // Put the digitizer in asynchronous mode to be able to process while grabbing. MIL.MdigControl(MilDigitizer, MIL.M_GRAB_MODE, MIL.M_ASYNCHRONOUS); // Grab the first buffer. MIL.MdigGrab(MilDigitizer, MilImage[0]); // Process one buffer while grabbing the other. n = 0; do { // Grab the other buffer while processing the previous one. MIL.MdigGrab(MilDigitizer, MilImage[1 - n]); // Synchronize and start the timer. if (NbProc == 0) { MIL.MappTimer(MIL.M_DEFAULT, MIL.M_TIMER_RESET + MIL.M_SYNCHRONOUS, MIL.M_NULL); } // Write the frame counter. MIL.MgraText(Default, MilImage[n], 32, 32, string.Format("{0}", NbProc + 1)); // Process the first buffer already grabbed. MIL.MimArith(MilImage[n], MIL.M_NULL, MilImageDisp, MIL.M_NOT); // Count processed buffers. NbProc++; // Toggle grab buffers. n = 1 - n; } while (!Console.KeyAvailable); // Wait until the end of the last grab and stop the timer. MIL.MdigGrabWait(MilDigitizer, MIL.M_GRAB_END); MIL.MappTimer(MIL.M_DEFAULT, MIL.M_TIMER_READ + MIL.M_SYNCHRONOUS, ref Time); Console.ReadKey(); // Print statistics. Console.WriteLine("{0} frames grabbed, at a frame rate of {1:0.00} frames/sec ({2:0.00} ms/frame).", NbProc, NbProc / Time, 1000.0 * Time / NbProc); Console.WriteLine("Press <Enter> to end."); Console.WriteLine(); Console.ReadKey(); // Unhook the function at the start of each frame. MIL.MdigHookFunction(MilDigitizer, MIL.M_GRAB_START + MIL.M_UNHOOK, grabStartDelegate, GCHandle.ToIntPtr(userObjectHandle)); // Free GCHandle to allow the garbage collector to reclaim the object. userObjectHandle.Free(); // Free allocations. for (n = 0; n < 2; n++) { MIL.MbufFree(MilImage[n]); } MIL.MappFreeDefault(MilApplication, MilSystem, MilDisplay, MilDigitizer, MilImageDisp); }
static void StripeMarker(MIL_ID MilSystem, MIL_ID MilDisplay, MIL_ID MilImage, string MODEL_FILE, string IMAGE_FILE) { MIL_ID MilSourceImage = MIL.M_NULL; MIL_ID MilGraphicList = MIL.M_NULL; MIL_ID MilModContext = MIL.M_NULL; MIL_ID MilModResult = MIL.M_NULL; MIL_ID MilFixturingOffset = MIL.M_NULL; MIL_ID StripeMarker = MIL.M_NULL; MIL_INT ImageSizeX = 0; MIL_INT ImageSizeY = 0; double ModelPosX = 0.0; double ModelPosY = 0.0; double ModelFindControl = 0.0; int StripePosX = 812; int StripePosY = 210; int StripeWidth = 80; int StripeHeight = 16; int StripeAngle = 90; int POLARITY_LEFT = MIL.M_ANY; int POLARITY_RIGHT = MIL.M_OPPOSITE; MIL_INT FindStripeControl = 0; double ResultWidth = 0.0; MIL.MbufRestore(IMAGE_FILE, MilSystem, ref MilSourceImage); MIL.MbufInquire(MilSourceImage, MIL.M_SIZE_X, ref ImageSizeX); MIL.MbufInquire(MilSourceImage, MIL.M_SIZE_Y, ref ImageSizeY); MIL.MbufAlloc2d(MilSystem, ImageSizeX, ImageSizeY, 8 + MIL.M_UNSIGNED, MIL.M_IMAGE + MIL.M_PROC + MIL.M_DISP, ref MilImage); MIL.MimConvert(MilSourceImage, MilImage, MIL.M_RGB_TO_L); MIL.MgraAllocList(MilSystem, MIL.M_DEFAULT, ref MilGraphicList); MIL.MdispSelect(MilDisplay, MilImage); MIL.MdispControl(MilDisplay, MIL.M_ASSOCIATED_GRAPHIC_LIST_ID, MilGraphicList); MIL.MmeasAllocMarker(MilSystem, MIL.M_STRIPE, MIL.M_DEFAULT, ref StripeMarker); //MIL.MmeasAllocMarker(MilSystem, MIL.M_EDGE, MIL.M_DEFAULT, ref StripeMarker); MIL.MmeasSetMarker(StripeMarker, MIL.M_SEARCH_REGION_INPUT_UNITS, MIL.M_WORLD, MIL.M_NULL); MIL.MmodAlloc(MilSystem, MIL.M_GEOMETRIC, MIL.M_DEFAULT, ref MilModContext); MIL.MmodRestore(MODEL_FILE, MilSystem, MIL.M_DEFAULT, ref MilModContext); MIL.MmodAllocResult(MilSystem, MIL.M_DEFAULT, ref MilModResult); MIL.MmodControl(MilModContext, MIL.M_DEFAULT, MIL.M_NUMBER, MIL.M_ALL); MIL.MmodControl(MilModContext, MIL.M_CONTEXT, MIL.M_SPEED, MIL.M_VERY_HIGH); MIL.MmodPreprocess(MilModContext, MIL.M_DEFAULT); MIL.McalAlloc(MilSystem, MIL.M_FIXTURING_OFFSET, MIL.M_DEFAULT, ref MilFixturingOffset); MIL.McalFixture(MIL.M_NULL, MilFixturingOffset, MIL.M_LEARN_OFFSET, MIL.M_MODEL_MOD, MilModContext, 0, MIL.M_DEFAULT, MIL.M_DEFAULT, MIL.M_DEFAULT); MIL.MmodFind(MilModContext, MilImage, MilModResult); MIL.MmodGetResult(MilModResult, MIL.M_GENERAL, MIL.M_NUMBER, ref ModelFindControl); if (ModelFindControl > 0) { MIL.MgraColor(MIL.M_DEFAULT, MIL.M_COLOR_GREEN); MIL.MmodDraw(MIL.M_DEFAULT, MilModResult, MilGraphicList, MIL.M_DRAW_POSITION, MIL.M_DEFAULT, MIL.M_DEFAULT); MIL.MmodGetResult(MilModResult, 0, MIL.M_POSITION_X + MIL.M_TYPE_MIL_DOUBLE, ref ModelPosX); MIL.MmodGetResult(MilModResult, 0, MIL.M_POSITION_Y + MIL.M_TYPE_MIL_DOUBLE, ref ModelPosY); MIL.MgraText(MIL.M_DEFAULT, MilGraphicList, ModelPosX - 20, ModelPosY, "Occurence Found"); MIL.McalFixture(MilImage, MilFixturingOffset, MIL.M_MOVE_RELATIVE, MIL.M_RESULT_MOD, MilModResult, 0, MIL.M_DEFAULT, MIL.M_DEFAULT, MIL.M_DEFAULT); MIL.MmeasSetMarker(StripeMarker, MIL.M_BOX_ORIGIN, StripePosX, StripePosY); MIL.MmeasSetMarker(StripeMarker, MIL.M_POLARITY, POLARITY_LEFT, POLARITY_RIGHT); MIL.MmeasSetMarker(StripeMarker, MIL.M_SEARCH_REGION_CLIPPING, MIL.M_ENABLE, MIL.M_NULL); MIL.MmeasSetMarker(StripeMarker, MIL.M_BOX_SIZE, StripeWidth, StripeHeight); MIL.MmeasSetMarker(StripeMarker, MIL.M_BOX_ANGLE, StripeAngle, MIL.M_NULL); MIL.MgraColor(MIL.M_DEFAULT, MIL.M_COLOR_BLUE); MIL.MgraControl(MIL.M_DEFAULT, MIL.M_INPUT_UNITS, MIL.M_WORLD); MIL.MmeasDraw(MIL.M_DEFAULT, StripeMarker, MilGraphicList, MIL.M_DRAW_SEARCH_REGION, MIL.M_DEFAULT, MIL.M_MARKER); MIL.MgraControl(MIL.M_DEFAULT, MIL.M_INPUT_UNITS, MIL.M_PIXEL); MIL.MmeasFindMarker(MIL.M_DEFAULT, MilImage, StripeMarker, MIL.M_POSITION + MIL.M_STRIPE_WIDTH); //MIL.MmeasFindMarker(MIL.M_DEFAULT, MilImage, StripeMarker, MIL.M_POSITION + MIL.M_LENGTH); MIL.MmeasGetResult(StripeMarker, MIL.M_NUMBER + MIL.M_TYPE_MIL_INT, ref FindStripeControl, MIL.M_NULL); if (FindStripeControl == 1) { //MIL.MmeasGetResult(StripeMarker, MIL.M_LENGTH, ref ResultWidth, MIL.M_NULL); MIL.MmeasGetResult(StripeMarker, MIL.M_STRIPE_WIDTH, ref ResultWidth, MIL.M_NULL); ResultWidth = Math.Round(ResultWidth, 4); Console.Write("Width: {0} pixels.\n", ResultWidth); MIL.MgraColor(MIL.M_DEFAULT, MIL.M_COLOR_GREEN); MIL.MgraText(MIL.M_DEFAULT, MilGraphicList, StripePosX + 40, StripePosY - 40, ResultWidth.ToString() + " px"); MIL.MgraColor(MIL.M_DEFAULT, MIL.M_COLOR_RED); //MIL.MmeasDraw(MIL.M_DEFAULT, StripeMarker, MilGraphicList, MIL.M_DRAW_EDGES, MIL.M_DEFAULT, MIL.M_RESULT); MIL.MmeasDraw(MIL.M_DEFAULT, StripeMarker, MilGraphicList, MIL.M_DRAW_WIDTH, MIL.M_DEFAULT, MIL.M_RESULT); } Console.Write("Press <Enter> to continue.\n"); Console.ReadKey(); } else { Console.Write("Occurence Not Found"); } MIL.MgraFree(MilGraphicList); MIL.MmeasFree(StripeMarker); MIL.MmodFree(MilModContext); MIL.MmodFree(MilModResult); MIL.McalFree(MilFixturingOffset); MIL.MbufFree(MilSourceImage); }