IOLink C# 1.11.0
Loading...
Searching...
No Matches
GrayscaleSphere.cs

This code demonstrates how to generate a grayscale sphere in a 3D volume. All voxels inside the sphere have value = 255, and others are 0.

using IOLink;
using System;
using System.Numerics;
using System.Runtime.Intrinsics;
namespace Examples
{
public class GrayscaleSphere
{
private static ImageView Generate(VectorXu64 shape)
{
// first we can check if given shape has exactly 3
// dimensions
if (shape.Size() != 3)
{
throw new ApplicationException("Shape must have 3 dimensions");
}
// To create a grayscale ImageView, the datatype of
// the image must only have 1 components
DataType dt = DataTypeId.UINT8;
// create an image view in CPU memory
ImageView image = ImageViewFactory.Allocate(shape, dt);
// indicate the created image is a VOLUME with
// Grayscale color interpretation
image.AxesInterpretation = ImageTypeId.VOLUME;
image.ImageInterpretation = ImageInterpretation.GRAYSCALE;
// determine volume center
VectorXu64 center = shape / 2;
// determine the radius of the volume
// we use the smallest axis length
ulong radius = Math.Min(center[0], center[1]);
radius = Math.Min(radius, center[2]);
Byte[] filledVoxel = new Byte[] { 255 };
Byte[] emptyVoxel = new Byte[] { 0 };
VectorXi64 center_i = new VectorXi64((long)center[0], (long)center[1], (long)center[2]);
// iterate over all voxels in the image
for (ulong z = 0; z < shape[2]; z++)
{
for (ulong y = 0; y < shape[1]; y++)
{
for (ulong x = 0; x < shape[0]; x++)
{
// calculate the distance from the center
// of the volume
VectorXi64 voxelPos_i = new VectorXi64((long)x, (long)y, (long)z);
VectorXu64 voxelPos = new VectorXu64(x, y, z);
VectorXi64 distance = voxelPos_i - center_i;
// calculate the distance from the center
// of the volume
double distanceFromCenter = distance.Length();
// if the distance is less than the
// radius, the voxel is inside the sphere
if (distanceFromCenter < (double)radius)
{
image.Write(voxelPos, filledVoxel);
}
else
{
image.Write(voxelPos, emptyVoxel);
}
}
}
}
return image;
}
public static void Main(string[] args)
{
var image = Generate(new VectorXu64(100, 100, 100));
Console.WriteLine("Generated image: " + image.ToString());
Console.WriteLine("SUCCESS");
}
}
}
Definition CreateDataFrame.cs:6