Spaces:
Sleeping
Sleeping
import streamlit as st | |
import pydicom | |
import matplotlib.pyplot as plt | |
import os | |
# Set up the Streamlit app title | |
st.title("DICOM Viewer for CBCT Scans") | |
# Directory where DICOM files are stored in the repository | |
dicom_directory = "./dicom_files/" | |
# Function to get the slice location or image position for sorting | |
def get_slice_location(dicom_file): | |
ds = pydicom.dcmread(dicom_file) | |
# Try to get the 'Slice Location'; if not available, use 'Image Position Patient' | |
if 'SliceLocation' in ds: | |
return float(ds.SliceLocation) | |
elif 'ImagePositionPatient' in ds: | |
# 'ImagePositionPatient' is a list; use the first element (z-coordinate) | |
return float(ds.ImagePositionPatient[2]) | |
else: | |
return 0 # Default to 0 if neither tag is available | |
# Read all DICOM files from the directory | |
dicom_files = [os.path.join(dicom_directory, f) for f in os.listdir(dicom_directory) if f.endswith('.dcm')] | |
if dicom_files: | |
# Sort DICOM files by slice location or image position | |
dicom_files.sort(key=lambda x: get_slice_location(x)) | |
# Read all DICOM images (sorted) | |
dicom_images = [pydicom.dcmread(file).pixel_array for file in dicom_files] | |
# Interactive slider to select image index | |
st.sidebar.header("Image Slider") | |
image_index = st.sidebar.slider("Select Image Index", 0, len(dicom_images) - 1, 0) | |
# Display the selected DICOM image | |
st.header(f"Displaying Image {image_index + 1} of {len(dicom_images)}") | |
fig, ax = plt.subplots() | |
ax.imshow(dicom_images[image_index], cmap='gray') | |
ax.axis('off') | |
st.pyplot(fig) | |
else: | |
st.write("No DICOM files found in the directory. Please check the folder and try again.") | |