Skip to content

EnhanceEdges

vtk-examples/Cxx/ImageProcessing/EnhanceEdges


Description

High-pass filters can also be used to compress the range of an image. Since low frequencies account for much of the dynamic range of an image but carry little information, a high-pass filter can significantly decrease an image’s scalar range and emphasize hidden details. The Laplacian filter, which is a second derivative operation, is one implementation of a high-pass filter. It eliminates constant and low frequencies leaving only high-frequency edges. The output of the Laplacian can be subtracted from the original image to produce edge enhancement or sharpening of an image.

This example subtracts the Laplacian (middle) from the original image (left) resulting in edge enhancement or a sharpening operation (right).

Other languages

See (Python)

Question

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

Code

EnhanceEdges.cxx

#include <vector>
#include <vtkCamera.h>
#include <vtkDataArray.h>
#include <vtkImageActor.h>
#include <vtkImageCast.h>
#include <vtkImageData.h>
#include <vtkImageLaplacian.h>
#include <vtkImageMapToWindowLevelColors.h>
#include <vtkImageMapper3D.h>
#include <vtkImageMathematics.h>
#include <vtkImageProperty.h>
#include <vtkImageReader2.h>
#include <vtkImageReader2Factory.h>
#include <vtkImageThreshold.h>
#include <vtkInteractorStyleImage.h>
#include <vtkNew.h>
#include <vtkPointData.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRenderer.h>
#include <vtkSmartPointer.h>

