Skip to content

ImageValueRange

Repository source: ImageValueRange

Question

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

Code

ImageValueRange.cxx

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

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

  // Specify the size of the image data.
  imageData->SetDimensions(5, 1, 1);
  imageData->AllocateScalars(VTK_DOUBLE, 1);

  const int* dims = imageData->GetDimensions();

  for (int x = 0; x < dims[0]; x++)
  {
    double* pixel = static_cast<double*>(imageData->GetScalarPointer(x, 0, 0));
    pixel[0] = x * 10;
  }

  double valuesRange[2];
  dynamic_cast<vtkDoubleArray*>(
      imageData->GetPointData()->GetArray("ImageScalars"))
      ->GetValueRange(valuesRange);
  std::cout << "valuesRange = " << valuesRange[0] << " " << valuesRange[1]
            << std::endl;

  // Alternatively.
  auto min = imageData->GetScalarRange()[0];
  auto max = imageData->GetScalarRange()[1];
  std::cout << "alternatively:\nvaluesRange = " << min << " " << max
            << std::endl;

  return EXIT_SUCCESS;
}

CMakeLists.txt

cmake_minimum_required(VERSION 3.12 FATAL_ERROR)

project(ImageValueRange)

find_package(VTK COMPONENTS 
  CommonCore
  CommonDataModel
)

if (NOT VTK_FOUND)
  message(FATAL_ERROR "ImageValueRange: Unable to find the VTK build folder.")
endif()

# Prevent a "command line is too long" failure in Windows.
set(CMAKE_NINJA_FORCE_RESPONSE_FILE "ON" CACHE BOOL "Force Ninja to use response files.")
add_executable(ImageValueRange MACOSX_BUNDLE ImageValueRange.cxx )
  target_link_libraries(ImageValueRange PRIVATE ${VTK_LIBRARIES}
)
# vtk_module_autoinit is needed
vtk_module_autoinit(
  TARGETS ImageValueRange
  MODULES ${VTK_LIBRARIES}
)

Download and Build ImageValueRange

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

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

./ImageValueRange

WINDOWS USERS

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