Skip to content

NegativeIndices

vtk-examples/Cxx/Images/NegativeIndices

Question

If you have a question about this example, please use the VTK Discourse Forum

Code

NegativeIndices.cxx

#include <vtkImageData.h>
#include <vtkNew.h>

int main(int, char*[])
{
  // Create the image data
  vtkNew<vtkImageData> imageData;

  // Specify the size of the image data
  imageData->SetExtent(-5, 5, -5, 5, -5, 5);

  // Fill every entry of the image data with "2.0"
  int* extent = imageData->GetExtent();

  imageData->AllocateScalars(VTK_UNSIGNED_CHAR, 1);

  std::cout << "Extent: "
            << " xmin: " << extent[0] << " xmax: " << extent[1]
            << " ymin: " << extent[2] << " ymax: " << extent[3]
            << " zmin: " << extent[4] << " zmax: " << extent[5] << std::endl;

  for (int z = extent[4]; z < extent[5]; z++)
  {
    for (int y = extent[2]; y < extent[3]; y++)
    {
      for (int x = extent[0]; x < extent[1]; x++)
      {
        imageData->SetScalarComponentFromDouble(x, y, z, 0, 2.0);
      }
    }
  }

  // Retrieve the entries from the image data and print them to the screen
  for (int z = extent[4]; z < extent[5]; z++)
  {
    for (int y = extent[2]; y < extent[3]; y++)
    {
      for (int x = extent[0]; x < extent[1]; x++)
      {
        // Zero is the component, add another loop if you have more
        // than one component
        double v = imageData->GetScalarComponentAsDouble(x, y, z, 0);
        // Eo something with v
        std::cout << v << " ";
      }
      std::cout << std::endl;
    }
    std::cout << std::endl;
  }

  return EXIT_SUCCESS;
}

CMakeLists.txt

cmake_minimum_required(VERSION 3.3 FATAL_ERROR)

project(NegativeIndices)

find_package(VTK COMPONENTS 
  vtkCommonCore
  vtkCommonDataModel
  QUIET
)

if (NOT VTK_FOUND)
  message("Skipping NegativeIndices: ${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(NegativeIndices MACOSX_BUNDLE NegativeIndices.cxx )
  target_link_libraries(NegativeIndices PRIVATE ${VTK_LIBRARIES})
else ()
  # include all components
  add_executable(NegativeIndices MACOSX_BUNDLE NegativeIndices.cxx )
  target_link_libraries(NegativeIndices PRIVATE ${VTK_LIBRARIES})
  # vtk_module_autoinit is needed
  vtk_module_autoinit(
    TARGETS NegativeIndices
    MODULES ${VTK_LIBRARIES}
    )
endif ()

Download and Build NegativeIndices

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

cd NegativeIndices/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:

./NegativeIndices

WINDOWS USERS

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