SimpleITK  
Python/ConnectedThresholdImageFilter.py
1#! /usr/bin/env python
2# =========================================================================
3#
4# Copyright NumFOCUS
5#
6# Licensed under the Apache License, Version 2.0 (the "License");
7# you may not use this file except in compliance with the License.
8# You may obtain a copy of the License at
9#
10# http://www.apache.org/licenses/LICENSE-2.0.txt
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS,
14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15# See the License for the specific language governing permissions and
16# limitations under the License.
17#
18# =========================================================================
19
20""" An example script showing the use of the ConnectedThresholdImageFilter """
21
22import sys
23import os
24import SimpleITK as sitk
25
26#
27# Check Command Line
28#
29if len(sys.argv) < 7:
30 print(
31 "Usage: ConnectedThresholdImageFilter inputImage outputImage",
32 "lowerThreshold upperThreshold seedX seedY [seed2X seed2Y ... ]",
33 )
34 sys.exit(1)
35
36#
37# Read the image
38#
39reader = sitk.ImageFileReader()
40reader.SetFileName(sys.argv[1])
41image = reader.Execute()
42
43#
44# Blur using CurvatureFlowImageFilter
45#
47blurFilter.SetNumberOfIterations(5)
48blurFilter.SetTimeStep(0.125)
49image = blurFilter.Execute(image)
50
51#
52# Set up ConnectedThresholdImageFilter for segmentation
53#
54segmentationFilter = sitk.ConnectedThresholdImageFilter()
55segmentationFilter.SetLower(float(sys.argv[3]))
56segmentationFilter.SetUpper(float(sys.argv[4]))
57segmentationFilter.SetReplaceValue(255)
58
59for i in range(5, len(sys.argv) - 1, 2):
60 seed = [int(sys.argv[i]), int(sys.argv[i + 1])]
61 segmentationFilter.AddSeed(seed)
62 print("Adding seed at: ", seed, " with intensity: ", image.GetPixel(*seed))
63
64# Run the segmentation filter
65image = segmentationFilter.Execute(image)
66image[seed] = 255
67
68#
69# Write out the result
70#
71writer = sitk.ImageFileWriter()
72writer.SetFileName(sys.argv[2])
73writer.Execute(image)
74
75if "SITK_NOSHOW" not in os.environ:
76 sitk.Show(image, "ConntectedThreshold")
Label pixels that are connected to a seed and lie within a range of values.
Denoise an image using curvature driven flow.
Read an image file and return a SimpleITK Image.
Write out a SimpleITK image to the specified file location.
void SITKIO_EXPORT Show(const Image &image, const std::string &title="", const bool debugOn=ProcessObject::GetGlobalDefaultDebug())