I am beginner in Python. I want to display the CT images in three views: sagittal, axial and coronal. Using examples and sample codes I searched, I wrote the below code, But I have two problems:
1- With this code, sagittal and coronal images are displayed rotated.
2- It shows only one slice and I want it to show all slices.
can you help me?
thanks a lot
`import pydicom
import numpy as np
import matplotlib.pyplot as plt
import os
# Specify the path to the folder containing DICOM files
folder_path = r"D:python test"
# List to store DICOM datasets
ct_datasets = []
# Loop through DICOM files in the folder
for file_name in os.listdir(folder_path):
if file_name.endswith('.dcm'):
file_path = os.path.join(folder_path, file_name)
ds = pydicom.dcmread(file_path)
ct_datasets.append(ds)
# Check if any DICOM datasets were loaded
if len(ct_datasets) == 0:
print("No DICOM files found in the specified folder.")
exit()
# Sort DICOM datasets by SliceLocation (assuming this attribute is present)
ct_datasets.sort(key=lambda x: float(x.SliceLocation))
# Get PixelSpacing and SliceThickness from the first DICOM dataset
first_dataset = ct_datasets[0]
ps = first_dataset.PixelSpacing
ss = first_dataset.SliceThickness
# Calculate aspect ratios for plotting
ax_aspect = ps[1] / ps[0]
sag_aspect = ps[1] / ss
cor_aspect = ss / ps[0]
# Create a 3D array to hold the image data
img_shape = list(first_dataset.pixel_array.shape)
img_shape.append(len(ct_datasets))
img3d = np.zeros(img_shape)
# Fill the 3D array with image data from DICOM datasets
for i, ds in enumerate(ct_datasets):
img2d = ds.pixel_array
img3d[:, :, i] = img2d
# Plot 3 orthogonal slices (axial, sagittal, coronal)
plt.figure(figsize=(10, 10))
# Axial view
a1 = plt.subplot(2, 2, 1)
plt.imshow(img3d[:, :, img_shape[2] // 2], cmap='gray')
a1.set_aspect(ax_aspect)
plt.title('Axial')
# Sagittal view
a2 = plt.subplot(2, 2, 2)
plt.imshow(img3d[:, img_shape[1] // 2, :], cmap='gray')
a2.set_aspect(sag_aspect)
plt.title('Sagittal')
# Coronal view
a3 = plt.subplot(2, 2, 3)
plt.imshow(img3d[img_shape[0] // 2, :, :].T, cmap='gray')
a3.set_aspect(cor_aspect)
plt.title('Coronal')
plt.show()'
New contributor
aseman is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.