GimnTools 1.0.0__py3-none-any.whl

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.

Files changed (48) hide show
  1. GimnTools/ImaGIMN/IO/GimnIO.py +80 -0
  2. GimnTools/ImaGIMN/IO/MIIO.py +283 -0
  3. GimnTools/ImaGIMN/IO/__init__.py +2 -0
  4. GimnTools/ImaGIMN/__init__.py +6 -0
  5. GimnTools/ImaGIMN/gimnRec/__init__.py +6 -0
  6. GimnTools/ImaGIMN/gimnRec/backprojectors.py +132 -0
  7. GimnTools/ImaGIMN/gimnRec/corrections.py +25 -0
  8. GimnTools/ImaGIMN/gimnRec/projectors.py +122 -0
  9. GimnTools/ImaGIMN/gimnRec/reconstruction_filters.py +67 -0
  10. GimnTools/ImaGIMN/gimnRec/reconstructors/__init__.py +4 -0
  11. GimnTools/ImaGIMN/gimnRec/reconstructors/line_integral_reconstructor.py +305 -0
  12. GimnTools/ImaGIMN/gimnRec/reconstructors/rotation_reconstruction.py +254 -0
  13. GimnTools/ImaGIMN/gimnRec/reconstructors/system_matrix_reconstruction.py +297 -0
  14. GimnTools/ImaGIMN/image.py +137 -0
  15. GimnTools/ImaGIMN/phantoms/__init__.py +3 -0
  16. GimnTools/ImaGIMN/phantoms/derenzzo.py +253 -0
  17. GimnTools/ImaGIMN/phantoms/geometries/__init__.py +0 -0
  18. GimnTools/ImaGIMN/phantoms/geometries/figures.py +164 -0
  19. GimnTools/ImaGIMN/phantoms/random.py +91 -0
  20. GimnTools/ImaGIMN/process_root.py +296 -0
  21. GimnTools/ImaGIMN/processing/__init__.py +5 -0
  22. GimnTools/ImaGIMN/processing/filters/__init__.py +4 -0
  23. GimnTools/ImaGIMN/processing/filters/frequency_filters.py +65 -0
  24. GimnTools/ImaGIMN/processing/filters/morphological_filters.py +90 -0
  25. GimnTools/ImaGIMN/processing/filters/spatial_filters.py +140 -0
  26. GimnTools/ImaGIMN/processing/interpolators/__init__.py +1 -0
  27. GimnTools/ImaGIMN/processing/interpolators/reconstruction.py +85 -0
  28. GimnTools/ImaGIMN/processing/normalizations/__init__.py +0 -0
  29. GimnTools/ImaGIMN/processing/ploter/__init__.py +1 -0
  30. GimnTools/ImaGIMN/processing/ploter/ploter.py +74 -0
  31. GimnTools/ImaGIMN/processing/tools/__init__.py +3 -0
  32. GimnTools/ImaGIMN/processing/tools/kernels.py +133 -0
  33. GimnTools/ImaGIMN/processing/tools/math.py +202 -0
  34. GimnTools/ImaGIMN/processing/tools/utils.py +234 -0
  35. GimnTools/ImaGIMN/sinogramer/__init__.py +6 -0
  36. GimnTools/ImaGIMN/sinogramer/conf.py +32 -0
  37. GimnTools/ImaGIMN/sinogramer/sinogramer.py +293 -0
  38. GimnTools/ImaGIMN/sinogramer/systemSpace.py +255 -0
  39. GimnTools/__init__.py +5 -0
  40. GimnTools/tests/__init__.py +2 -0
  41. GimnTools/tests/test_reconstruction.py +167 -0
  42. GimnTools/tests/tests.py +394 -0
  43. gimntools-1.0.0.dist-info/METADATA +778 -0
  44. gimntools-1.0.0.dist-info/RECORD +48 -0
  45. gimntools-1.0.0.dist-info/WHEEL +5 -0
  46. gimntools-1.0.0.dist-info/entry_points.txt +4 -0
  47. gimntools-1.0.0.dist-info/licenses/LICENSE +201 -0
  48. gimntools-1.0.0.dist-info/top_level.txt +1 -0
