CellIdFromGridCoordinates

VTKExamples/Cxx/ImageData/CellIdFromGridCoordinates

Code

CellIdFromGridCoordinates.cxx

#include <vtkSmartPointer.h>
#include <vtkImageData.h>
#include <vtkStructuredData.h>

int main(int, char *[])
{

  vtkSmartPointer<vtkImageData> grid = vtkSmartPointer<vtkImageData>::New();
  grid->SetOrigin(0, 0, 0);

  unsigned int numVoxelsPerDimension = 2; //the number of voxels in each dimension
  grid->SetSpacing(1, 1, 1);

  int extent[6];
  extent[0] = 0;
  extent[1] = numVoxelsPerDimension;
  extent[2] = 0;
  extent[3] = numVoxelsPerDimension;
  extent[4] = 0;
  extent[5] = numVoxelsPerDimension;
  grid->SetExtent(extent);
  grid->AllocateScalars(VTK_INT,1);

  for(unsigned int i = 0; i < numVoxelsPerDimension; ++i)
  {
    for(unsigned int j = 0; j < numVoxelsPerDimension; ++j)
    {
      for(unsigned int k = 0; k < numVoxelsPerDimension; ++k)
      {
        int pos[3];
        pos[0] = i;
        pos[1] = j;
        pos[2] = k;

        vtkIdType id = vtkStructuredData::ComputeCellIdForExtent(extent, pos);
        std::cout << "Cell " << i << " " << j << " " << k << " has id : " << id << std::endl;
      }
    }
  }

  return EXIT_SUCCESS;
}

CMakeLists.txt

cmake_minimum_required(VERSION 3.3 FATAL_ERROR)

project(CellIdFromGridCoordinates)

find_package(VTK COMPONENTS 
  vtkCommonCore
  vtkCommonDataModel QUIET)
if (NOT VTK_FOUND)
  message("Skipping CellIdFromGridCoordinates: ${VTK_NOT_FOUND_MESSAGE}")
  return ()
endif()
message (STATUS "VTK_VERSION: ${VTK_VERSION}")
if (VTK_VERSION VERSION_LESS "8.90.0")
  # old system
  include(${VTK_USE_FILE})
  add_executable(CellIdFromGridCoordinates MACOSX_BUNDLE CellIdFromGridCoordinates.cxx )
  target_link_libraries(CellIdFromGridCoordinates PRIVATE ${VTK_LIBRARIES})
else ()
  # include all components
  add_executable(CellIdFromGridCoordinates MACOSX_BUNDLE CellIdFromGridCoordinates.cxx )
  target_link_libraries(CellIdFromGridCoordinates PRIVATE ${VTK_LIBRARIES})
  # vtk_module_autoinit is needed
  vtk_module_autoinit(
    TARGETS CellIdFromGridCoordinates
    MODULES ${VTK_LIBRARIES}
    )
endif () 

Download and Build CellIdFromGridCoordinates

Click here to download CellIdFromGridCoordinates and its CMakeLists.txt file. Once the tarball CellIdFromGridCoordinates.tar has been downloaded and extracted,

cd CellIdFromGridCoordinates/build 

If VTK is installed:

cmake ..

If VTK is not installed but compiled on your system, you will need to specify the path to your VTK build:

cmake -DVTK_DIR:PATH=/home/me/vtk_build ..

Build the project:

make

and run it:

./CellIdFromGridCoordinates

WINDOWS USERS

Be sure to add the VTK bin directory to your path. This will resolve the VTK dll's at run time.