Update preprocessing.py
Browse files- preprocessing.py +105 -0
preprocessing.py
CHANGED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Preprocessing script for DICOM medical images
|
| 3 |
+
"""
|
| 4 |
+
import os
|
| 5 |
+
import numpy as np
|
| 6 |
+
import pydicom
|
| 7 |
+
import cv2
|
| 8 |
+
from glob import glob
|
| 9 |
+
from tqdm import tqdm
|
| 10 |
+
import argparse
|
| 11 |
+
|
| 12 |
+
def apply_window_level(image, window_center, window_width):
|
| 13 |
+
"""
|
| 14 |
+
Apply windowing to the DICOM image to enhance visualization
|
| 15 |
+
|
| 16 |
+
Args:
|
| 17 |
+
image (numpy.ndarray): Input image
|
| 18 |
+
window_center (float): Window center (level)
|
| 19 |
+
window_width (float): Window width
|
| 20 |
+
|
| 21 |
+
Returns:
|
| 22 |
+
numpy.ndarray: Windowed image
|
| 23 |
+
"""
|
| 24 |
+
img_min = window_center - window_width // 2
|
| 25 |
+
img_max = window_center + window_width // 2
|
| 26 |
+
|
| 27 |
+
windowed = np.clip(image, img_min, img_max)
|
| 28 |
+
windowed = (windowed - img_min) / (img_max - img_min) * 255.0
|
| 29 |
+
|
| 30 |
+
return windowed.astype(np.uint8)
|
| 31 |
+
|
| 32 |
+
def process_dicom_files(input_dir, output_dir):
|
| 33 |
+
"""
|
| 34 |
+
Process all DICOM files in the input directory
|
| 35 |
+
|
| 36 |
+
Args:
|
| 37 |
+
input_dir (str): Directory containing DICOM files
|
| 38 |
+
output_dir (str): Directory to save processed images
|
| 39 |
+
"""
|
| 40 |
+
# Create output directories
|
| 41 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 42 |
+
images_dir = os.path.join(output_dir, "images")
|
| 43 |
+
os.makedirs(images_dir, exist_ok=True)
|
| 44 |
+
|
| 45 |
+
# Find all DICOM files
|
| 46 |
+
dicom_files = glob(os.path.join(input_dir, "**", "*.dcm"), recursive=True)
|
| 47 |
+
print(f"Found {len(dicom_files)} DICOM files")
|
| 48 |
+
|
| 49 |
+
# Process each file
|
| 50 |
+
for i, dicom_path in enumerate(tqdm(dicom_files, desc="Processing DICOM files")):
|
| 51 |
+
try:
|
| 52 |
+
# Read DICOM file
|
| 53 |
+
dicom = pydicom.dcmread(dicom_path)
|
| 54 |
+
|
| 55 |
+
# Extract image data
|
| 56 |
+
image = dicom.pixel_array
|
| 57 |
+
|
| 58 |
+
# Apply windowing if available
|
| 59 |
+
if hasattr(dicom, 'WindowCenter') and hasattr(dicom, 'WindowWidth'):
|
| 60 |
+
window_center = dicom.WindowCenter
|
| 61 |
+
window_width = dicom.WindowWidth
|
| 62 |
+
|
| 63 |
+
# Handle multiple window values
|
| 64 |
+
if isinstance(window_center, pydicom.multival.MultiValue):
|
| 65 |
+
window_center = window_center[0]
|
| 66 |
+
if isinstance(window_width, pydicom.multival.MultiValue):
|
| 67 |
+
window_width = window_width[0]
|
| 68 |
+
|
| 69 |
+
image = apply_window_level(image, window_center, window_width)
|
| 70 |
+
else:
|
| 71 |
+
# Apply default windowing for CT images
|
| 72 |
+
if dicom.Modality == "CT":
|
| 73 |
+
image = apply_window_level(image, 40, 400) # Soft tissue window
|
| 74 |
+
else:
|
| 75 |
+
# Normalize to 0-255 range
|
| 76 |
+
image = ((image - image.min()) / (image.max() - image.min() + 1e-8) * 255).astype(np.uint8)
|
| 77 |
+
|
| 78 |
+
# Generate output filename
|
| 79 |
+
patient_id = dicom.PatientID if hasattr(dicom, 'PatientID') else "unknown"
|
| 80 |
+
series_uid = dicom.SeriesInstanceUID if hasattr(dicom, 'SeriesInstanceUID') else "unknown"
|
| 81 |
+
instance_uid = dicom.SOPInstanceUID if hasattr(dicom, 'SOPInstanceUID') else str(i)
|
| 82 |
+
|
| 83 |
+
output_filename = f"{patient_id}_{series_uid[-8:]}_{instance_uid[-8:]}.png"
|
| 84 |
+
output_path = os.path.join(images_dir, output_filename)
|
| 85 |
+
|
| 86 |
+
# Save image
|
| 87 |
+
cv2.imwrite(output_path, image)
|
| 88 |
+
|
| 89 |
+
# Save metadata
|
| 90 |
+
with open(os.path.join(output_dir, "metadata.txt"), "a") as f:
|
| 91 |
+
f.write(f"{output_filename},{dicom_path}\n")
|
| 92 |
+
|
| 93 |
+
except Exception as e:
|
| 94 |
+
print(f"Error processing {dicom_path}: {e}")
|
| 95 |
+
|
| 96 |
+
print(f"Processing complete. Processed images saved to {images_dir}")
|
| 97 |
+
|
| 98 |
+
if __name__ == "__main__":
|
| 99 |
+
parser = argparse.ArgumentParser(description='Process DICOM files')
|
| 100 |
+
parser.add_argument('--input', type=str, required=True, help='Input directory with DICOM files')
|
| 101 |
+
parser.add_argument('--output', type=str, default='./processed_data', help='Output directory')
|
| 102 |
+
|
| 103 |
+
args = parser.parse_args()
|
| 104 |
+
|
| 105 |
+
process_dicom_files(args.input, args.output)
|