int main(int argc, char* argv[])
{
  // Verify input arguments
  if (argc != 2)
  {
    std::cout << "Usage: " << argv[0] << " Filename e.g. FullHead.mhd" << std::endl;
    return EXIT_FAILURE;
  }

  // Read the image
  vtkNew<vtkImageReader2Factory> readerFactory;
  vtkSmartPointer<vtkImageReader2> reader;
  reader.TakeReference(readerFactory->CreateImageReader2(argv[1]));
  reader->SetFileName(argv[1]);
  reader->Update();

  int scalarRange[2];
  scalarRange[0] =
      reader->GetOutput()->GetPointData()->GetScalars()->GetRange()[0];
  scalarRange[1] =
      reader->GetOutput()->GetPointData()->GetScalars()->GetRange()[1];
  std::cout << "Range: " << scalarRange[0] << ", " << scalarRange[1]
            << std::endl;
  // int middleSlice = (reader->GetOutput()->GetExtent()[5] -
  //                   reader->GetOutput()->GetExtent()[4]) /
  //    2;

  // Better to use this value.
  auto middleSlice = 22;

  // Work with triple images
  vtkNew<vtkImageCast> cast;
  cast->SetInputConnection(reader->GetOutputPort());
  cast->SetOutputScalarTypeToDouble();
  cast->Update();

  vtkNew<vtkImageLaplacian> laplacian;
  laplacian->SetInputConnection(cast->GetOutputPort());
  laplacian->SetDimensionality(3);

  vtkNew<vtkImageMathematics> enhance;
  enhance->SetInputConnection(0, cast->GetOutputPort());
  enhance->SetInputConnection(1, laplacian->GetOutputPort());
  enhance->SetOperationToSubtract();

  int colorWindow = (scalarRange[1] - scalarRange[0]);
  int colorLevel = colorWindow / 2;

  // Map the image through the lookup table
  vtkNew<vtkImageMapToWindowLevelColors> originalColor;
  originalColor->SetWindow(colorWindow);
  originalColor->SetLevel(colorLevel);
  originalColor->SetInputConnection(reader->GetOutputPort());

  vtkNew<vtkImageActor> originalActor;
  originalActor->GetMapper()->SetInputConnection(
      originalColor->GetOutputPort());
  originalActor->GetProperty()->SetInterpolationTypeToNearest();
  originalActor->SetDisplayExtent(
      reader->GetDataExtent()[0], reader->GetDataExtent()[1],
      reader->GetDataExtent()[2], reader->GetDataExtent()[3], middleSlice,
      middleSlice);

  vtkNew<vtkImageMapToWindowLevelColors> laplacianColor;
  laplacianColor->SetWindow(1000);
  laplacianColor->SetLevel(0);
  laplacianColor->SetInputConnection(laplacian->GetOutputPort());

  vtkNew<vtkImageActor> laplacianActor;
  laplacianActor->GetMapper()->SetInputConnection(
      laplacianColor->GetOutputPort());
  laplacianActor->GetProperty()->SetInterpolationTypeToNearest();
  laplacianActor->SetDisplayExtent(originalActor->GetDisplayExtent());

  vtkNew<vtkImageMapToWindowLevelColors> enhancedColor;
  enhancedColor->SetWindow(colorWindow);
  enhancedColor->SetLevel(colorLevel);
  enhancedColor->SetInputConnection(enhance->GetOutputPort());

  vtkNew<vtkImageActor> enhancedActor;
  enhancedActor->GetMapper()->SetInputConnection(
      enhancedColor->GetOutputPort());
  enhancedActor->GetProperty()->SetInterpolationTypeToNearest();
  enhancedActor->SetDisplayExtent(originalActor->GetDisplayExtent());

  // Setup renderers
  vtkNew<vtkRenderer> originalRenderer;
  originalRenderer->AddActor(originalActor);
  vtkNew<vtkRenderer> laplacianRenderer;
  laplacianRenderer->AddActor(laplacianActor);
  vtkNew<vtkRenderer> enhancedRenderer;
  enhancedRenderer->AddActor(enhancedActor);

  std::vector<vtkSmartPointer<vtkRenderer>> renderers;
  renderers.push_back(originalRenderer);
  renderers.push_back(laplacianRenderer);
  renderers.push_back(enhancedRenderer);

  // Setup viewports for the renderers
  int rendererSize = 400;
  unsigned int xGridDimensions = 3;
  unsigned int yGridDimensions = 1;

  vtkNew<vtkRenderWindow> renderWindow;
  renderWindow->SetSize(rendererSize * xGridDimensions,
                        rendererSize * yGridDimensions);
  for (int row = 0; row < static_cast<int>(yGridDimensions); row++)
  {
    for (int col = 0; col < static_cast<int>(xGridDimensions); col++)
    {
      int index = row * xGridDimensions + col;
      // (xmin, ymin, xmax, ymax)
      double viewport[4] = {
          static_cast<double>(col) / xGridDimensions,
          static_cast<double>(yGridDimensions - (row + 1)) / yGridDimensions,
          static_cast<double>(col + 1) / xGridDimensions,
          static_cast<double>(yGridDimensions - row) / yGridDimensions};
      renderers[index]->SetViewport(viewport);
      renderWindow->AddRenderer(renderers[index]);
    }
  }
  renderWindow->SetWindowName("EnhanceEdges");

  vtkNew<vtkRenderWindowInteractor> renderWindowInteractor;
  vtkNew<vtkInteractorStyleImage> style;

  renderWindowInteractor->SetInteractorStyle(style);
  renderWindowInteractor->SetRenderWindow(renderWindow);

  // Renderers share one camera
  renderWindow->Render();
  renderers[0]->GetActiveCamera()->Dolly(1.5);
  renderers[0]->ResetCameraClippingRange();

  for (size_t r = 1; r < renderers.size(); ++r)
  {
    renderers[r]->SetActiveCamera(renderers[0]->GetActiveCamera());
  }
  renderWindowInteractor->Initialize();
  renderWindowInteractor->Start();

  return EXIT_SUCCESS;
}

CMakeLists.txt

cmake_minimum_required(VERSION 3.12 FATAL_ERROR)

project(EnhanceEdges)

find_package(VTK COMPONENTS 
  CommonCore
  CommonDataModel
  IOImage
  ImagingColor
  ImagingCore
  ImagingGeneral
  ImagingMath
  InteractionStyle
  RenderingContextOpenGL2
  RenderingCore
  RenderingFreeType
  RenderingGL2PSOpenGL2
  RenderingOpenGL2
)

if (NOT VTK_FOUND)
  message(FATAL_ERROR "EnhanceEdges: 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(EnhanceEdges MACOSX_BUNDLE EnhanceEdges.cxx )
  target_link_libraries(EnhanceEdges PRIVATE ${VTK_LIBRARIES}
)
# vtk_module_autoinit is needed
vtk_module_autoinit(
  TARGETS EnhanceEdges
  MODULES ${VTK_LIBRARIES}
)

Download and Build EnhanceEdges

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

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

./EnhanceEdges

WINDOWS USERS

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