Question

Here there,

I'm currently working on a C# project and I need to create a snippet using SimpleITK libraries, in which my image matrix ArrayIn will be compared to a number DoubleVar.

Then, if, for each element, the value of ArrayIn is greater than the DoubleVar one, the respective element of my output image ArrayOut will be 1. If not, that element will be 0. The matrix ArrayOut is a binary Image , with ones and zeros. The size of AArrayOut will be the same as the input's one. I need to use the function Getbufferasint16() but I can't do so.

The following code is part of intents , but with no result

uint8_t *buffer = (my image) ->GetBufferAsUInt16();
buffer[c + numComponents*(x+ xSize* (y*+ySize*z))];
Was it helpful?

Solution

Please find this new example on how to access a buffer from SimpleITK in C#: http://www.itk.org/SimpleITKDoxygen/html/ImageGetBuffer_8cs-example.html

You need to you need to use the Marshal class to safely interface the unmanaged code with the C# data, or use an unsafe block:

  input = SimpleITK.Cast(input, PixelId.sitkFloat32);
  // calculate the nubmer of pixels
  VectorUInt32 size = input.GetSize();
  int len = 1;
  for (int dim = 0; dim < input.GetDimension(); dim++) {
    len *= (int)size[dim];
  }
  IntPtr buffer = input.GetBufferAsFloat();
  // There are two ways to access the buffer:
  // (1) Access the underlying buffer as a pointer in an "unsafe" block
  // (note that in C# "unsafe" simply means that the compiler can not
  // perform full type checking), and requires the -unsafe compiler flag
  unsafe {
    float* bufferPtr = (float*)buffer.ToPointer();
    // Now the byte pointer can be accessed as per Brad's email
    // (of course this example is only a 2d single channel image):
    // This is a 1-D array but can be access as a 3-D. Given an
    // image of size [xS,yS,zS], you can access the image at
    // index [x,y,z] as you wish by image[x+y*xS+z*xS*yS],
    // so x is the fastest axis and z is the slowest.
    for (int j = 0; j < size[1]; j++) {
      for (int i = 0; i < size[0]; i++) {
        float pixel = bufferPtr[i + j*size[1]];
        // Do something with pixel here
      }
    }
  }
  // (2) Copy the buffer to a "safe" array (i.e. a fully typed array)
  // (note that this means memory is duplicated)
  float[] bufferAsArray = new float[len]; // Allocates new memory the size of input
  Marshal.Copy(buffer, bufferAsArray, 0, len);
  double total = 0.0;
  for (int j = 0; j < size[1]; j++) {
    for (int i = 0; i < size[0]; i++) {
      float pixel = bufferAsArray[i + j*size[1]];
      total += pixel;
    }
  }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top