@@ -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,2 @@
1
+ from GimnTools.ImaGIMN.IO.MIIO import *
2
+ from GimnTools.ImaGIMN.IO.GimnIO import *
@@ -0,0 +1,6 @@
1
+ from GimnTools.ImaGIMN import sinogramer
2
+ from GimnTools.ImaGIMN import process_root
3
+ from GimnTools.ImaGIMN import IO
4
+ from GimnTools.ImaGIMN.image import *
5
+
6
+
@@ -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
@@ -0,0 +1,122 @@
1
+ import numpy as np
2
+ from GimnTools.ImaGIMN.processing.tools.math import rotate
3
+ from numba import njit
4
+
5
+
6
+ def radon_m(image, angles, interpolator, center=None):
7
+ """
8
+ Computes the sinogram of an image using the Radon transform method.
9
+
10
+ @param image (numpy.ndarray): Input image.
11
+ @param angles (numpy.ndarray): Angles at which projections will be calculated.
12
+ @param interpolator (function): Interpolation function to be used.
13
+ @param center (tuple, optional): Center of the image (default is the center of the image).
14
+
15
+ @return sino (numpy.ndarray): Sinogram of the image.
16
+ """
17
+ sino = np.zeros([image.shape[0], angles.size])
18
+ for i, angle in enumerate(angles):
19
+ test = rotate(image, angle, interpolator, center=center)
20
+ sino[:, i] = test.sum(axis=1)
21
+ return sino
22
+
23
+ def projector(image, angles, interpolator, center=None):
24
+ """
25
+ Computes the sinogram of an image using the projection method.
26
+
27
+ @param image (numpy.ndarray): Input image.
28
+ @param angles (numpy.ndarray): Angles at which projections will be calculated.
29
+ @param interpolator (function): Interpolation function to be used.
30
+ @param center (tuple, optional): Center of the image (default is the center of the image).
31
+
32
+ @return sino (numpy.ndarray): Sinogram of the image.
33
+ """
34
+ ang = angles
35
+ sino = np.zeros([image.shape[0], len(angles)])
36
+ for i, angle in enumerate(ang):
37
+ test = rotate(image, angle, interpolator, center=center)
38
+ sino[:, i] = test.sum(axis=1)
39
+ return sino
40
+
41
+ @njit
42
+ def direct_radon (imagem , angles):
43
+ """
44
+ @brief Computes the Radon transform (sinogram) of a given image for specified projection angles.
45
+ This function calculates the direct Radon transform of a 2D image using bilinear interpolation
46
+ for a set of projection angles.
47
+
48
+ @param imagem 2D numpy array representing the input image. The image must be square (same number of rows and columns).
49
+ @param angles 1D array-like of projection angles in degrees at which the Radon transform is computed.
50
+ @return sinograma 2D numpy array containing the sinogram, where each column corresponds to the projection at a specific angle.
51
+ @note The function assumes that the input image is square. If the image is not square, a warning is printed.
52
+ @note Uses bilinear interpolation to estimate pixel values at non-integer coordinates during the projection process.
53
+ @warning The function prints a message if the input image is not square, but continues execution.
54
+ @see bilinear_interpolation
55
+ """
56
+ array = np.asarray(imagem)
57
+ nphi = len(angles)
58
+ dimensions = imagem.shape
59
+ tamanho=dimensions[0]
60
+ tamanho2=dimensions[1]
61
+ colsino=np.zeros((tamanho),dtype=np.float64)
62
+ if tamanho != tamanho2:
63
+ print('the image dimensions must be equal')
64
+ center=(tamanho-1)/2
65
+ radius=center*center
66
+
67
+ sinograma=np.zeros((tamanho,nphi))
68
+
69
+ for k in range(nphi):
70
+ angle = np.deg2rad(angles[k]-90)
71
+ cos=np.cos(angle)
72
+ sen=np.sin(angle)
73
+ for m in range (tamanho):
74
+ colsino[m]=0
75
+ for n in range (tamanho):
76
+ mc = m - center
77
+ nc = n - center
78
+ if mc*mc + nc*nc < radius:
79
+ x = center + mc*cos - nc*sen
80
+ y = center + mc*sen + nc*cos
81
+ v =bilinear_interpolation(imagem,x,y)
82
+ var =colsino[m]+v
83
+ colsino[m] =var
84
+ sinograma[:,k]=colsino
85
+ return sinograma
86
+
87
+
88
+ @njit
89
+ def bilinear_interpolation(image, x, y):
90
+ """
91
+ Perform bilinear interpolation for a given position (x,y) in the image.
92
+
93
+ Args:
94
+ image: 2D numpy array
95
+ x: x-coordinate (column)
96
+ y: y-coordinate (row)
97
+
98
+ Returns:
99
+ Interpolated pixel value
100
+ """
101
+ # Get integer coordinates
102
+ x0 = int(np.floor(x))
103
+ y0 = int(np.floor(y))
104
+ x1 = min(x0 + 1, image.shape[1] - 1) # Ensure within bounds
105
+ y1 = min(y0 + 1, image.shape[0] - 1)
106
+
107
+ # Get fractional parts
108
+ dx = x - x0
109
+ dy = y - y0
110
+
111
+ # Get pixel values
112
+ p00 = image[y0, x0] # Top-left
113
+ p01 = image[y0, x1] # Top-right
114
+ p10 = image[y1, x0] # Bottom-left
115
+ p11 = image[y1, x1] # Bottom-right
116
+
117
+ # Interpolate horizontally
118
+ top = (1 - dx) * p00 + dx * p01
119
+ bottom = (1 - dx) * p10 + dx * p11
120
+
121
+ # Interpolate vertically
122
+ return (1 - dy) * top + dy * bottom