IOLink 1.11.0
Loading...
Searching...
No Matches
grayscaleSphere.cpp

This code demonstrates how to generate a grayscale sphere in a 3D volume.

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.

#include <iostream>
#include <vector>
#include <cmath>
#include <iolink/view/ImageViewFactory.h>
using namespace iolink;
std::shared_ptr<ImageView>
grayscaleSphere(const VectorXu64& shape)
{
// first we can check if given shape has exactly 3 dimensions
if (shape.size() != 3)
{
throw std::runtime_error("grayscaleSphere: shape must have 3 dimensions");
}
// To create a grayscale ImageView, the datatype of the image must only have 1 components
const DataType dt = DataTypeId::UINT8;
// create an image view in CPU memory
std::shared_ptr<ImageView> image = ImageViewFactory::allocate(shape, dt);
// indicate the created image is a VOLUME with Grayscale color interpretation
image->setAxesInterpretation(ImageTypeId::VOLUME);
image->setImageInterpretation(ImageInterpretation::GRAYSCALE);
// determine volume center
VectorXu64 center = VectorXu64(shape) / 2;
// determine the radius of the volume
// we use the smallest axis length
size_t radius = std::min(center[0], center[1]);
radius = std::min(radius, center[2]);
uint8_t filledVoxel = 255;
uint8_t emptyVoxel = 0;
VectorXi64 center_i = VectorXi64(center);
// iterate over all voxels
for (size_t z = 0; z < shape[2]; ++z)
{
for (size_t y = 0; y < shape[1]; ++y)
{
for (size_t x = 0; x < shape[0]; ++x)
{
// position of the voxel
VectorXi64 voxelPosition{static_cast<int64_t>(x), static_cast<int64_t>(y), static_cast<int64_t>(z)};
// calculate distance to center
VectorXi64 delta = voxelPosition - center_i;
double distance = delta.length();
// set voxel value
if (distance <= static_cast<double>(radius))
{
image->write({x, y, z}, &filledVoxel);
}
else
{
image->write({x, y, z}, &emptyVoxel);
}
}
}
}
return image;
}
int
main(int argc, char** argv)
{
std::shared_ptr<ImageView> image = grayscaleSphere({100, 100, 100});
std::cout << "Created volume: " << image->toString() << std::endl;
return EXIT_SUCCESS;
}