Datasets:
dicom stl png pipeline
Browse files- README.md +1 -0
- code/README.md +39 -0
- code/dicom_stl_png_pipeline/dicom2stl.py +447 -0
- code/dicom_stl_png_pipeline/parseargs.py +223 -0
- code/dicom_stl_png_pipeline/requirements.txt +5 -0
- code/dicom_stl_png_pipeline/stl2png_centered.py +70 -0
- code/dicom_stl_png_pipeline/utils/__init__.py +1 -0
- code/dicom_stl_png_pipeline/utils/dicomutils.py +162 -0
- code/dicom_stl_png_pipeline/utils/sitk2vtk.py +87 -0
- code/dicom_stl_png_pipeline/utils/vtk2sitk.py +40 -0
- code/dicom_stl_png_pipeline/utils/vtkutils.py +506 -0
README.md
CHANGED
|
@@ -14,6 +14,7 @@ This repository contains:
|
|
| 14 |
- `AbdCTBench_dataset/`: split CSVs + image data archive + 3D stl meshes
|
| 15 |
- `code/`: training and evaluation pipeline
|
| 16 |
- `models/`: released pretrained checkpoints (`.safetensors`) with configs
|
|
|
|
| 17 |
|
| 18 |
## Quick Start
|
| 19 |
|
|
|
|
| 14 |
- `AbdCTBench_dataset/`: split CSVs + image data archive + 3D stl meshes
|
| 15 |
- `code/`: training and evaluation pipeline
|
| 16 |
- `models/`: released pretrained checkpoints (`.safetensors`) with configs
|
| 17 |
+
- `code/dicom_stl_png_pipeline/`: DICOM -> STL -> PNG conversion scripts
|
| 18 |
|
| 19 |
## Quick Start
|
| 20 |
|
code/README.md
CHANGED
|
@@ -69,6 +69,45 @@ Each released model folder contains:
|
|
| 69 |
- `config.json`
|
| 70 |
- `biomarker_config.json`
|
| 71 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
## Biomarker Config Templates
|
| 73 |
|
| 74 |
- `config/biomarker_config_single_task_example.yaml`
|
|
|
|
| 69 |
- `config.json`
|
| 70 |
- `biomarker_config.json`
|
| 71 |
|
| 72 |
+
## DICOM to PNG Pipeline
|
| 73 |
+
|
| 74 |
+
The DICOM -> STL -> PNG conversion scripts are in:
|
| 75 |
+
|
| 76 |
+
- `dicom_stl_png_pipeline/`
|
| 77 |
+
|
| 78 |
+
Key files:
|
| 79 |
+
|
| 80 |
+
- `dicom2stl.py`: converts a DICOM series (folder/zip) to STL
|
| 81 |
+
- `stl2png_centered.py`: renders STL to a centered PNG
|
| 82 |
+
- `parseargs.py` and `utils/`: argument parsing and volume/mesh helper utilities
|
| 83 |
+
- `requirements.txt` in this folder: extra dependencies for this conversion pipeline
|
| 84 |
+
|
| 85 |
+
Install pipeline dependencies:
|
| 86 |
+
|
| 87 |
+
```bash
|
| 88 |
+
pip install -r dicom_stl_png_pipeline/requirements.txt
|
| 89 |
+
```
|
| 90 |
+
|
| 91 |
+
Minimal usage:
|
| 92 |
+
|
| 93 |
+
```bash
|
| 94 |
+
python dicom_stl_png_pipeline/dicom2stl.py \
|
| 95 |
+
--type skin \
|
| 96 |
+
--output ./sample.stl \
|
| 97 |
+
/path/to/dicom_series_folder
|
| 98 |
+
```
|
| 99 |
+
|
| 100 |
+
```bash
|
| 101 |
+
python dicom_stl_png_pipeline/stl2png_centered.py \
|
| 102 |
+
./sample.stl \
|
| 103 |
+
./sample.png
|
| 104 |
+
```
|
| 105 |
+
|
| 106 |
+
Notes:
|
| 107 |
+
|
| 108 |
+
- This conversion pipeline is optional and separate from model train/test.
|
| 109 |
+
- `train.py` and `test.py` consume PNG + CSV data and do not run DICOM conversion internally.
|
| 110 |
+
|
| 111 |
## Biomarker Config Templates
|
| 112 |
|
| 113 |
- `config/biomarker_config_single_task_example.yaml`
|
code/dicom_stl_png_pipeline/dicom2stl.py
ADDED
|
@@ -0,0 +1,447 @@
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#! /usr/bin/env python
|
| 2 |
+
|
| 3 |
+
"""
|
| 4 |
+
Script to take a Dicom series and generate an STL surface mesh.
|
| 5 |
+
|
| 6 |
+
Written by David T. Chen from the National Institute of Allergy
|
| 7 |
+
and Infectious Diseases, dchen@mail.nih.gov.
|
| 8 |
+
It is covered by the Apache License, Version 2.0:
|
| 9 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
|
| 11 |
+
Note: if you run this script with the individual Dicom slices provided on the
|
| 12 |
+
command line, they might not be ordered in the correct order. You are better
|
| 13 |
+
off providing a zip file or a directory. Dicom slices are not necessarily
|
| 14 |
+
ordered the same alphabetically as they are physically.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
from __future__ import print_function
|
| 18 |
+
|
| 19 |
+
import gc
|
| 20 |
+
import math
|
| 21 |
+
import os
|
| 22 |
+
import sys
|
| 23 |
+
import tempfile
|
| 24 |
+
import shutil
|
| 25 |
+
import time
|
| 26 |
+
import zipfile
|
| 27 |
+
import vtk
|
| 28 |
+
import re
|
| 29 |
+
import SimpleITK as sitk
|
| 30 |
+
|
| 31 |
+
from SimpleITK.utilities.vtk import sitk2vtk
|
| 32 |
+
|
| 33 |
+
import parseargs
|
| 34 |
+
|
| 35 |
+
from glob import glob
|
| 36 |
+
|
| 37 |
+
from utils import dicomutils
|
| 38 |
+
from utils import vtkutils
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def roundThousand(x):
|
| 42 |
+
y = int(1000.0 * x + 0.5)
|
| 43 |
+
return str(float(y) * 0.001)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def elapsedTime(start_time):
|
| 47 |
+
dt = time.perf_counter() - start_time
|
| 48 |
+
print(" %4.3f seconds" % dt)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def loadVolume(fname, tempDir=None, verbose=False):
|
| 52 |
+
modality = None
|
| 53 |
+
zipFlag = False
|
| 54 |
+
dirFlag = False
|
| 55 |
+
|
| 56 |
+
# Parse wildcards
|
| 57 |
+
# sum() flatten nested list
|
| 58 |
+
fname = sum([glob(f) for f in fname], [])
|
| 59 |
+
|
| 60 |
+
if len(fname) == 0:
|
| 61 |
+
print("Error: no valid input given.")
|
| 62 |
+
sys.exit(4)
|
| 63 |
+
|
| 64 |
+
if zipfile.is_zipfile(fname[0]):
|
| 65 |
+
zipFlag = True
|
| 66 |
+
|
| 67 |
+
if os.path.isdir(fname[0]):
|
| 68 |
+
dirFlag = True
|
| 69 |
+
else:
|
| 70 |
+
if len(fname) > 1:
|
| 71 |
+
print(
|
| 72 |
+
"File names: ",
|
| 73 |
+
fname[0],
|
| 74 |
+
fname[1],
|
| 75 |
+
"...",
|
| 76 |
+
fname[len(fname) - 1],
|
| 77 |
+
"\n",
|
| 78 |
+
)
|
| 79 |
+
else:
|
| 80 |
+
print("File names: ", fname, "\n")
|
| 81 |
+
|
| 82 |
+
img = sitk.Image(100, 100, 100, sitk.sitkUInt8)
|
| 83 |
+
|
| 84 |
+
# Load our Dicom data
|
| 85 |
+
#
|
| 86 |
+
if zipFlag:
|
| 87 |
+
# Case for a zip file of images
|
| 88 |
+
if args.verbose:
|
| 89 |
+
print("zip")
|
| 90 |
+
if not tempDir:
|
| 91 |
+
with tempfile.TemporaryDirectory() as defaultTempDir:
|
| 92 |
+
img, modality = dicomutils.loadZipDicom(fname[0], defaultTempDir)
|
| 93 |
+
else:
|
| 94 |
+
img, modality = dicomutils.loadZipDicom(fname[0], tempDir)
|
| 95 |
+
|
| 96 |
+
else:
|
| 97 |
+
if dirFlag:
|
| 98 |
+
if verbose:
|
| 99 |
+
print("directory")
|
| 100 |
+
img, modality = dicomutils.loadLargestSeries(fname[0])
|
| 101 |
+
|
| 102 |
+
else:
|
| 103 |
+
# Case for a single volume image
|
| 104 |
+
if len(fname) == 1:
|
| 105 |
+
if verbose:
|
| 106 |
+
print("Reading volume: ", fname[0])
|
| 107 |
+
img = sitk.ReadImage(fname[0])
|
| 108 |
+
modality = dicomutils.getModality(img)
|
| 109 |
+
|
| 110 |
+
else:
|
| 111 |
+
# Case for a series of image files
|
| 112 |
+
# For files named like IM1, IM2, .. IM10
|
| 113 |
+
# They would be ordered by default as IM1, IM10, IM2, ...
|
| 114 |
+
# sort the fname list in correct serial number order
|
| 115 |
+
RE_NUMBERS = re.compile(r"\d+")
|
| 116 |
+
|
| 117 |
+
def extract_int(file_path):
|
| 118 |
+
file_name = os.path.basename(file_path)
|
| 119 |
+
return int(RE_NUMBERS.findall(file_name)[0])
|
| 120 |
+
|
| 121 |
+
fname = sorted(fname, key=extract_int)
|
| 122 |
+
|
| 123 |
+
if args.verbose:
|
| 124 |
+
if args.verbose > 1:
|
| 125 |
+
print("Reading images: ", fname)
|
| 126 |
+
else:
|
| 127 |
+
print(
|
| 128 |
+
"Reading images: ",
|
| 129 |
+
fname[0],
|
| 130 |
+
fname[1],
|
| 131 |
+
"...",
|
| 132 |
+
fname[len(fname) - 1],
|
| 133 |
+
)
|
| 134 |
+
isr = sitk.ImageSeriesReader()
|
| 135 |
+
isr.SetFileNames(fname)
|
| 136 |
+
img = isr.Execute()
|
| 137 |
+
firstslice = sitk.ReadImage(fname[0])
|
| 138 |
+
modality = dicomutils.getModality(firstslice)
|
| 139 |
+
|
| 140 |
+
return img, modality
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def writeMetadataFile(img, metaName):
|
| 144 |
+
FP = open(metaName, "w")
|
| 145 |
+
size = img.GetSize()
|
| 146 |
+
spacing = img.GetSpacing()
|
| 147 |
+
FP.write("xdimension " + str(size[0]) + "\n")
|
| 148 |
+
FP.write("ydimension " + str(size[1]) + "\n")
|
| 149 |
+
FP.write("zdimension " + str(size[2]) + "\n")
|
| 150 |
+
FP.write("xspacing " + roundThousand(spacing[0]) + "\n")
|
| 151 |
+
FP.write("yspacing " + roundThousand(spacing[1]) + "\n")
|
| 152 |
+
FP.write("zspacing " + roundThousand(spacing[2]) + "\n")
|
| 153 |
+
FP.close()
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def volumeProcessingPipeline(
|
| 157 |
+
img, shrinkFlag=True, anisotropicSmoothing=True, thresholds=[], medianFilter=False
|
| 158 |
+
):
|
| 159 |
+
#
|
| 160 |
+
# shrink the volume to 256 cubed
|
| 161 |
+
if shrinkFlag:
|
| 162 |
+
sfactor = []
|
| 163 |
+
size = img.GetSize()
|
| 164 |
+
total = 0
|
| 165 |
+
for s in size:
|
| 166 |
+
x = int(math.ceil(s / 256))
|
| 167 |
+
sfactor.append(x)
|
| 168 |
+
total = total + x
|
| 169 |
+
|
| 170 |
+
if total > 3:
|
| 171 |
+
# if total==3, no shrink happens
|
| 172 |
+
t = time.perf_counter()
|
| 173 |
+
print("Shrink factors: ", sfactor)
|
| 174 |
+
img = sitk.Shrink(img, sfactor)
|
| 175 |
+
newsize = img.GetSize()
|
| 176 |
+
print(size, "->", newsize)
|
| 177 |
+
elapsedTime(t)
|
| 178 |
+
|
| 179 |
+
gc.collect()
|
| 180 |
+
|
| 181 |
+
# Apply anisotropic smoothing to the volume image. That's a smoothing filter
|
| 182 |
+
# that preserves edges.
|
| 183 |
+
#
|
| 184 |
+
if anisotropicSmoothing:
|
| 185 |
+
print("Anisotropic Smoothing")
|
| 186 |
+
t = time.perf_counter()
|
| 187 |
+
pixelType = img.GetPixelID()
|
| 188 |
+
img = sitk.Cast(img, sitk.sitkFloat32)
|
| 189 |
+
img = sitk.CurvatureAnisotropicDiffusion(img, 0.03)
|
| 190 |
+
img = sitk.Cast(img, pixelType)
|
| 191 |
+
elapsedTime(t)
|
| 192 |
+
gc.collect()
|
| 193 |
+
|
| 194 |
+
# Apply the double threshold filter to the volume
|
| 195 |
+
#
|
| 196 |
+
if len(thresholds) == 4:
|
| 197 |
+
print("Double Threshold: ", thresholds)
|
| 198 |
+
t = time.perf_counter()
|
| 199 |
+
img = sitk.DoubleThreshold(
|
| 200 |
+
img, thresholds[0], thresholds[1], thresholds[2], thresholds[3], 255, 0
|
| 201 |
+
)
|
| 202 |
+
elapsedTime(t)
|
| 203 |
+
gc.collect()
|
| 204 |
+
|
| 205 |
+
# Apply a 3x3x1 median filter. I only use 1 in the Z direction so it's not so
|
| 206 |
+
# slow.
|
| 207 |
+
#
|
| 208 |
+
if medianFilter:
|
| 209 |
+
print("Median filter")
|
| 210 |
+
t = time.perf_counter()
|
| 211 |
+
img = sitk.Median(img, [3, 3, 1])
|
| 212 |
+
elapsedTime(t)
|
| 213 |
+
gc.collect()
|
| 214 |
+
|
| 215 |
+
#
|
| 216 |
+
# Get the minimum image intensity for padding the image
|
| 217 |
+
#
|
| 218 |
+
stats = sitk.StatisticsImageFilter()
|
| 219 |
+
stats.Execute(img)
|
| 220 |
+
minVal = stats.GetMinimum()
|
| 221 |
+
|
| 222 |
+
# Pad black to the boundaries of the image
|
| 223 |
+
#
|
| 224 |
+
pad = [5, 5, 5]
|
| 225 |
+
img = sitk.ConstantPad(img, pad, pad, minVal)
|
| 226 |
+
gc.collect()
|
| 227 |
+
|
| 228 |
+
return img
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def meshProcessingPipeline(
|
| 232 |
+
mesh,
|
| 233 |
+
connectivityFilter=False,
|
| 234 |
+
smallFactor=0.05,
|
| 235 |
+
smoothN=5000,
|
| 236 |
+
reduceFactor=0.9,
|
| 237 |
+
rotation=["X", 0.0],
|
| 238 |
+
debug=False,
|
| 239 |
+
subdivisionIterations=2, # Add this parameter for subdivision iterations
|
| 240 |
+
):
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
if debug:
|
| 244 |
+
print("Cleaning mesh")
|
| 245 |
+
mesh2 = vtkutils.cleanMesh(mesh, connectivityFilter)
|
| 246 |
+
mesh = None
|
| 247 |
+
gc.collect()
|
| 248 |
+
|
| 249 |
+
# Apply subdivision
|
| 250 |
+
if subdivisionIterations > 0:
|
| 251 |
+
print(f"Applying subdivision filter with {subdivisionIterations} iterations")
|
| 252 |
+
subdivisionFilter = vtk.vtkLoopSubdivisionFilter()
|
| 253 |
+
subdivisionFilter.SetNumberOfSubdivisions(subdivisionIterations)
|
| 254 |
+
subdivisionFilter.SetInputData(mesh2)
|
| 255 |
+
subdivisionFilter.Update()
|
| 256 |
+
mesh2 = subdivisionFilter.GetOutput()
|
| 257 |
+
gc.collect()
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
if debug:
|
| 261 |
+
print(f"Cleaning small parts ratio{smallFactor}")
|
| 262 |
+
mesh_cleaned_parts = vtkutils.removeSmallObjects(mesh2, smallFactor)
|
| 263 |
+
mesh2 = None
|
| 264 |
+
gc.collect()
|
| 265 |
+
|
| 266 |
+
if debug:
|
| 267 |
+
print("Smoothing mesh", smoothN, "iterations")
|
| 268 |
+
mesh3 = vtkutils.smoothMesh(mesh_cleaned_parts, smoothN)
|
| 269 |
+
mesh_cleaned_parts = None
|
| 270 |
+
gc.collect()
|
| 271 |
+
|
| 272 |
+
if debug:
|
| 273 |
+
print("Simplifying mesh")
|
| 274 |
+
mesh4 = vtkutils.reduceMesh(mesh3, reduceFactor)
|
| 275 |
+
mesh3 = None
|
| 276 |
+
gc.collect()
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
print(rotation)
|
| 280 |
+
axis_map = {"X": 0, "Y": 1, "Z": 2}
|
| 281 |
+
try:
|
| 282 |
+
rotAxis = axis_map[rotation[0]]
|
| 283 |
+
if rotation[1] != 0.0:
|
| 284 |
+
mesh5 = vtkutils.rotateMesh(mesh4, rotAxis, rotation[1])
|
| 285 |
+
else:
|
| 286 |
+
mesh5 = mesh4
|
| 287 |
+
except BaseException:
|
| 288 |
+
mesh5 = mesh4
|
| 289 |
+
mesh4 = None
|
| 290 |
+
gc.collect()
|
| 291 |
+
|
| 292 |
+
return mesh5
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
def getTissueThresholds(tissueType):
|
| 296 |
+
thresholds = []
|
| 297 |
+
medianFilter = False
|
| 298 |
+
|
| 299 |
+
# Convert tissue type name to threshold values
|
| 300 |
+
print("Tissue type: ", tissueType)
|
| 301 |
+
if tissueType.find("bone") > -1:
|
| 302 |
+
thresholds = [200.0, 800.0, 1300.0, 1500.0]
|
| 303 |
+
elif tissueType.find("skin") > -1:
|
| 304 |
+
thresholds = [-200.0, 0.0, 500.0, 1500.0]
|
| 305 |
+
elif tissueType.find("soft") > -1:
|
| 306 |
+
thresholds = [-15.0, 30.0, 58.0, 100.0]
|
| 307 |
+
medianFilter = True
|
| 308 |
+
elif tissueType.find("fat") > -1:
|
| 309 |
+
thresholds = [-122.0, -112.0, -96.0, -70.0]
|
| 310 |
+
medianFilter = True
|
| 311 |
+
|
| 312 |
+
return thresholds, medianFilter
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
def dicom2stl(args):
|
| 316 |
+
# Global variables
|
| 317 |
+
#
|
| 318 |
+
thresholds = []
|
| 319 |
+
shrinkFlag = True
|
| 320 |
+
connectivityFilter = True
|
| 321 |
+
anisotropicSmoothing = True
|
| 322 |
+
medianFilter = False
|
| 323 |
+
rotFlag = True
|
| 324 |
+
|
| 325 |
+
# Handle enable/disable filters
|
| 326 |
+
|
| 327 |
+
if args.filters:
|
| 328 |
+
for x in args.filters:
|
| 329 |
+
val = True
|
| 330 |
+
y = x
|
| 331 |
+
if x[:2] == "no":
|
| 332 |
+
val = False
|
| 333 |
+
y = x[2:]
|
| 334 |
+
if y.startswith("shrink"):
|
| 335 |
+
shrinkFlag = val
|
| 336 |
+
if y.startswith("aniso"):
|
| 337 |
+
anisotropicSmoothing = val
|
| 338 |
+
if y.startswith("median"):
|
| 339 |
+
medianFilter = val
|
| 340 |
+
if y.startswith("large"):
|
| 341 |
+
connectivityFilter = val
|
| 342 |
+
if y.startswith("rotat"):
|
| 343 |
+
rotFlag = val
|
| 344 |
+
|
| 345 |
+
print("")
|
| 346 |
+
if args.temp == None:
|
| 347 |
+
args.temp = tempfile.mkdtemp()
|
| 348 |
+
print("Temp dir: ", args.temp)
|
| 349 |
+
|
| 350 |
+
if args.tissue:
|
| 351 |
+
thresholds, medianFilter = getTissueThresholds(args.tissue)
|
| 352 |
+
|
| 353 |
+
if args.double_threshold:
|
| 354 |
+
words = args.double_threshold.split(";")
|
| 355 |
+
thresholds = []
|
| 356 |
+
for x in words:
|
| 357 |
+
thresholds.append(float(x))
|
| 358 |
+
# check that there are 4 threshold values.
|
| 359 |
+
print("Thresholds: ", thresholds)
|
| 360 |
+
if len(thresholds) != 4:
|
| 361 |
+
print("Error: Thresholds is not of len 4.", thresholds)
|
| 362 |
+
sys.exit(3)
|
| 363 |
+
else:
|
| 364 |
+
print("Isovalue = ", args.isovalue)
|
| 365 |
+
|
| 366 |
+
if args.debug:
|
| 367 |
+
print("SimpleITK version: ", sitk.Version.VersionString())
|
| 368 |
+
print("SimpleITK: ", sitk, "\n")
|
| 369 |
+
|
| 370 |
+
#
|
| 371 |
+
# Load the volume image
|
| 372 |
+
img, modality = loadVolume(args.filenames, args.temp, args.verbose)
|
| 373 |
+
|
| 374 |
+
if args.ctonly:
|
| 375 |
+
if modality.find("CT") == -1:
|
| 376 |
+
print("Imaging modality is not CT. Exiting.")
|
| 377 |
+
sys.exit(1)
|
| 378 |
+
|
| 379 |
+
# Write out the metadata text file
|
| 380 |
+
if args.meta:
|
| 381 |
+
writeMetadataFile(img, args.meta)
|
| 382 |
+
|
| 383 |
+
#
|
| 384 |
+
# Filter the volume image
|
| 385 |
+
img = volumeProcessingPipeline(
|
| 386 |
+
img, shrinkFlag, anisotropicSmoothing, thresholds, medianFilter
|
| 387 |
+
)
|
| 388 |
+
|
| 389 |
+
if len(thresholds) == 4:
|
| 390 |
+
args.isovalue = 64.0
|
| 391 |
+
|
| 392 |
+
if args.verbose:
|
| 393 |
+
print("\nImage for isocontouring")
|
| 394 |
+
print(img.GetSize())
|
| 395 |
+
print(img.GetPixelIDTypeAsString())
|
| 396 |
+
print(img.GetSpacing())
|
| 397 |
+
print(img.GetOrigin())
|
| 398 |
+
if args.verbose > 1:
|
| 399 |
+
print(img)
|
| 400 |
+
print("")
|
| 401 |
+
|
| 402 |
+
# Convert the SimpleITK image to a VTK image
|
| 403 |
+
vtkimg = sitk2vtk(img)
|
| 404 |
+
|
| 405 |
+
# Delete the SimpleITK image, free its memory
|
| 406 |
+
img = None
|
| 407 |
+
gc.collect()
|
| 408 |
+
|
| 409 |
+
if args.debug:
|
| 410 |
+
print("\nVTK version: ", vtk.vtkVersion.GetVTKVersion())
|
| 411 |
+
print("VTK: ", vtk, "\n")
|
| 412 |
+
|
| 413 |
+
# Extract the iso-surface
|
| 414 |
+
if args.debug:
|
| 415 |
+
print("Extracting surface")
|
| 416 |
+
mesh = vtkutils.extractSurface(vtkimg, args.isovalue)
|
| 417 |
+
|
| 418 |
+
# Delete the VTK image, free its memory
|
| 419 |
+
vtkimg = None
|
| 420 |
+
gc.collect()
|
| 421 |
+
|
| 422 |
+
# Filter the output mesh
|
| 423 |
+
mesh = meshProcessingPipeline(
|
| 424 |
+
mesh,
|
| 425 |
+
connectivityFilter,
|
| 426 |
+
args.small,
|
| 427 |
+
args.smooth,
|
| 428 |
+
args.reduce,
|
| 429 |
+
[args.rotaxis, args.rotangle],
|
| 430 |
+
args.debug,
|
| 431 |
+
)
|
| 432 |
+
|
| 433 |
+
# We done! Write out the results
|
| 434 |
+
vtkutils.writeMesh(mesh, args.output)
|
| 435 |
+
|
| 436 |
+
# remove the temp directory
|
| 437 |
+
if args.clean:
|
| 438 |
+
# shutil.rmtree(args.temp)
|
| 439 |
+
# with context manager the temp dir would be deleted any way
|
| 440 |
+
pass
|
| 441 |
+
|
| 442 |
+
print("")
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
if __name__ == "__main__":
|
| 446 |
+
args = parseargs.parseargs()
|
| 447 |
+
dicom2stl(args)
|
code/dicom_stl_png_pipeline/parseargs.py
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#! /usr/bin/env python
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class disableFilter(argparse.Action):
|
| 7 |
+
def __call__(self, parser, args, values, option_string=None):
|
| 8 |
+
# print("action, baby!", self.dest, values)
|
| 9 |
+
# print(args, type(args))
|
| 10 |
+
noval = "no" + values
|
| 11 |
+
if isinstance(args.filters, type(None)):
|
| 12 |
+
args.filters = [noval]
|
| 13 |
+
else:
|
| 14 |
+
args.filters.append(noval)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class enableAnisotropic(argparse.Action):
|
| 18 |
+
def __init__(self, nargs=0, **kw):
|
| 19 |
+
super().__init__(nargs=nargs, **kw)
|
| 20 |
+
|
| 21 |
+
def __call__(self, parser, args, values, option_string=None):
|
| 22 |
+
# x = getattr(args, 'filters')
|
| 23 |
+
if isinstance(args.filters, type(None)):
|
| 24 |
+
args.filters = ["anisotropic"]
|
| 25 |
+
# args.filters.append('anisotropic')
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class enableLargest(argparse.Action):
|
| 29 |
+
def __init__(self, nargs=0, **kw):
|
| 30 |
+
super().__init__(nargs=nargs, **kw)
|
| 31 |
+
|
| 32 |
+
def __call__(self, parser, args, values, option_string=None):
|
| 33 |
+
x = getattr(args, "filters")
|
| 34 |
+
x.append("largest")
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def createParser():
|
| 38 |
+
parser = argparse.ArgumentParser()
|
| 39 |
+
|
| 40 |
+
parser.add_argument("filenames", nargs="*")
|
| 41 |
+
|
| 42 |
+
parser.add_argument(
|
| 43 |
+
"--verbose",
|
| 44 |
+
"-v",
|
| 45 |
+
action="store_true",
|
| 46 |
+
default=False,
|
| 47 |
+
dest="verbose",
|
| 48 |
+
help="Enable verbose messages",
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
parser.add_argument(
|
| 52 |
+
"--debug",
|
| 53 |
+
"-D",
|
| 54 |
+
action="store_true",
|
| 55 |
+
default=False,
|
| 56 |
+
dest="debug",
|
| 57 |
+
help="""Enable debugging messages
|
| 58 |
+
""",
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
parser.add_argument(
|
| 62 |
+
"--output",
|
| 63 |
+
"-o",
|
| 64 |
+
action="store",
|
| 65 |
+
dest="output",
|
| 66 |
+
default="result.stl",
|
| 67 |
+
help="Output file name (default=result.stl)",
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
parser.add_argument(
|
| 71 |
+
"--meta",
|
| 72 |
+
"-m",
|
| 73 |
+
action="store",
|
| 74 |
+
dest="meta",
|
| 75 |
+
help="Output metadata file",
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
parser.add_argument(
|
| 79 |
+
"--ct",
|
| 80 |
+
action="store_true",
|
| 81 |
+
default=False,
|
| 82 |
+
dest="ctonly",
|
| 83 |
+
help="Only allow CT Dicom as input",
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
parser.add_argument(
|
| 87 |
+
"--clean",
|
| 88 |
+
"-c",
|
| 89 |
+
action="store_true",
|
| 90 |
+
default=False,
|
| 91 |
+
dest="clean",
|
| 92 |
+
help="Clean up temp files",
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
parser.add_argument(
|
| 96 |
+
"--temp", "-T", action="store", dest="temp", help="Temporary directory"
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
parser.add_argument(
|
| 100 |
+
"--search",
|
| 101 |
+
"-s",
|
| 102 |
+
action="store",
|
| 103 |
+
dest="search",
|
| 104 |
+
help="Dicom series search string",
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
# Options that apply to the volumetric portion of the pipeline
|
| 108 |
+
vol_group = parser.add_argument_group("Volume options")
|
| 109 |
+
|
| 110 |
+
vol_group.add_argument(
|
| 111 |
+
"--type",
|
| 112 |
+
"-t",
|
| 113 |
+
action="store",
|
| 114 |
+
dest="tissue",
|
| 115 |
+
choices=["skin", "bone", "soft_tissue", "fat"],
|
| 116 |
+
help="CT tissue type",
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
vol_group.add_argument(
|
| 120 |
+
"--anisotropic",
|
| 121 |
+
"-a",
|
| 122 |
+
action=enableAnisotropic,
|
| 123 |
+
help="Apply anisotropic smoothing to the volume",
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
vol_group.add_argument(
|
| 127 |
+
"--isovalue",
|
| 128 |
+
"-i",
|
| 129 |
+
action="store",
|
| 130 |
+
dest="isovalue",
|
| 131 |
+
type=float,
|
| 132 |
+
default=0.0,
|
| 133 |
+
help="Iso-surface value",
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
vol_group.add_argument(
|
| 137 |
+
"--double",
|
| 138 |
+
"-d",
|
| 139 |
+
action="store",
|
| 140 |
+
dest="double_threshold",
|
| 141 |
+
help="""Double threshold with 4 semicolon separated floats
|
| 142 |
+
""",
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
# Options that apply to the mesh processing portion of the pipeline
|
| 146 |
+
mesh_group = parser.add_argument_group("Mesh options")
|
| 147 |
+
mesh_group.add_argument(
|
| 148 |
+
"--largest",
|
| 149 |
+
"-l",
|
| 150 |
+
action=enableLargest,
|
| 151 |
+
help="Only keep the largest connected sub-mesh",
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
mesh_group.add_argument(
|
| 155 |
+
"--rotaxis",
|
| 156 |
+
action="store",
|
| 157 |
+
dest="rotaxis",
|
| 158 |
+
default="Y",
|
| 159 |
+
choices=["X", "Y", "Z"],
|
| 160 |
+
help="Rotation axis (default=Y)",
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
mesh_group.add_argument(
|
| 164 |
+
"--rotangle",
|
| 165 |
+
action="store",
|
| 166 |
+
dest="rotangle",
|
| 167 |
+
type=float,
|
| 168 |
+
default=0.0,
|
| 169 |
+
help="Rotation angle in degrees (default=180)",
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
mesh_group.add_argument(
|
| 173 |
+
"--smooth",
|
| 174 |
+
action="store",
|
| 175 |
+
dest="smooth",
|
| 176 |
+
type=int,
|
| 177 |
+
default=25,
|
| 178 |
+
help="Mesh smoothing iterations (default=25)",
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
mesh_group.add_argument(
|
| 182 |
+
"--reduce",
|
| 183 |
+
action="store",
|
| 184 |
+
dest="reduce",
|
| 185 |
+
type=float,
|
| 186 |
+
default=0.9,
|
| 187 |
+
help="Mesh reduction factor (default=.9)",
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
mesh_group.add_argument(
|
| 191 |
+
"--clean-small",
|
| 192 |
+
"-x",
|
| 193 |
+
action="store",
|
| 194 |
+
dest="small",
|
| 195 |
+
type=float,
|
| 196 |
+
default=0.05,
|
| 197 |
+
help="Clean small parts factor (default=.05)",
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
# Filtering options
|
| 201 |
+
filter_group = parser.add_argument_group("Filtering options")
|
| 202 |
+
filter_group.add_argument(
|
| 203 |
+
"--enable",
|
| 204 |
+
action="append",
|
| 205 |
+
dest="filters",
|
| 206 |
+
choices=["anisotropic", "shrink", "median", "largest", "rotation"],
|
| 207 |
+
help="Enable filtering options",
|
| 208 |
+
)
|
| 209 |
+
filter_group.add_argument(
|
| 210 |
+
"--disable",
|
| 211 |
+
action=disableFilter,
|
| 212 |
+
dest="filters",
|
| 213 |
+
choices=["anisotropic", "shrink", "median", "largest", "rotation"],
|
| 214 |
+
help="Disable filtering options",
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
return parser
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def parseargs():
|
| 221 |
+
parser = createParser()
|
| 222 |
+
args = parser.parse_args()
|
| 223 |
+
return args
|
code/dicom_stl_png_pipeline/requirements.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
numpy>=1.24.0
|
| 2 |
+
SimpleITK>=2.2
|
| 3 |
+
vtk>=9.2.0
|
| 4 |
+
pydicom>=2.3
|
| 5 |
+
simpleitkutilities>=0.2.2
|
code/dicom_stl_png_pipeline/stl2png_centered.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import pyvista as pv
|
| 3 |
+
import numpy as np
|
| 4 |
+
#import cv2
|
| 5 |
+
|
| 6 |
+
def blur_image(image_path, output_path, kernel_size=(5, 5)):
|
| 7 |
+
# Read the image
|
| 8 |
+
image = cv2.imread(image_path)
|
| 9 |
+
|
| 10 |
+
# Blur the image
|
| 11 |
+
blurred_image = cv2.GaussianBlur(image, kernel_size, 0)
|
| 12 |
+
|
| 13 |
+
# Write the blurred image back to a file
|
| 14 |
+
cv2.imwrite(output_path, blurred_image)
|
| 15 |
+
|
| 16 |
+
def generate_png_from_stl(stl_filename, png_filename, background_color=(1, 1, 1), camera_angles=(0, 0, 0)):
|
| 17 |
+
# Load the STL file
|
| 18 |
+
mesh = pv.read(stl_filename)
|
| 19 |
+
mesh = mesh.smooth(n_iter=5000) # Increase n_iter for more smoothing
|
| 20 |
+
|
| 21 |
+
# Center the mesh at the origin
|
| 22 |
+
bounds = mesh.bounds
|
| 23 |
+
center = [(bounds[i] + bounds[i+1]) / 2 for i in range(0, 6, 2)]
|
| 24 |
+
mesh.translate([-c for c in center])
|
| 25 |
+
|
| 26 |
+
# Create a plotter with window size set to 384x384
|
| 27 |
+
plotter = pv.Plotter(window_size=(384, 384), off_screen=True)
|
| 28 |
+
|
| 29 |
+
# Set up the camera position
|
| 30 |
+
distance_factor = 3 # Adjust this value to move the camera closer or further
|
| 31 |
+
cam_pos = [center[0], center[1] - (bounds[3] - bounds[2]) * distance_factor, center[2]]
|
| 32 |
+
focal_point = center
|
| 33 |
+
view_up = [0, 0, 1]
|
| 34 |
+
|
| 35 |
+
plotter.camera_position = [cam_pos, focal_point, view_up]
|
| 36 |
+
|
| 37 |
+
# Adjust the zoom (values < 1 will zoom out)
|
| 38 |
+
plotter.camera.zoom(0.8) # Adjust this value as needed
|
| 39 |
+
|
| 40 |
+
# Add the mesh without edges (lines) and with the desired color
|
| 41 |
+
plotter.add_mesh(mesh, color='white', show_edges=False)
|
| 42 |
+
|
| 43 |
+
# Set the background color
|
| 44 |
+
plotter.set_background(background_color)
|
| 45 |
+
|
| 46 |
+
# Take a screenshot and save as PNG
|
| 47 |
+
plotter.show(screenshot=png_filename)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def main():
|
| 51 |
+
parser = argparse.ArgumentParser(description="Generate a PNG image from an STL file.")
|
| 52 |
+
parser.add_argument("stl_file", help="Path to the STL file.")
|
| 53 |
+
parser.add_argument("png_file", help="Output PNG file name.")
|
| 54 |
+
parser.add_argument("--background", nargs=3, type=float, default=[0, 0, 0],
|
| 55 |
+
help="Background color as RGB values (between 0 and 1). Default is black.")
|
| 56 |
+
parser.add_argument("--camera", nargs=3, type=float, default=[0, 0, 0],
|
| 57 |
+
help="Camera view angles for azimuth (horizontal rotation), elevation (vertical rotation), and roll (rotation about view direction) in degrees. Default is (0, 0, 0).")
|
| 58 |
+
|
| 59 |
+
args = parser.parse_args()
|
| 60 |
+
stl_file = args.stl_file
|
| 61 |
+
png_file = args.png_file
|
| 62 |
+
background_color = tuple(args.background)
|
| 63 |
+
camera_angles = tuple(args.camera)
|
| 64 |
+
generate_png_from_stl(stl_file, png_file, background_color, camera_angles)
|
| 65 |
+
|
| 66 |
+
# Blur the resulting image
|
| 67 |
+
#blur_image(png_file, 'blured'+png_file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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#! /usr/bin/env python
|
| 2 |
+
|
| 3 |
+
"""
|
| 4 |
+
Function to load the largest Dicom series in a directory.
|
| 5 |
+
|
| 6 |
+
It scans the directory recursively search for files with the ".dcm"
|
| 7 |
+
suffix. Note that DICOM fails don't always have that suffix. In
|
| 8 |
+
that case this function will fail.
|
| 9 |
+
|
| 10 |
+
Written by David T. Chen from the National Institute of Allergy
|
| 11 |
+
and Infectious Diseases, dchen@mail.nih.gov.
|
| 12 |
+
It is covered by the Apache License, Version 2.0:
|
| 13 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
from __future__ import print_function
|
| 18 |
+
import sys
|
| 19 |
+
import os
|
| 20 |
+
import fnmatch
|
| 21 |
+
import zipfile
|
| 22 |
+
import SimpleITK as sitk
|
| 23 |
+
|
| 24 |
+
from pydicom.filereader import read_file_meta_info
|
| 25 |
+
from pydicom.errors import InvalidDicomError
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def testDicomFile(file_path):
|
| 29 |
+
"""Test if given file is in DICOM format."""
|
| 30 |
+
try:
|
| 31 |
+
read_file_meta_info(file_path)
|
| 32 |
+
return True
|
| 33 |
+
except InvalidDicomError:
|
| 34 |
+
return False
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def scanDirForDicom(dicomdir):
|
| 38 |
+
matches = []
|
| 39 |
+
dirs = []
|
| 40 |
+
try:
|
| 41 |
+
for root, dirnames, filenames in os.walk(dicomdir):
|
| 42 |
+
for filename in fnmatch.filter(filenames, "*.dcm"):
|
| 43 |
+
matches.append(os.path.join(root, filename))
|
| 44 |
+
if root not in dirs:
|
| 45 |
+
dirs.append(root)
|
| 46 |
+
except BaseException as e:
|
| 47 |
+
print("Error in scanDirForDicom: ", e)
|
| 48 |
+
print("dicomdir = ", dicomdir)
|
| 49 |
+
|
| 50 |
+
return (matches, dirs)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def getAllSeries(dirs):
|
| 54 |
+
"""Get all the Dicom series in a set of directories."""
|
| 55 |
+
isr = sitk.ImageSeriesReader()
|
| 56 |
+
seriessets = []
|
| 57 |
+
for d in dirs:
|
| 58 |
+
series = isr.GetGDCMSeriesIDs(d)
|
| 59 |
+
for s in series:
|
| 60 |
+
files = isr.GetGDCMSeriesFileNames(d, s)
|
| 61 |
+
print(s, d, len(files))
|
| 62 |
+
seriessets.append([s, d, files])
|
| 63 |
+
return seriessets
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def getModality(img):
|
| 67 |
+
"""Get an image's modality, as stored in the Dicom meta data."""
|
| 68 |
+
modality = ""
|
| 69 |
+
if (sitk.Version.MinorVersion() > 8) or (sitk.Version.MajorVersion() > 0):
|
| 70 |
+
try:
|
| 71 |
+
modality = img.GetMetaData("0008|0060")
|
| 72 |
+
except BaseException:
|
| 73 |
+
modality = ""
|
| 74 |
+
return modality
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def loadLargestSeries(dicomdir):
|
| 78 |
+
"""
|
| 79 |
+
Load the largest Dicom series it finds in a recursive scan of
|
| 80 |
+
a directory.
|
| 81 |
+
|
| 82 |
+
Largest means has the most slices. It also returns the modality
|
| 83 |
+
of the series.
|
| 84 |
+
"""
|
| 85 |
+
|
| 86 |
+
files, dirs = scanDirForDicom(dicomdir)
|
| 87 |
+
|
| 88 |
+
if (len(files) == 0) or (len(dirs) == 0):
|
| 89 |
+
print("Error in loadLargestSeries. No files found.")
|
| 90 |
+
print("dicomdir = ", dicomdir)
|
| 91 |
+
return None
|
| 92 |
+
seriessets = getAllSeries(dirs)
|
| 93 |
+
maxsize = 0
|
| 94 |
+
maxindex = -1
|
| 95 |
+
|
| 96 |
+
count = 0
|
| 97 |
+
for ss in seriessets:
|
| 98 |
+
size = len(ss[2])
|
| 99 |
+
if size > maxsize:
|
| 100 |
+
maxsize = size
|
| 101 |
+
maxindex = count
|
| 102 |
+
count = count + 1
|
| 103 |
+
if maxindex < 0:
|
| 104 |
+
print("Error: no series found")
|
| 105 |
+
return None
|
| 106 |
+
isr = sitk.ImageSeriesReader()
|
| 107 |
+
ss = seriessets[maxindex]
|
| 108 |
+
files = ss[2]
|
| 109 |
+
isr.SetFileNames(files)
|
| 110 |
+
print("\nLoading series", ss[0], "in directory", ss[1])
|
| 111 |
+
img = isr.Execute()
|
| 112 |
+
|
| 113 |
+
firstslice = sitk.ReadImage(files[0])
|
| 114 |
+
modality = getModality(firstslice)
|
| 115 |
+
|
| 116 |
+
return img, modality
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def loadZipDicom(name, tempDir):
|
| 120 |
+
"""Unzip a zipfile of dicom images into a temp directory, then
|
| 121 |
+
load the series that has the most slices.
|
| 122 |
+
"""
|
| 123 |
+
|
| 124 |
+
print("Reading Dicom zip file:", name)
|
| 125 |
+
print("tempDir = ", tempDir)
|
| 126 |
+
myzip = zipfile.ZipFile(name, "r")
|
| 127 |
+
|
| 128 |
+
try:
|
| 129 |
+
myzip.extractall(tempDir)
|
| 130 |
+
except BaseException:
|
| 131 |
+
print("Zip extract failed")
|
| 132 |
+
|
| 133 |
+
return loadLargestSeries(tempDir)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
#
|
| 137 |
+
# Main (test code)
|
| 138 |
+
#
|
| 139 |
+
|
| 140 |
+
if __name__ == "__main__":
|
| 141 |
+
print("")
|
| 142 |
+
print("dicomutils.py")
|
| 143 |
+
print(sys.argv[1])
|
| 144 |
+
|
| 145 |
+
# img = loadLargestSeries(sys.argv[1])
|
| 146 |
+
# print (img)
|
| 147 |
+
# sys.exit(0)
|
| 148 |
+
|
| 149 |
+
files, dirs = scanDirForDicom(sys.argv[1])
|
| 150 |
+
print("")
|
| 151 |
+
print("files")
|
| 152 |
+
print(files)
|
| 153 |
+
print("")
|
| 154 |
+
print("dirs")
|
| 155 |
+
print(dirs)
|
| 156 |
+
|
| 157 |
+
print("series")
|
| 158 |
+
seriessets = getAllSeries(dirs)
|
| 159 |
+
for ss in seriessets:
|
| 160 |
+
print(ss[0], " ", ss[1])
|
| 161 |
+
print(len(ss[2]))
|
| 162 |
+
print("")
|
code/dicom_stl_png_pipeline/utils/sitk2vtk.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#! /usr/bin/env python
|
| 2 |
+
|
| 3 |
+
"""
|
| 4 |
+
Function to convert a SimpleITK image to a VTK image.
|
| 5 |
+
|
| 6 |
+
Written by David T. Chen from the National Institute of Allergy
|
| 7 |
+
and Infectious Diseases, dchen@mail.nih.gov.
|
| 8 |
+
It is covered by the Apache License, Version 2.0:
|
| 9 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import SimpleITK as sitk
|
| 13 |
+
import vtk
|
| 14 |
+
from vtk.util import numpy_support
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def sitk2vtk(img, debugOn=False):
|
| 18 |
+
"""Convert a SimpleITK image to a VTK image, via numpy."""
|
| 19 |
+
|
| 20 |
+
size = list(img.GetSize())
|
| 21 |
+
origin = list(img.GetOrigin())
|
| 22 |
+
spacing = list(img.GetSpacing())
|
| 23 |
+
ncomp = img.GetNumberOfComponentsPerPixel()
|
| 24 |
+
direction = img.GetDirection()
|
| 25 |
+
|
| 26 |
+
# there doesn't seem to be a way to specify the image orientation in VTK
|
| 27 |
+
|
| 28 |
+
# convert the SimpleITK image to a numpy array
|
| 29 |
+
i2 = sitk.GetArrayFromImage(img)
|
| 30 |
+
if debugOn:
|
| 31 |
+
i2_string = i2.tostring()
|
| 32 |
+
print("data string address inside sitk2vtk", hex(id(i2_string)))
|
| 33 |
+
|
| 34 |
+
vtk_image = vtk.vtkImageData()
|
| 35 |
+
|
| 36 |
+
# VTK expects 3-dimensional parameters
|
| 37 |
+
if len(size) == 2:
|
| 38 |
+
size.append(1)
|
| 39 |
+
|
| 40 |
+
if len(origin) == 2:
|
| 41 |
+
origin.append(0.0)
|
| 42 |
+
|
| 43 |
+
if len(spacing) == 2:
|
| 44 |
+
spacing.append(spacing[0])
|
| 45 |
+
|
| 46 |
+
if len(direction) == 4:
|
| 47 |
+
direction = [
|
| 48 |
+
direction[0],
|
| 49 |
+
direction[1],
|
| 50 |
+
0.0,
|
| 51 |
+
direction[2],
|
| 52 |
+
direction[3],
|
| 53 |
+
0.0,
|
| 54 |
+
0.0,
|
| 55 |
+
0.0,
|
| 56 |
+
1.0,
|
| 57 |
+
]
|
| 58 |
+
|
| 59 |
+
vtk_image.SetDimensions(size)
|
| 60 |
+
vtk_image.SetSpacing(spacing)
|
| 61 |
+
vtk_image.SetOrigin(origin)
|
| 62 |
+
vtk_image.SetExtent(0, size[0] - 1, 0, size[1] - 1, 0, size[2] - 1)
|
| 63 |
+
|
| 64 |
+
if vtk.vtkVersion.GetVTKMajorVersion() < 9:
|
| 65 |
+
print("Warning: VTK version <9. No direction matrix.")
|
| 66 |
+
else:
|
| 67 |
+
vtk_image.SetDirectionMatrix(direction)
|
| 68 |
+
|
| 69 |
+
# depth_array = numpy_support.numpy_to_vtk(i2.ravel(), deep=True,
|
| 70 |
+
# array_type = vtktype)
|
| 71 |
+
depth_array = numpy_support.numpy_to_vtk(i2.ravel())
|
| 72 |
+
depth_array.SetNumberOfComponents(ncomp)
|
| 73 |
+
vtk_image.GetPointData().SetScalars(depth_array)
|
| 74 |
+
|
| 75 |
+
vtk_image.Modified()
|
| 76 |
+
#
|
| 77 |
+
if debugOn:
|
| 78 |
+
print("Volume object inside sitk2vtk")
|
| 79 |
+
print(vtk_image)
|
| 80 |
+
# print("type = ", vtktype)
|
| 81 |
+
print("num components = ", ncomp)
|
| 82 |
+
print(size)
|
| 83 |
+
print(origin)
|
| 84 |
+
print(spacing)
|
| 85 |
+
print(vtk_image.GetScalarComponentAsFloat(0, 0, 0, 0))
|
| 86 |
+
|
| 87 |
+
return vtk_image
|
code/dicom_stl_png_pipeline/utils/vtk2sitk.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
|
| 3 |
+
import SimpleITK as sitk
|
| 4 |
+
import vtk
|
| 5 |
+
import vtk.util.numpy_support as vtknp
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def vtk2sitk(vtkimg, debug=False):
|
| 9 |
+
"""Takes a VTK image, returns a SimpleITK image."""
|
| 10 |
+
sd = vtkimg.GetPointData().GetScalars()
|
| 11 |
+
npdata = vtknp.vtk_to_numpy(sd)
|
| 12 |
+
|
| 13 |
+
dims = list(vtkimg.GetDimensions())
|
| 14 |
+
origin = vtkimg.GetOrigin()
|
| 15 |
+
spacing = vtkimg.GetSpacing()
|
| 16 |
+
|
| 17 |
+
if debug:
|
| 18 |
+
print("dims:", dims)
|
| 19 |
+
print("origin:", origin)
|
| 20 |
+
print("spacing:", spacing)
|
| 21 |
+
|
| 22 |
+
print("numpy type:", npdata.dtype)
|
| 23 |
+
print("numpy shape:", npdata.shape)
|
| 24 |
+
|
| 25 |
+
dims.reverse()
|
| 26 |
+
npdata.shape = tuple(dims)
|
| 27 |
+
if debug:
|
| 28 |
+
print("new shape:", npdata.shape)
|
| 29 |
+
sitkimg = sitk.GetImageFromArray(npdata)
|
| 30 |
+
sitkimg.SetSpacing(spacing)
|
| 31 |
+
sitkimg.SetOrigin(origin)
|
| 32 |
+
|
| 33 |
+
if vtk.vtkVersion.GetVTKMajorVersion() >= 9:
|
| 34 |
+
direction = vtkimg.GetDirectionMatrix()
|
| 35 |
+
d = []
|
| 36 |
+
for y in range(3):
|
| 37 |
+
for x in range(3):
|
| 38 |
+
d.append(direction.GetElement(y, x))
|
| 39 |
+
sitkimg.SetDirection(d)
|
| 40 |
+
return sitkimg
|
code/dicom_stl_png_pipeline/utils/vtkutils.py
ADDED
|
@@ -0,0 +1,506 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#! /usr/bin/env python
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
"""
|
| 5 |
+
A collection of VTK functions for processing surfaces and volume.
|
| 6 |
+
|
| 7 |
+
Written by David T. Chen from the National Institute of Allergy and
|
| 8 |
+
Infectious Diseases, dchen@mail.nih.gov.
|
| 9 |
+
It is covered by the Apache License, Version 2.0:
|
| 10 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from __future__ import print_function
|
| 14 |
+
|
| 15 |
+
# import gc
|
| 16 |
+
import sys
|
| 17 |
+
import time
|
| 18 |
+
import traceback
|
| 19 |
+
|
| 20 |
+
import vtk
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def elapsedTime(start_time):
|
| 24 |
+
dt = time.perf_counter() - start_time
|
| 25 |
+
print(" %4.3f seconds" % dt)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
#
|
| 29 |
+
# Isosurface extraction
|
| 30 |
+
#
|
| 31 |
+
def extractSurface(vol, isovalue=0.0):
|
| 32 |
+
"""Extract an isosurface from a volume."""
|
| 33 |
+
try:
|
| 34 |
+
t = time.perf_counter()
|
| 35 |
+
iso = vtk.vtkContourFilter()
|
| 36 |
+
if vtk.vtkVersion.GetVTKMajorVersion() >= 6:
|
| 37 |
+
iso.SetInputData(vol)
|
| 38 |
+
else:
|
| 39 |
+
iso.SetInput(vol)
|
| 40 |
+
iso.SetValue(0, isovalue)
|
| 41 |
+
iso.Update()
|
| 42 |
+
print("Surface extracted")
|
| 43 |
+
mesh = iso.GetOutput()
|
| 44 |
+
print(" ", mesh.GetNumberOfPolys(), "polygons")
|
| 45 |
+
elapsedTime(t)
|
| 46 |
+
iso = None
|
| 47 |
+
return mesh
|
| 48 |
+
except BaseException:
|
| 49 |
+
print("Iso-surface extraction failed")
|
| 50 |
+
exc_type, exc_value, exc_traceback = sys.exc_info()
|
| 51 |
+
traceback.print_exception(
|
| 52 |
+
exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout
|
| 53 |
+
)
|
| 54 |
+
return None
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
#
|
| 58 |
+
# Mesh filtering
|
| 59 |
+
#
|
| 60 |
+
def cleanMesh(mesh, connectivityFilter=False):
|
| 61 |
+
"""Clean a mesh using VTK's CleanPolyData filter."""
|
| 62 |
+
try:
|
| 63 |
+
t = time.perf_counter()
|
| 64 |
+
connect = vtk.vtkPolyDataConnectivityFilter()
|
| 65 |
+
clean = vtk.vtkCleanPolyData()
|
| 66 |
+
|
| 67 |
+
if connectivityFilter:
|
| 68 |
+
if vtk.vtkVersion.GetVTKMajorVersion() >= 6:
|
| 69 |
+
connect.SetInputData(mesh)
|
| 70 |
+
else:
|
| 71 |
+
connect.SetInput(mesh)
|
| 72 |
+
connect.SetExtractionModeToLargestRegion()
|
| 73 |
+
clean.SetInputConnection(connect.GetOutputPort())
|
| 74 |
+
else:
|
| 75 |
+
if vtk.vtkVersion.GetVTKMajorVersion() >= 6:
|
| 76 |
+
clean.SetInputData(mesh)
|
| 77 |
+
else:
|
| 78 |
+
clean.SetInput(mesh)
|
| 79 |
+
|
| 80 |
+
clean.Update()
|
| 81 |
+
print("Surface cleaned")
|
| 82 |
+
m2 = clean.GetOutput()
|
| 83 |
+
print(" ", m2.GetNumberOfPolys(), "polygons")
|
| 84 |
+
elapsedTime(t)
|
| 85 |
+
clean = None
|
| 86 |
+
connect = None
|
| 87 |
+
return m2
|
| 88 |
+
except BaseException:
|
| 89 |
+
print("Surface cleaning failed")
|
| 90 |
+
exc_type, exc_value, exc_traceback = sys.exc_info()
|
| 91 |
+
traceback.print_exception(
|
| 92 |
+
exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout
|
| 93 |
+
)
|
| 94 |
+
return None
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def smoothMesh(mesh, nIterations=10):
|
| 98 |
+
"""Smooth a mesh using VTK's WindowedSincPolyData filter."""
|
| 99 |
+
try:
|
| 100 |
+
t = time.perf_counter()
|
| 101 |
+
smooth = vtk.vtkWindowedSincPolyDataFilter()
|
| 102 |
+
smooth.SetNumberOfIterations(nIterations)
|
| 103 |
+
if vtk.vtkVersion.GetVTKMajorVersion() >= 6:
|
| 104 |
+
smooth.SetInputData(mesh)
|
| 105 |
+
else:
|
| 106 |
+
smooth.SetInput(mesh)
|
| 107 |
+
smooth.Update()
|
| 108 |
+
print("Surface smoothed")
|
| 109 |
+
m2 = smooth.GetOutput()
|
| 110 |
+
print(" ", m2.GetNumberOfPolys(), "polygons")
|
| 111 |
+
elapsedTime(t)
|
| 112 |
+
smooth = None
|
| 113 |
+
return m2
|
| 114 |
+
except BaseException:
|
| 115 |
+
print("Surface smoothing failed")
|
| 116 |
+
exc_type, exc_value, exc_traceback = sys.exc_info()
|
| 117 |
+
traceback.print_exception(
|
| 118 |
+
exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout
|
| 119 |
+
)
|
| 120 |
+
return None
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def rotateMesh(mesh, axis=1, angle=0):
|
| 124 |
+
"""Rotate a mesh about an arbitrary axis. Angle is in degrees."""
|
| 125 |
+
try:
|
| 126 |
+
print("Rotating surface: axis=", axis, "angle=", angle)
|
| 127 |
+
matrix = vtk.vtkTransform()
|
| 128 |
+
if axis == 0:
|
| 129 |
+
matrix.RotateX(angle)
|
| 130 |
+
if axis == 1:
|
| 131 |
+
matrix.RotateY(angle)
|
| 132 |
+
if axis == 2:
|
| 133 |
+
matrix.RotateZ(angle)
|
| 134 |
+
tfilter = vtk.vtkTransformPolyDataFilter()
|
| 135 |
+
tfilter.SetTransform(matrix)
|
| 136 |
+
if vtk.vtkVersion.GetVTKMajorVersion() >= 6:
|
| 137 |
+
tfilter.SetInputData(mesh)
|
| 138 |
+
else:
|
| 139 |
+
tfilter.SetInput(mesh)
|
| 140 |
+
tfilter.Update()
|
| 141 |
+
mesh2 = tfilter.GetOutput()
|
| 142 |
+
return mesh2
|
| 143 |
+
except BaseException:
|
| 144 |
+
print("Surface rotating failed")
|
| 145 |
+
exc_type, exc_value, exc_traceback = sys.exc_info()
|
| 146 |
+
traceback.print_exception(
|
| 147 |
+
exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout
|
| 148 |
+
)
|
| 149 |
+
return None
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
# @profile
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def reduceMesh(mymesh, reductionFactor):
|
| 156 |
+
"""Reduce the number of triangles in a mesh using VTK's vtkDecimatePro
|
| 157 |
+
filter."""
|
| 158 |
+
try:
|
| 159 |
+
t = time.perf_counter()
|
| 160 |
+
# deci = vtk.vtkQuadricDecimation()
|
| 161 |
+
deci = vtk.vtkDecimatePro()
|
| 162 |
+
deci.SetTargetReduction(reductionFactor)
|
| 163 |
+
if vtk.vtkVersion.GetVTKMajorVersion() >= 6:
|
| 164 |
+
deci.SetInputData(mymesh)
|
| 165 |
+
else:
|
| 166 |
+
deci.SetInput(mymesh)
|
| 167 |
+
deci.Update()
|
| 168 |
+
print("Surface reduced")
|
| 169 |
+
m2 = deci.GetOutput()
|
| 170 |
+
del deci
|
| 171 |
+
# deci = None
|
| 172 |
+
print(" ", m2.GetNumberOfPolys(), "polygons")
|
| 173 |
+
elapsedTime(t)
|
| 174 |
+
return m2
|
| 175 |
+
except BaseException:
|
| 176 |
+
print("Surface reduction failed")
|
| 177 |
+
exc_type, exc_value, exc_traceback = sys.exc_info()
|
| 178 |
+
traceback.print_exception(
|
| 179 |
+
exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout
|
| 180 |
+
)
|
| 181 |
+
return None
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
# from https://github.com/AOT-AG/DicomToMesh/blob/master/lib/src/meshRoutines.cpp#L109
|
| 185 |
+
# MIT License
|
| 186 |
+
def removeSmallObjects(mesh, ratio):
|
| 187 |
+
"""
|
| 188 |
+
Remove small parts which are not of interest
|
| 189 |
+
@param ratio A floating-point value between 0.0 and 1.0, the higher the stronger effect
|
| 190 |
+
"""
|
| 191 |
+
|
| 192 |
+
# do nothing if ratio is 0
|
| 193 |
+
if ratio == 0:
|
| 194 |
+
return mesh
|
| 195 |
+
|
| 196 |
+
try:
|
| 197 |
+
t = time.perf_counter()
|
| 198 |
+
conn_filter = vtk.vtkPolyDataConnectivityFilter()
|
| 199 |
+
conn_filter.SetInputData(mesh)
|
| 200 |
+
conn_filter.SetExtractionModeToAllRegions()
|
| 201 |
+
conn_filter.Update()
|
| 202 |
+
|
| 203 |
+
# remove objects consisting of less than ratio vertexes of the biggest object
|
| 204 |
+
region_sizes = conn_filter.GetRegionSizes()
|
| 205 |
+
|
| 206 |
+
# find object with most vertices
|
| 207 |
+
max_size = 0
|
| 208 |
+
for i in range(conn_filter.GetNumberOfExtractedRegions()):
|
| 209 |
+
if region_sizes.GetValue(i) > max_size:
|
| 210 |
+
max_size = region_sizes.GetValue(i)
|
| 211 |
+
|
| 212 |
+
# append regions of sizes over the threshold
|
| 213 |
+
conn_filter.SetExtractionModeToSpecifiedRegions()
|
| 214 |
+
for i in range(conn_filter.GetNumberOfExtractedRegions()):
|
| 215 |
+
if region_sizes.GetValue(i) > max_size * ratio:
|
| 216 |
+
conn_filter.AddSpecifiedRegion(i)
|
| 217 |
+
|
| 218 |
+
conn_filter.Update()
|
| 219 |
+
processed_mesh = conn_filter.GetOutput()
|
| 220 |
+
print("Small parts cleaned")
|
| 221 |
+
print(" ", processed_mesh.GetNumberOfPolys(), "polygons")
|
| 222 |
+
elapsedTime(t)
|
| 223 |
+
return processed_mesh
|
| 224 |
+
|
| 225 |
+
except BaseException:
|
| 226 |
+
print("Remove small objects failed")
|
| 227 |
+
exc_type, exc_value, exc_traceback = sys.exc_info()
|
| 228 |
+
traceback.print_exception(
|
| 229 |
+
exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
#
|
| 234 |
+
# Mesh I/O
|
| 235 |
+
#
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def readMesh(name):
|
| 239 |
+
"""Read a mesh. Uses suffix to determine specific file type reader."""
|
| 240 |
+
if name.endswith(".vtk"):
|
| 241 |
+
return readVTKMesh(name)
|
| 242 |
+
if name.endswith(".ply"):
|
| 243 |
+
return readPLY(name)
|
| 244 |
+
if name.endswith(".stl"):
|
| 245 |
+
return readSTL(name)
|
| 246 |
+
print("Unknown file type: ", name)
|
| 247 |
+
return None
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def readVTKMesh(name):
|
| 251 |
+
"""Read a VTK mesh file."""
|
| 252 |
+
try:
|
| 253 |
+
reader = vtk.vtkPolyDataReader()
|
| 254 |
+
reader.SetFileName(name)
|
| 255 |
+
reader.Update()
|
| 256 |
+
print("Input mesh:", name)
|
| 257 |
+
mesh = reader.GetOutput()
|
| 258 |
+
del reader
|
| 259 |
+
# reader = None
|
| 260 |
+
return mesh
|
| 261 |
+
except BaseException:
|
| 262 |
+
print("VTK mesh reader failed")
|
| 263 |
+
exc_type, exc_value, exc_traceback = sys.exc_info()
|
| 264 |
+
traceback.print_exception(
|
| 265 |
+
exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout
|
| 266 |
+
)
|
| 267 |
+
return None
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
def readSTL(name):
|
| 271 |
+
"""Read an STL mesh file."""
|
| 272 |
+
try:
|
| 273 |
+
reader = vtk.vtkSTLReader()
|
| 274 |
+
reader.SetFileName(name)
|
| 275 |
+
reader.Update()
|
| 276 |
+
print("Input mesh:", name)
|
| 277 |
+
mesh = reader.GetOutput()
|
| 278 |
+
del reader
|
| 279 |
+
# reader = None
|
| 280 |
+
return mesh
|
| 281 |
+
except BaseException:
|
| 282 |
+
print("STL Mesh reader failed")
|
| 283 |
+
exc_type, exc_value, exc_traceback = sys.exc_info()
|
| 284 |
+
traceback.print_exception(
|
| 285 |
+
exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout
|
| 286 |
+
)
|
| 287 |
+
return None
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
def readPLY(name):
|
| 291 |
+
"""Read a PLY mesh file."""
|
| 292 |
+
try:
|
| 293 |
+
reader = vtk.vtkPLYReader()
|
| 294 |
+
reader.SetFileName(name)
|
| 295 |
+
reader.Update()
|
| 296 |
+
print("Input mesh:", name)
|
| 297 |
+
mesh = reader.GetOutput()
|
| 298 |
+
del reader
|
| 299 |
+
# reader = None
|
| 300 |
+
return mesh
|
| 301 |
+
except BaseException:
|
| 302 |
+
print("PLY Mesh reader failed")
|
| 303 |
+
exc_type, exc_value, exc_traceback = sys.exc_info()
|
| 304 |
+
traceback.print_exception(
|
| 305 |
+
exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout
|
| 306 |
+
)
|
| 307 |
+
return None
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
def writeMesh(mesh, name):
|
| 311 |
+
"""Write a mesh. Uses suffix to determine specific file type writer."""
|
| 312 |
+
print("Writing", mesh.GetNumberOfPolys(), "polygons to", name)
|
| 313 |
+
if name.endswith(".vtk"):
|
| 314 |
+
writeVTKMesh(mesh, name)
|
| 315 |
+
return
|
| 316 |
+
if name.endswith(".ply"):
|
| 317 |
+
writePLY(mesh, name)
|
| 318 |
+
return
|
| 319 |
+
if name.endswith(".stl"):
|
| 320 |
+
writeSTL(mesh, name)
|
| 321 |
+
return
|
| 322 |
+
print("Unknown file type: ", name)
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
def writeVTKMesh(mesh, name):
|
| 326 |
+
"""Write a VTK mesh file."""
|
| 327 |
+
try:
|
| 328 |
+
writer = vtk.vtkPolyDataWriter()
|
| 329 |
+
if vtk.vtkVersion.GetVTKMajorVersion() >= 6:
|
| 330 |
+
writer.SetInputData(mesh)
|
| 331 |
+
else:
|
| 332 |
+
writer.SetInput(mesh)
|
| 333 |
+
writer.SetFileTypeToBinary()
|
| 334 |
+
writer.SetFileName(name)
|
| 335 |
+
writer.Write()
|
| 336 |
+
print("Output mesh:", name)
|
| 337 |
+
writer = None
|
| 338 |
+
except BaseException:
|
| 339 |
+
print("VTK mesh writer failed")
|
| 340 |
+
exc_type, exc_value, exc_traceback = sys.exc_info()
|
| 341 |
+
traceback.print_exception(
|
| 342 |
+
exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout
|
| 343 |
+
)
|
| 344 |
+
return None
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
def writeSTL(mesh, name):
|
| 348 |
+
"""Write an STL mesh file."""
|
| 349 |
+
try:
|
| 350 |
+
writer = vtk.vtkSTLWriter()
|
| 351 |
+
if vtk.vtkVersion.GetVTKMajorVersion() >= 6:
|
| 352 |
+
print("writeSTL 1")
|
| 353 |
+
writer.SetInputData(mesh)
|
| 354 |
+
else:
|
| 355 |
+
print("writeSTL 2")
|
| 356 |
+
writer.SetInput(mesh)
|
| 357 |
+
writer.SetFileTypeToBinary()
|
| 358 |
+
writer.SetFileName(name)
|
| 359 |
+
writer.Write()
|
| 360 |
+
print("Output mesh:", name)
|
| 361 |
+
writer = None
|
| 362 |
+
except BaseException:
|
| 363 |
+
print("STL mesh writer failed")
|
| 364 |
+
exc_type, exc_value, exc_traceback = sys.exc_info()
|
| 365 |
+
traceback.print_exception(
|
| 366 |
+
exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout
|
| 367 |
+
)
|
| 368 |
+
return None
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
def writePLY(mesh, name):
|
| 372 |
+
"""Read a PLY mesh file."""
|
| 373 |
+
try:
|
| 374 |
+
writer = vtk.vtkPLYWriter()
|
| 375 |
+
if vtk.vtkVersion.GetVTKMajorVersion() >= 6:
|
| 376 |
+
writer.SetInputData(mesh)
|
| 377 |
+
else:
|
| 378 |
+
writer.SetInput(mesh)
|
| 379 |
+
writer.SetFileTypeToBinary()
|
| 380 |
+
writer.SetFileName(name)
|
| 381 |
+
writer.Write()
|
| 382 |
+
print("Output mesh:", name)
|
| 383 |
+
writer = None
|
| 384 |
+
except BaseException:
|
| 385 |
+
print("PLY mesh writer failed")
|
| 386 |
+
exc_type, exc_value, exc_traceback = sys.exc_info()
|
| 387 |
+
traceback.print_exception(
|
| 388 |
+
exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout
|
| 389 |
+
)
|
| 390 |
+
return None
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
#
|
| 394 |
+
# Volume I/O
|
| 395 |
+
#
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
def readVTKVolume(name):
|
| 399 |
+
"""Read a VTK volume image file. Returns a vtkStructuredPoints object."""
|
| 400 |
+
try:
|
| 401 |
+
reader = vtk.vtkStructuredPointsReader()
|
| 402 |
+
reader.SetFileName(name)
|
| 403 |
+
reader.Update()
|
| 404 |
+
print("Input volume:", name)
|
| 405 |
+
vol = reader.GetOutput()
|
| 406 |
+
reader = None
|
| 407 |
+
return vol
|
| 408 |
+
except BaseException:
|
| 409 |
+
print("VTK volume reader failed")
|
| 410 |
+
exc_type, exc_value, exc_traceback = sys.exc_info()
|
| 411 |
+
traceback.print_exception(
|
| 412 |
+
exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout
|
| 413 |
+
)
|
| 414 |
+
return None
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
def writeVTKVolume(vtkimg, name):
|
| 418 |
+
"""Write the old VTK Image file format"""
|
| 419 |
+
try:
|
| 420 |
+
writer = vtk.vtkStructuredPointsWriter()
|
| 421 |
+
writer.SetFileName(name)
|
| 422 |
+
writer.SetInputData(vtkimg)
|
| 423 |
+
writer.SetFileTypeToBinary()
|
| 424 |
+
writer.Update()
|
| 425 |
+
except BaseException:
|
| 426 |
+
print("VTK volume writer failed")
|
| 427 |
+
exc_type, exc_value, exc_traceback = sys.exc_info()
|
| 428 |
+
traceback.print_exception(
|
| 429 |
+
exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout
|
| 430 |
+
)
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
def readVTIVolume(name):
|
| 434 |
+
"""Read a VTK XML volume image file. Returns a vtkStructuredPoints object."""
|
| 435 |
+
try:
|
| 436 |
+
reader = vtk.vtkXMLImageDataReader()
|
| 437 |
+
reader.SetFileName(name)
|
| 438 |
+
reader.Update()
|
| 439 |
+
print("Input volume:", name)
|
| 440 |
+
vol = reader.GetOutput()
|
| 441 |
+
reader = None
|
| 442 |
+
return vol
|
| 443 |
+
except BaseException:
|
| 444 |
+
print("VTK XML volume reader failed")
|
| 445 |
+
exc_type, exc_value, exc_traceback = sys.exc_info()
|
| 446 |
+
traceback.print_exception(
|
| 447 |
+
exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout
|
| 448 |
+
)
|
| 449 |
+
return None
|
| 450 |
+
|
| 451 |
+
|
| 452 |
+
def writeVTIVolume(vtkimg, name):
|
| 453 |
+
"""Write the new XML VTK Image file format"""
|
| 454 |
+
try:
|
| 455 |
+
writer = vtk.vtkXMLImageDataWriter()
|
| 456 |
+
writer.SetFileName(name)
|
| 457 |
+
writer.SetInputData(vtkimg)
|
| 458 |
+
writer.Update()
|
| 459 |
+
except BaseException:
|
| 460 |
+
print("VTK volume writer failed")
|
| 461 |
+
exc_type, exc_value, exc_traceback = sys.exc_info()
|
| 462 |
+
traceback.print_exception(
|
| 463 |
+
exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout
|
| 464 |
+
)
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
# @profile
|
| 468 |
+
|
| 469 |
+
|
| 470 |
+
def memquery1():
|
| 471 |
+
print("Hiya 1")
|
| 472 |
+
|
| 473 |
+
|
| 474 |
+
# @profile
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
def memquery2():
|
| 478 |
+
print("Hiya 2")
|
| 479 |
+
|
| 480 |
+
|
| 481 |
+
# @profile
|
| 482 |
+
|
| 483 |
+
|
| 484 |
+
def memquery3():
|
| 485 |
+
print("Hiya 3")
|
| 486 |
+
|
| 487 |
+
|
| 488 |
+
#
|
| 489 |
+
# Main (test code)
|
| 490 |
+
#
|
| 491 |
+
if __name__ == "__main__":
|
| 492 |
+
print("vtkutils.py")
|
| 493 |
+
|
| 494 |
+
print("VTK version:", vtk.vtkVersion.GetVTKVersion())
|
| 495 |
+
print("VTK:", vtk)
|
| 496 |
+
|
| 497 |
+
try:
|
| 498 |
+
mesh = readMesh(sys.argv[1])
|
| 499 |
+
# mesh = readMesh("models/soft.stl")
|
| 500 |
+
# mesh = cleanMesh(mesh, False)
|
| 501 |
+
# mesh = smoothMesh(mesh)
|
| 502 |
+
mesh2 = reduceMesh(mesh, 0.50)
|
| 503 |
+
# writeMesh(mesh2, "soft.ply")
|
| 504 |
+
writeMesh(mesh2, sys.argv[2])
|
| 505 |
+
except BaseException:
|
| 506 |
+
print("Usage: vtkutils.py input_mesh output_mesh")
|