GimnTools 1.0.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of GimnTools might be problematic. Click here for more details.
- gimntools-1.0.0/CHANGELOG.md +88 -0
- gimntools-1.0.0/GimnTools/ImaGIMN/IO/GimnIO.py +80 -0
- gimntools-1.0.0/GimnTools/ImaGIMN/IO/MIIO.py +283 -0
- gimntools-1.0.0/GimnTools/ImaGIMN/IO/__init__.py +2 -0
- gimntools-1.0.0/GimnTools/ImaGIMN/__init__.py +6 -0
- gimntools-1.0.0/GimnTools/ImaGIMN/gimnRec/__init__.py +6 -0
- gimntools-1.0.0/GimnTools/ImaGIMN/gimnRec/backprojectors.py +132 -0
- gimntools-1.0.0/GimnTools/ImaGIMN/gimnRec/corrections.py +25 -0
- gimntools-1.0.0/GimnTools/ImaGIMN/gimnRec/projectors.py +122 -0
- gimntools-1.0.0/GimnTools/ImaGIMN/gimnRec/reconstruction_filters.py +67 -0
- gimntools-1.0.0/GimnTools/ImaGIMN/gimnRec/reconstructors/__init__.py +4 -0
- gimntools-1.0.0/GimnTools/ImaGIMN/gimnRec/reconstructors/line_integral_reconstructor.py +305 -0
- gimntools-1.0.0/GimnTools/ImaGIMN/gimnRec/reconstructors/rotation_reconstruction.py +254 -0
- gimntools-1.0.0/GimnTools/ImaGIMN/gimnRec/reconstructors/system_matrix_reconstruction.py +297 -0
- gimntools-1.0.0/GimnTools/ImaGIMN/image.py +137 -0
- gimntools-1.0.0/GimnTools/ImaGIMN/phantoms/__init__.py +3 -0
- gimntools-1.0.0/GimnTools/ImaGIMN/phantoms/derenzzo.py +253 -0
- gimntools-1.0.0/GimnTools/ImaGIMN/phantoms/geometries/__init__.py +0 -0
- gimntools-1.0.0/GimnTools/ImaGIMN/phantoms/geometries/figures.py +164 -0
- gimntools-1.0.0/GimnTools/ImaGIMN/phantoms/random.py +91 -0
- gimntools-1.0.0/GimnTools/ImaGIMN/process_root.py +296 -0
- gimntools-1.0.0/GimnTools/ImaGIMN/processing/__init__.py +5 -0
- gimntools-1.0.0/GimnTools/ImaGIMN/processing/filters/__init__.py +4 -0
- gimntools-1.0.0/GimnTools/ImaGIMN/processing/filters/frequency_filters.py +65 -0
- gimntools-1.0.0/GimnTools/ImaGIMN/processing/filters/morphological_filters.py +90 -0
- gimntools-1.0.0/GimnTools/ImaGIMN/processing/filters/spatial_filters.py +140 -0
- gimntools-1.0.0/GimnTools/ImaGIMN/processing/interpolators/__init__.py +1 -0
- gimntools-1.0.0/GimnTools/ImaGIMN/processing/interpolators/reconstruction.py +85 -0
- gimntools-1.0.0/GimnTools/ImaGIMN/processing/normalizations/__init__.py +0 -0
- gimntools-1.0.0/GimnTools/ImaGIMN/processing/ploter/__init__.py +1 -0
- gimntools-1.0.0/GimnTools/ImaGIMN/processing/ploter/ploter.py +74 -0
- gimntools-1.0.0/GimnTools/ImaGIMN/processing/tools/__init__.py +3 -0
- gimntools-1.0.0/GimnTools/ImaGIMN/processing/tools/kernels.py +133 -0
- gimntools-1.0.0/GimnTools/ImaGIMN/processing/tools/math.py +202 -0
- gimntools-1.0.0/GimnTools/ImaGIMN/processing/tools/utils.py +234 -0
- gimntools-1.0.0/GimnTools/ImaGIMN/sinogramer/__init__.py +6 -0
- gimntools-1.0.0/GimnTools/ImaGIMN/sinogramer/conf.py +32 -0
- gimntools-1.0.0/GimnTools/ImaGIMN/sinogramer/sinogramer.py +293 -0
- gimntools-1.0.0/GimnTools/ImaGIMN/sinogramer/systemSpace.py +255 -0
- gimntools-1.0.0/GimnTools/__init__.py +5 -0
- gimntools-1.0.0/GimnTools/tests/__init__.py +2 -0
- gimntools-1.0.0/GimnTools/tests/test_reconstruction.py +167 -0
- gimntools-1.0.0/GimnTools/tests/tests.py +394 -0
- gimntools-1.0.0/GimnTools.egg-info/SOURCES.txt +56 -0
- gimntools-1.0.0/LICENSE +201 -0
- gimntools-1.0.0/MANIFEST.in +55 -0
- gimntools-1.0.0/Makefile +177 -0
- gimntools-1.0.0/PKG-INFO +778 -0
- gimntools-1.0.0/README.md +692 -0
- gimntools-1.0.0/examples/Exemplos.ipynb +471 -0
- gimntools-1.0.0/examples/basic_usage.py +196 -0
- gimntools-1.0.0/pyproject.toml +3 -0
- gimntools-1.0.0/requirements-dev.txt +55 -0
- gimntools-1.0.0/requirements.txt +44 -0
- gimntools-1.0.0/scripts/build.py +0 -0
- gimntools-1.0.0/scripts/deploy.py +400 -0
- gimntools-1.0.0/scripts/install.py +295 -0
- gimntools-1.0.0/setup.cfg +4 -0
- gimntools-1.0.0/setup.py +135 -0
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
Todas as mudanças notáveis neste projeto serão documentadas neste arquivo.
|
|
4
|
+
|
|
5
|
+
O formato é baseado em [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
|
6
|
+
e este projeto adere ao [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
|
+
|
|
8
|
+
## [1.0.0] - 2024-06-19
|
|
9
|
+
|
|
10
|
+
### Adicionado
|
|
11
|
+
- Versão inicial da biblioteca GimnTools
|
|
12
|
+
- Classe `image` para manipulação de imagens médicas
|
|
13
|
+
- Módulo `sinogramer` para geração e manipulação de sinogramas
|
|
14
|
+
- Suporte para cristais monolíticos e segmentados
|
|
15
|
+
- Conversão de coordenadas de cristais
|
|
16
|
+
- Módulo `gimnRec` para reconstrução tomográfica
|
|
17
|
+
- Algoritmos MLEM, OSEM e FBP
|
|
18
|
+
- Reconstrução por integrais de linha
|
|
19
|
+
- Matriz de sistema para reconstrução
|
|
20
|
+
- Módulo `processing` para processamento de imagens
|
|
21
|
+
- Filtros espaciais com otimização Numba
|
|
22
|
+
- Filtros de frequência
|
|
23
|
+
- Filtros morfológicos
|
|
24
|
+
- Ferramentas matemáticas e kernels
|
|
25
|
+
- Sistema de visualização (ploter)
|
|
26
|
+
- Módulo `phantoms` para geração de fantomas
|
|
27
|
+
- Fantoma de Derenzo parametrizável
|
|
28
|
+
- Fantomas aleatórios
|
|
29
|
+
- Geometrias customizadas
|
|
30
|
+
- Módulo `IO` para entrada e saída
|
|
31
|
+
- Suporte completo para DICOM via SimpleITK e ITK
|
|
32
|
+
- Normalização automática de tipos de dados
|
|
33
|
+
- Preservação de metadados médicos
|
|
34
|
+
|
|
35
|
+
### Ferramentas de Desenvolvimento
|
|
36
|
+
- Script automatizado de build (`scripts/build.py`)
|
|
37
|
+
- Script de instalação (`scripts/install.py`)
|
|
38
|
+
- Script de deploy (`scripts/deploy.py`)
|
|
39
|
+
- Makefile para automação de tarefas
|
|
40
|
+
- Configuração completa do ambiente de desenvolvimento
|
|
41
|
+
|
|
42
|
+
### Documentação
|
|
43
|
+
- Documentação técnica completa em português
|
|
44
|
+
- README abrangente com exemplos
|
|
45
|
+
- Guia de instalação detalhado
|
|
46
|
+
- Exemplos práticos de uso
|
|
47
|
+
- API Reference completa
|
|
48
|
+
|
|
49
|
+
### Configuração do Projeto
|
|
50
|
+
- `setup.py` para distribuição via PyPI
|
|
51
|
+
- `pyproject.toml` com configurações modernas
|
|
52
|
+
- `requirements.txt` e `requirements-dev.txt`
|
|
53
|
+
- Configuração de ferramentas de qualidade (black, flake8, mypy)
|
|
54
|
+
- Configuração de testes com pytest
|
|
55
|
+
- Licença MIT
|
|
56
|
+
|
|
57
|
+
### Dependências
|
|
58
|
+
- numpy (≥1.20.0) - Computação numérica
|
|
59
|
+
- scipy (≥1.7.0) - Algoritmos científicos
|
|
60
|
+
- matplotlib (≥3.3.0) - Visualização
|
|
61
|
+
- numba (≥0.54.0) - Compilação JIT
|
|
62
|
+
- SimpleITK (≥2.1.0) - Processamento de imagens médicas
|
|
63
|
+
- itk (≥5.2.0) - Toolkit de imagens
|
|
64
|
+
- Pillow (≥8.0.0) - Manipulação de imagens
|
|
65
|
+
- scikit-image (≥0.18.0) - Processamento adicional
|
|
66
|
+
- h5py (≥3.1.0) - Armazenamento HDF5
|
|
67
|
+
- tqdm (≥4.60.0) - Barras de progresso
|
|
68
|
+
|
|
69
|
+
## [Unreleased]
|
|
70
|
+
|
|
71
|
+
### Planejado
|
|
72
|
+
- Implementação de algoritmos de reconstrução iterativa avançados
|
|
73
|
+
- Suporte para reconstrução 4D (temporal)
|
|
74
|
+
- Interface gráfica para visualização interativa
|
|
75
|
+
- Plugins para software de análise médica
|
|
76
|
+
- Otimizações de performance com CUDA/OpenCL
|
|
77
|
+
- Suporte para formatos adicionais (NIfTI, ANALYZE)
|
|
78
|
+
- Documentação em inglês
|
|
79
|
+
- Tutoriais em vídeo
|
|
80
|
+
- API REST para processamento em nuvem
|
|
81
|
+
|
|
82
|
+
### Em Consideração
|
|
83
|
+
- Integração com ITK-SNAP
|
|
84
|
+
- Suporte para processamento distribuído
|
|
85
|
+
- Interface com MATLAB
|
|
86
|
+
- Bindings para R
|
|
87
|
+
- Containerização Docker
|
|
88
|
+
- Deployment em Kubernetes
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import os
|
|
3
|
+
import sys
|
|
4
|
+
|
|
5
|
+
class GimnIO:
|
|
6
|
+
|
|
7
|
+
def __init__ (self):
|
|
8
|
+
pass
|
|
9
|
+
|
|
10
|
+
@staticmethod
|
|
11
|
+
def check_and_create_folder(folder_path):
|
|
12
|
+
"""
|
|
13
|
+
@brief Checks if a folder exists at the specified path and creates it if it does not exist.
|
|
14
|
+
This function verifies whether the folder at the given path exists. If the folder does not exist,
|
|
15
|
+
it creates the folder and prints a success message. If the folder already exists, it prints a message
|
|
16
|
+
indicating so.
|
|
17
|
+
@param folder_path (str): The path to the folder to be checked or created.
|
|
18
|
+
@return str: The path to the checked or newly created folder.
|
|
19
|
+
"""
|
|
20
|
+
if not os.path.exists(folder_path):
|
|
21
|
+
os.makedirs(folder_path)
|
|
22
|
+
print(f"A pasta '{folder_path}' foi criada com sucesso.")
|
|
23
|
+
else:
|
|
24
|
+
print(f"A pasta '{folder_path}' já existe.")
|
|
25
|
+
|
|
26
|
+
return folder_path
|
|
27
|
+
|
|
28
|
+
@staticmethod
|
|
29
|
+
def read_json(file_name):
|
|
30
|
+
"""
|
|
31
|
+
@brief Reads a JSON file and returns its contents as a dictionary.
|
|
32
|
+
|
|
33
|
+
@param file_name The path to the JSON file to be read.
|
|
34
|
+
|
|
35
|
+
@return dict The contents of the JSON file as a Python dictionary.
|
|
36
|
+
|
|
37
|
+
@exception FileNotFoundError If the specified file does not exist.
|
|
38
|
+
@exception json.JSONDecodeError If the file is not a valid JSON.
|
|
39
|
+
|
|
40
|
+
@note This function assumes the file contains valid JSON data.
|
|
41
|
+
"""
|
|
42
|
+
with open(file_name, 'r') as file:
|
|
43
|
+
dic = json.load(file)
|
|
44
|
+
return dic
|
|
45
|
+
|
|
46
|
+
@staticmethod
|
|
47
|
+
def save_json(file_name,dict):
|
|
48
|
+
"""
|
|
49
|
+
@brief Saves a dictionary to a JSON file.
|
|
50
|
+
|
|
51
|
+
This function writes the contents of a dictionary to a file in JSON format.
|
|
52
|
+
It handles values of type str, float, int, list, and numpy.ndarray. Numpy arrays are converted to lists before saving.
|
|
53
|
+
|
|
54
|
+
@param file_name The path to the file where the JSON data will be saved.
|
|
55
|
+
@param dict The dictionary containing data to be saved.
|
|
56
|
+
|
|
57
|
+
@note This function does not use the built-in json module and may not handle all edge cases of JSON serialization.
|
|
58
|
+
"""
|
|
59
|
+
with open(file_name,'w') as file:
|
|
60
|
+
file.write("{\n")
|
|
61
|
+
counter = 0
|
|
62
|
+
items = len(dict)
|
|
63
|
+
for key,value in dict.items():
|
|
64
|
+
if isinstance(value,str):
|
|
65
|
+
file.write(f'\t"{key}":"{value}"')
|
|
66
|
+
elif isinstance(value,float):
|
|
67
|
+
file.write(f'\t"{key}":{value}')
|
|
68
|
+
elif isinstance(value,list):
|
|
69
|
+
file.write(f'\t"{key}":{value}')
|
|
70
|
+
elif isinstance(value,np.ndarray):
|
|
71
|
+
a=value.tolist()
|
|
72
|
+
file.write(f'\t"{key}":{a}')
|
|
73
|
+
elif isinstance(value,int):
|
|
74
|
+
file.write(f'\t"{key}":{value}')
|
|
75
|
+
if counter<items-1:
|
|
76
|
+
file.write(",\n")
|
|
77
|
+
else:
|
|
78
|
+
file.write("\n")
|
|
79
|
+
counter+=1
|
|
80
|
+
file.write("}")
|
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
import SimpleITK as sitk
|
|
2
|
+
import numpy as np
|
|
3
|
+
import itk
|
|
4
|
+
import time
|
|
5
|
+
from GimnTools.ImaGIMN.IO.GimnIO import GimnIO
|
|
6
|
+
from copy import deepcopy
|
|
7
|
+
import os
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class MIIO:
|
|
12
|
+
"""
|
|
13
|
+
@class MIIO
|
|
14
|
+
@brief A class for handling DICOM image input and output operations.
|
|
15
|
+
|
|
16
|
+
The `MIIO` class provides methods to read, write, and manipulate DICOM images,
|
|
17
|
+
including normalization and metadata handling.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
def __init__(self):
|
|
21
|
+
"""
|
|
22
|
+
@brief Initializes the MIIO class.
|
|
23
|
+
|
|
24
|
+
This constructor does not take any parameters and initializes the class.
|
|
25
|
+
"""
|
|
26
|
+
pass
|
|
27
|
+
|
|
28
|
+
@staticmethod
|
|
29
|
+
def renormalize(image, dtype):
|
|
30
|
+
"""
|
|
31
|
+
@brief Renormalizes the input image to the specified data type.
|
|
32
|
+
|
|
33
|
+
This method normalizes each slice of the input image to fit within the
|
|
34
|
+
range of the specified data type.
|
|
35
|
+
|
|
36
|
+
@param image A 3D numpy array representing the image to be normalized.
|
|
37
|
+
@param dtype The desired data type to which the image should be cast.
|
|
38
|
+
|
|
39
|
+
@return A tuple containing the normalized image and a dictionary with
|
|
40
|
+
regression parameters (slope and intercept).
|
|
41
|
+
"""
|
|
42
|
+
image = deepcopy(image)
|
|
43
|
+
slices = np.shape(image)[0]
|
|
44
|
+
normalized = np.zeros_like(image).astype(dtype)
|
|
45
|
+
regression = {"slope": [], "intercept": []}
|
|
46
|
+
|
|
47
|
+
for slc in range(slices):
|
|
48
|
+
min_value = image[slc].min()
|
|
49
|
+
max_value = image[slc].max()
|
|
50
|
+
rescale_slope = (max_value - min_value) / np.iinfo(dtype).max
|
|
51
|
+
rescale_intercept = min_value
|
|
52
|
+
|
|
53
|
+
normalized[slc] = ((image[slc] - min_value) / rescale_slope).astype(dtype)
|
|
54
|
+
regression['slope'].append(float(rescale_slope))
|
|
55
|
+
regression['intercept'].append(float(rescale_intercept))
|
|
56
|
+
|
|
57
|
+
return normalized, regression
|
|
58
|
+
|
|
59
|
+
@staticmethod
|
|
60
|
+
def save_dicom(image, nome_arquivo, origin=(0, 0, 0), spacing=(1.0, 1.0, 1.0), save_json=True):
|
|
61
|
+
"""
|
|
62
|
+
@brief Saves a numpy array as a DICOM file.
|
|
63
|
+
|
|
64
|
+
This method normalizes the image, sets the necessary metadata, and
|
|
65
|
+
saves the image as a DICOM file.
|
|
66
|
+
|
|
67
|
+
@param image A 3D numpy array representing the image to save.
|
|
68
|
+
@param nome_arquivo The filename (including path) to save the DICOM file.
|
|
69
|
+
@param origin A tuple representing the origin of the image.
|
|
70
|
+
@param spacing A tuple representing the spacing of the image.
|
|
71
|
+
@param save_json A boolean indicating whether to save regression data as JSON.
|
|
72
|
+
"""
|
|
73
|
+
# Normalize the float values to uint16 range and cast to uint16
|
|
74
|
+
image, regression = MIIO.renormalize(image, np.uint16)
|
|
75
|
+
image = sitk.GetImageFromArray(image)
|
|
76
|
+
|
|
77
|
+
folder_path = GimnIO.check_and_create_folder(nome_arquivo)
|
|
78
|
+
name = nome_arquivo.split(sep="/")[-1]
|
|
79
|
+
nome_arquivo = folder_path + "/" + name
|
|
80
|
+
|
|
81
|
+
print("NOME DO ARQUIVO", nome_arquivo)
|
|
82
|
+
print(folder_path)
|
|
83
|
+
|
|
84
|
+
# Define origin and spacing
|
|
85
|
+
image.SetOrigin(origin)
|
|
86
|
+
image.SetSpacing(spacing)
|
|
87
|
+
|
|
88
|
+
# Fill in necessary metadata
|
|
89
|
+
image.SetMetaData("0010|0010", "Nome do Paciente") # Patient Name
|
|
90
|
+
image.SetMetaData("0008|0060", "CT") # Modality
|
|
91
|
+
image.SetMetaData("0008|103e", "Descrição da Série") # Series Description
|
|
92
|
+
image.SetMetaData("0028|0004", "MONOCHROME2") # Photometric Interpretation
|
|
93
|
+
image.SetMetaData("0028|0100", str(16)) # Bits Allocated
|
|
94
|
+
image.SetMetaData("0028|0101", str(16)) # Bits Stored
|
|
95
|
+
image.SetMetaData("0028|0102", str(15)) # High Bit
|
|
96
|
+
image.SetMetaData("0028|0103", str(0)) # Pixel Representation (0 for unsigned)
|
|
97
|
+
|
|
98
|
+
if save_json:
|
|
99
|
+
json_name = nome_arquivo + ".json"
|
|
100
|
+
GimnIO.save_json(json_name, regression)
|
|
101
|
+
|
|
102
|
+
# Save the image as a DICOM file
|
|
103
|
+
writer = sitk.ImageFileWriter()
|
|
104
|
+
writer.SetFileName(f"{nome_arquivo}.dcm")
|
|
105
|
+
writer.Execute(image)
|
|
106
|
+
|
|
107
|
+
@staticmethod
|
|
108
|
+
def read_dicom(folder_name, use_json=False):
|
|
109
|
+
"""
|
|
110
|
+
@brief Reads a DICOM file from the specified folder.
|
|
111
|
+
|
|
112
|
+
This method reads a DICOM file and returns the image data along with
|
|
113
|
+
its origin and spacing.
|
|
114
|
+
|
|
115
|
+
@param folder_name The folder containing the DICOM file.
|
|
116
|
+
@param use_json A boolean indicating whether to use regression data from JSON.
|
|
117
|
+
|
|
118
|
+
@return A tuple containing the numpy array of the image, origin, and spacing.
|
|
119
|
+
"""
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
file_name = folder_name + "/" + folder_name.split(sep="/")[-1]
|
|
123
|
+
image = sitk.ReadImage(f"{file_name}.dcm")
|
|
124
|
+
np_matrix = sitk.GetArrayFromImage(image).astype(np.float32)
|
|
125
|
+
|
|
126
|
+
if use_json:
|
|
127
|
+
regression = GimnIO.read_json(f"{file_name}.json")
|
|
128
|
+
slices, height, width = np_matrix.shape
|
|
129
|
+
|
|
130
|
+
# Renormalize to the pixel value
|
|
131
|
+
for slc in range(slices):
|
|
132
|
+
np_matrix[slc] = np_matrix[slc] * regression['slope'][slc] + regression['intercept'][slc]
|
|
133
|
+
|
|
134
|
+
origin = image.GetOrigin()
|
|
135
|
+
spacing = image.GetSpacing()
|
|
136
|
+
|
|
137
|
+
return np_matrix, origin, spacing
|
|
138
|
+
|
|
139
|
+
@staticmethod
|
|
140
|
+
def save_series(image, out_dir, origin=[0, 0, 0], spacing=[1, 1, 1], pixel_dtype=np.uint16, save_json=False):
|
|
141
|
+
"""
|
|
142
|
+
@brief Saves a series of images as DICOM files.
|
|
143
|
+
|
|
144
|
+
This method normalizes the image series and saves each slice as a
|
|
145
|
+
separate DICOM file.
|
|
146
|
+
|
|
147
|
+
@param image A 4D numpy array representing the image series.
|
|
148
|
+
@param out_dir The output directory where the DICOM files will be saved.
|
|
149
|
+
@param origin A list representing the origin of the image.
|
|
150
|
+
@param spacing A list representing the spacing of the image.
|
|
151
|
+
@param pixel_dtype The desired data type for the pixel values.
|
|
152
|
+
@param save_json A boolean indicating whether to save regression data as JSON.
|
|
153
|
+
"""
|
|
154
|
+
out_dir = out_dir + "_series"
|
|
155
|
+
GimnIO.check_and_create_folder(out_dir)
|
|
156
|
+
|
|
157
|
+
normalized_data, regression = MIIO.renormalize(image, pixel_dtype)
|
|
158
|
+
|
|
159
|
+
if save_json:
|
|
160
|
+
file_name = out_dir.split(sep="/")[-1]
|
|
161
|
+
json_name = out_dir + '/' + file_name + ".json"
|
|
162
|
+
GimnIO.save_json(json_name, regression)
|
|
163
|
+
|
|
164
|
+
new_img = sitk.GetImageFromArray(normalized_data)
|
|
165
|
+
new_img.SetSpacing(spacing)
|
|
166
|
+
new_img.SetOrigin(origin)
|
|
167
|
+
|
|
168
|
+
writer = sitk.ImageFileWriter()
|
|
169
|
+
writer.KeepOriginalImageUIDOn()
|
|
170
|
+
|
|
171
|
+
modification_time = time.strftime("%H%M%S")
|
|
172
|
+
modification_date = time.strftime("%Y%m%d")
|
|
173
|
+
direction = new_img.GetDirection()
|
|
174
|
+
|
|
175
|
+
series_tag_values = [
|
|
176
|
+
("0008|0031", modification_time), # Series Time
|
|
177
|
+
("0008|0021", modification_date), # Series Date
|
|
178
|
+
("0008|0008", "DERIVED\\SECONDARY"), # Image Type
|
|
179
|
+
("0020|000e", "1.2.826.0.1.3680043.2.1125." + modification_date + ".1" + modification_time), # Series Instance UID
|
|
180
|
+
("0020|0037", "\\".join(map(str, direction))), # Image Orientation
|
|
181
|
+
("0008|103e", "Created-SimpleITK") # Series Description
|
|
182
|
+
]
|
|
183
|
+
|
|
184
|
+
# Write slices to output directory
|
|
185
|
+
for i in range(new_img.GetDepth()):
|
|
186
|
+
MIIO.writeSlices(series_tag_values, new_img, out_dir, i)
|
|
187
|
+
|
|
188
|
+
@staticmethod
|
|
189
|
+
def writeSlices(series_tag_values, new_img, out_dir, i):
|
|
190
|
+
"""
|
|
191
|
+
@brief Writes a single slice of the image to a DICOM file.
|
|
192
|
+
|
|
193
|
+
This method sets the metadata for the slice and saves it as a DICOM file.
|
|
194
|
+
|
|
195
|
+
@param series_tag_values A list of tuples containing the series metadata.
|
|
196
|
+
@param new_img The new image object containing the slice data.
|
|
197
|
+
@param out_dir The output directory where the DICOM file will be saved.
|
|
198
|
+
@param i The index of the slice to be written.
|
|
199
|
+
"""
|
|
200
|
+
image_slice = new_img[:, :, i]
|
|
201
|
+
|
|
202
|
+
list(
|
|
203
|
+
map(
|
|
204
|
+
lambda tag_value: image_slice.SetMetaData(tag_value[0], tag_value[1]),
|
|
205
|
+
series_tag_values,
|
|
206
|
+
)
|
|
207
|
+
)
|
|
208
|
+
|
|
209
|
+
# Slice specific tags
|
|
210
|
+
image_slice.SetMetaData("0008|0012", time.strftime("%Y%m%d")) # Instance Creation Date
|
|
211
|
+
image_slice.SetMetaData("0008|0013", time.strftime("%H%M%S")) # Instance Creation Time
|
|
212
|
+
image_slice.SetMetaData("0008|0060", "CT") # Modality
|
|
213
|
+
image_slice.SetMetaData("0020|0013", str(i)) # Instance Number
|
|
214
|
+
|
|
215
|
+
writer = sitk.ImageFileWriter()
|
|
216
|
+
writer.SetFileName(os.path.join(out_dir, str(i) + ".dcm"))
|
|
217
|
+
writer.Execute(image_slice)
|
|
218
|
+
|
|
219
|
+
@staticmethod
|
|
220
|
+
def read_series(path_to_folder, pixel_type, use_json=False):
|
|
221
|
+
"""
|
|
222
|
+
@brief Reads a series of DICOM images from the specified folder.
|
|
223
|
+
|
|
224
|
+
This method reads all DICOM files in the specified folder and
|
|
225
|
+
returns a numpy array of the image series.
|
|
226
|
+
|
|
227
|
+
@param path_to_folder The path to the folder containing the DICOM series.
|
|
228
|
+
@param pixel_type The desired pixel type for the images.
|
|
229
|
+
@param use_json A boolean indicating whether to use regression data from JSON.
|
|
230
|
+
|
|
231
|
+
@return A numpy array representing the image series.
|
|
232
|
+
"""
|
|
233
|
+
if use_json:
|
|
234
|
+
file_name = path_to_folder.split(sep="/")[-1]
|
|
235
|
+
json_name = path_to_folder + '/' + file_name + ".json"
|
|
236
|
+
regression = GimnIO.read_json(json_name)
|
|
237
|
+
|
|
238
|
+
PixelType = pixel_type
|
|
239
|
+
Dimension = 3
|
|
240
|
+
ImageType = itk.Image[PixelType, Dimension]
|
|
241
|
+
|
|
242
|
+
dirName = path_to_folder
|
|
243
|
+
namesGenerator = itk.GDCMSeriesFileNames.New()
|
|
244
|
+
namesGenerator.SetUseSeriesDetails(True)
|
|
245
|
+
namesGenerator.AddSeriesRestriction("0008|0021")
|
|
246
|
+
namesGenerator.SetGlobalWarningDisplay(False)
|
|
247
|
+
namesGenerator.SetDirectory(dirName)
|
|
248
|
+
|
|
249
|
+
seriesUID = namesGenerator.GetSeriesUIDs()
|
|
250
|
+
|
|
251
|
+
if len(seriesUID) < 1:
|
|
252
|
+
print("No DICOMs in: " + dirName)
|
|
253
|
+
sys.exit(1)
|
|
254
|
+
|
|
255
|
+
print("The directory: " + dirName)
|
|
256
|
+
print("Contains the following DICOM Series: ")
|
|
257
|
+
|
|
258
|
+
for uid in seriesUID:
|
|
259
|
+
print(uid)
|
|
260
|
+
|
|
261
|
+
seriesIdentifier = uid
|
|
262
|
+
fileNames = namesGenerator.GetFileNames(seriesIdentifier)
|
|
263
|
+
|
|
264
|
+
reader = itk.ImageSeriesReader[ImageType].New()
|
|
265
|
+
dicomIO = itk.GDCMImageIO.New()
|
|
266
|
+
reader.SetImageIO(dicomIO)
|
|
267
|
+
reader.SetFileNames(fileNames)
|
|
268
|
+
reader.ForceOrthogonalDirectionOff()
|
|
269
|
+
reader.Update()
|
|
270
|
+
|
|
271
|
+
image_itk = reader.GetOutput()
|
|
272
|
+
np_array = itk.array_view_from_image(image_itk)
|
|
273
|
+
slices, height, width = np_array.shape
|
|
274
|
+
|
|
275
|
+
# Renormalize to the pixel value
|
|
276
|
+
if use_json:
|
|
277
|
+
try:
|
|
278
|
+
for slc in range(slices):
|
|
279
|
+
np_array[slc] = np_array[slc] * regression['slope'][slc] + regression['intercept'][slc]
|
|
280
|
+
except:
|
|
281
|
+
print(f"Error reading json, check if the file {json_name} exists")
|
|
282
|
+
|
|
283
|
+
return np_array
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
from GimnTools.ImaGIMN.gimnRec import reconstructors
|
|
2
|
+
from GimnTools.ImaGIMN.gimnRec.projectors import *
|
|
3
|
+
from GimnTools.ImaGIMN.gimnRec.backprojectors import *
|
|
4
|
+
from GimnTools.ImaGIMN.gimnRec.corrections import *
|
|
5
|
+
from GimnTools.ImaGIMN.gimnRec.reconstruction_filters import *
|
|
6
|
+
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
from scipy.ndimage import rotate as rt_scipy
|
|
3
|
+
from numba import njit
|
|
4
|
+
from GimnTools.ImaGIMN.processing.tools.math import rotate
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def iradon_m(sinogram, interpolator, angles, center=None):
|
|
8
|
+
"""
|
|
9
|
+
Performs image reconstruction from a sinogram using the filtered backprojection method.
|
|
10
|
+
|
|
11
|
+
@param sinogram (numpy.ndarray): Input sinogram.
|
|
12
|
+
@param interpolator (function): Interpolation function to be used.
|
|
13
|
+
@param angles (numpy.ndarray): Angles corresponding to the projections of the sinogram.
|
|
14
|
+
@param center (tuple, optional): Center of the image (default is the center of the image).
|
|
15
|
+
|
|
16
|
+
@return Reconstructed image.
|
|
17
|
+
"""
|
|
18
|
+
size = sinogram.shape[0]
|
|
19
|
+
angle_n = angles
|
|
20
|
+
|
|
21
|
+
out = np.zeros([size, size])
|
|
22
|
+
aux = np.zeros([size, size])
|
|
23
|
+
|
|
24
|
+
for i, angle in enumerate(angle_n):
|
|
25
|
+
col = sinogram[:, i]
|
|
26
|
+
aux[:, 0:size] = col
|
|
27
|
+
out += rotate(aux, angle - 90, interpolator, center=center)
|
|
28
|
+
out = out / size
|
|
29
|
+
return np.flip(out, axis=1)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def backprojector(sinogram, angles, interpolator, center=None):
|
|
33
|
+
"""
|
|
34
|
+
Performs backprojection of a sinogram to reconstruct the image.
|
|
35
|
+
|
|
36
|
+
@param sinogram (numpy.ndarray): Input sinogram.
|
|
37
|
+
@param angles (numpy.ndarray): Angles corresponding to the projections of the sinogram.
|
|
38
|
+
@param interpolator (function): Interpolation function to be used.
|
|
39
|
+
@param center (tuple, optional): Center of the image (default is the center of the image).
|
|
40
|
+
|
|
41
|
+
@return Reconstructed image.
|
|
42
|
+
"""
|
|
43
|
+
size = sinogram.shape[0]
|
|
44
|
+
|
|
45
|
+
out = np.zeros([size, size])
|
|
46
|
+
aux = np.zeros([size, size])
|
|
47
|
+
|
|
48
|
+
for i, angle in enumerate(angles):
|
|
49
|
+
col = sinogram[:, i]
|
|
50
|
+
aux[:, 0:size] = col
|
|
51
|
+
out += rotate(aux, angle - 90, interpolator, center=center)
|
|
52
|
+
|
|
53
|
+
#out += rotate(aux, angle - (np.pi / 2.0), interpolator, center=center)
|
|
54
|
+
out = out / size
|
|
55
|
+
return np.flip(out, axis=1)
|
|
56
|
+
|
|
57
|
+
#(parallel=True)
|
|
58
|
+
#
|
|
59
|
+
# Quando estamos trabalhando com parallel=True irá demorar muito mais
|
|
60
|
+
@njit
|
|
61
|
+
def inverse_radon(sinogram, angles):
|
|
62
|
+
"""
|
|
63
|
+
@brief Reconstructs an image from its sinogram using the inverse backprojection method.
|
|
64
|
+
This function implements the inverse backprojection (Inverse Radon Transform) to reconstruct a two-dimensional image
|
|
65
|
+
from its sinogram, using a list of projection angles. For each pixel of the output image, the function
|
|
66
|
+
sums the contributions from all projections, interpolating values from the sinogram when necessary.
|
|
67
|
+
@param sinogram (np.ndarray): 2D matrix representing the sinogram, where each column corresponds to a projection at a specific angle.
|
|
68
|
+
@param angles (np.ndarray): 1D vector containing the angles (in degrees) of the projections present in the sinogram.
|
|
69
|
+
@return np.ndarray: Image reconstructed from the sinogram, with the same size as the vertical dimension of the sinogram.
|
|
70
|
+
@note
|
|
71
|
+
- The function assumes that the output image is square and that the number of rows in the sinogram matches the image size.
|
|
72
|
+
- Linear interpolation is used for non-integer values when accessing the sinogram.
|
|
73
|
+
- Normalization is performed by the ratio between the largest angle (in radians) and the number of angles.
|
|
74
|
+
"""
|
|
75
|
+
nb_angles = sinogram.shape[1] # Número de ângulos (largura do sinograma)
|
|
76
|
+
size = sinogram.shape[0] # Tamanho da imagem (altura e largura)
|
|
77
|
+
|
|
78
|
+
# Inicializa a matriz de saída
|
|
79
|
+
reconstructed_image = np.zeros((size, size), dtype=np.float64)
|
|
80
|
+
center = (size - 1) / 2 # Centro da imagem
|
|
81
|
+
|
|
82
|
+
# Loop sobre cada pixel da imagem de saída
|
|
83
|
+
for i in range(size):
|
|
84
|
+
for j in range(size):
|
|
85
|
+
sum_value = 0.0
|
|
86
|
+
for k in range(nb_angles):
|
|
87
|
+
angle = np.deg2rad(angles[k]-90)
|
|
88
|
+
cos_angle = np.cos(angle) # Coseno do ângulo k
|
|
89
|
+
sin_angle = np.sin(angle) # Seno do ângulo k
|
|
90
|
+
|
|
91
|
+
S = ((j-center)*cos_angle + (i-center)* sin_angle)+center
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
# Pega a coluna k do sinograma
|
|
95
|
+
col_sin = sinogram[:,k ]
|
|
96
|
+
|
|
97
|
+
# Se V não for inteiro, faz interpolação
|
|
98
|
+
if S< 0 or S >= len(col_sin):
|
|
99
|
+
continue # Ignora se V estiver fora dos limites
|
|
100
|
+
|
|
101
|
+
if S - int(S) != 0:
|
|
102
|
+
inter = get_interpolated_pixel_1d(col_sin, S)
|
|
103
|
+
sum_value += inter
|
|
104
|
+
else:
|
|
105
|
+
sum_value += col_sin[int(S)]
|
|
106
|
+
|
|
107
|
+
# Normaliza a soma sobre todos os ângulos
|
|
108
|
+
reconstructed_image[i, j] = sum_value * (np.deg2rad(angles.max())/ nb_angles)
|
|
109
|
+
|
|
110
|
+
return reconstructed_image
|
|
111
|
+
|
|
112
|
+
@njit
|
|
113
|
+
def get_interpolated_pixel_1d(vector, t):
|
|
114
|
+
"""
|
|
115
|
+
@brief Performs 1D linear interpolation for a value t between the indices of a vector.
|
|
116
|
+
This function calculates the linearly interpolated value between two adjacent elements of a vector,
|
|
117
|
+
given a fractional index t. If t is out of the vector bounds, it returns 0.0.
|
|
118
|
+
@param vector Input vector (1D array) containing the values to be interpolated.
|
|
119
|
+
@param t Fractional index (float) for which the interpolated value will be calculated.
|
|
120
|
+
@return Interpolated value corresponding to index t. Returns 0.0 if t is out of the vector bounds.
|
|
121
|
+
"""
|
|
122
|
+
tt = int(t)
|
|
123
|
+
|
|
124
|
+
if tt < 0 or tt + 1 >= len(vector):
|
|
125
|
+
return 0.0 # Retorna zero se estiver fora dos limites
|
|
126
|
+
|
|
127
|
+
T = t - tt
|
|
128
|
+
|
|
129
|
+
# Interpolação linear entre os valores adjacentes de vector
|
|
130
|
+
interpolated = (vector[tt + 1] - vector[tt]) * T + vector[tt]
|
|
131
|
+
|
|
132
|
+
return interpolated
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
from scipy.fft import rfft
|
|
3
|
+
from scipy.ndimage import gaussian_filter
|
|
4
|
+
|
|
5
|
+
from scipy.ndimage import rotate
|
|
6
|
+
|
|
7
|
+
def rot_center(theta):
|
|
8
|
+
"""
|
|
9
|
+
@brief Calculates the center of rotation (COR) of a sinogram.
|
|
10
|
+
This function computes the center of rotation from a 2D sinogram array by analyzing its Fourier transform.
|
|
11
|
+
@param thetasum (array-like)
|
|
12
|
+
The 2D sinogram array with dimensions (z, theta).
|
|
13
|
+
@return float
|
|
14
|
+
The calculated center of rotation (COR).
|
|
15
|
+
@details
|
|
16
|
+
The function applies a real-valued Fast Fourier Transform (rFFT) to the flattened input array,
|
|
17
|
+
extracts the real and imaginary parts at a specific frequency, computes the phase, and then
|
|
18
|
+
determines the center of rotation based on the phase information.
|
|
19
|
+
"""
|
|
20
|
+
T = rfft(theta.ravel())
|
|
21
|
+
imag = T[theta.shape[0]].imag
|
|
22
|
+
real = T[theta.shape[0]].real
|
|
23
|
+
phase = np.arctan2(imag*np.sign(real), real*np.sign(real))
|
|
24
|
+
COR = theta.shape[-1]/2-phase*theta.shape[-1]/(2*np.pi)
|
|
25
|
+
return COR
|