Skip to Main Content
Centro de soporte de Cognex
LogoLogo

How To Access Pixel Data With VisionPro Scripts

22/04/2025

Details

In some cases, your application may need direct access to the raw pixel data of an image. Taking an 8-bit grayscale image as an example, VisionPro provides the CogImage8Grey and ICogImage8PixelMemory interfaces for this purpose.

ICogImage8PixelMemory is an interface associated with the CogImage8Grey class. This interface provides a single method, Get8GreyPixelMemory, that returns an ICogImage8PixelMemory object that allows you to access all or part of an image's pixel data. This object performs the appropriate marshaling, if necessary, so that the pixel data is always in local memory.

The ICogImage8PixelMemory property Scan0 returns a pointer to the raw pixel data. The ICogImage8PixelMemory object is not intended for long term use. You must call Dispose to release any resources that it uses. (Calling Dispose releases only resources used by ICogImage8PixelMemory, not the image data itself.)

Although you can use the value that Scan0 returns as you would any other pointer, you should not make any assumptions about how the memory is organized. In particular, keep in mind the following points:

  • Do not attempt to access memory outside of the region you requested
  • Assume that pixel data is written back to the image itself only after you call Dispose.
     

The following is an example code for obtaining 8-bit grayscale pixel data:

   CogImage8Grey greyImage = Inputs.InputImage as CogImage8Grey;
   ICogImage8PixelMemory src8PixelMemory = greyImage.Get8GreyPixelMemory(CogImageDataModeConstants.Read, 0, 0, width, height);
   int stride = src8PixelMemory.Stride;
   try
   {
     unsafe
     {
       byte* pSrc = (byte*) src8PixelMemory.Scan0;
       for(int j = 0;j < height;j++)
       {
         for(int i = 0;i < width;i++)
         {
           <get pixel value> = pSrc[i];
         }
         pSrc += stride;
       }
     }
   }
   catch
   {
     throw new Exception("Out of the image!");
   }
   finally
   {
     src8PixelMemory.Dispose();
   }

Recursos relacionados

Loading component...