A Multiple Sclerosis MRI Dataset with Tri-Mask Annotations for Lesion Segmentation.
The 17 matches
- [1] § Technical Validation › Baseline methods and implementation ↔ old_scripts/model_architecturs.py, lines 852–909 · score 0.86 · nested skip pathways, semantic gap, medical image segmentation, convolutional, encoder, channel
- [2] § Background & Summary ↔ preprocessing/dicom_to_nifti.py, lines 235–310 · score 0.69 · T1 weighted, T2 weighted, FLAIR sequences, suppresses, detection, protocols
- [3] § Materials & Methods › Preprocessing › Step 5: Brain extraction ↔ preprocessing/coregistration_and_brain_extraction.py, lines 251–378 · score 0.67 · Brain Extraction, brain mask, FSL, BET, FLAIR
- [4] § Data Records ↔ preprocessing/dicom_to_nifti.py, lines 352–417 · score 0.63 · voxel spacing, headers preserve, NIfTI, matrices, preprocessed, Patient
- [5] § Materials & Methods › Data collection › Patient cohort ↔ preprocessing/dicom_to_nifti.py, lines 235–310 · score 0.63 · motion artifacts, image quality, technical, MS, patient
- [6] § Materials & Methods › Annotation methodology › Annotation statistics ↔ dataset_analysis/ms_demographics_table.py, lines 98–181 · score 0.62 · female patients, sex, cohort, age, MS
- [7] § Background & Summary ↔ preprocessing/coregistration_and_brain_extraction.py, lines 1–30 · score 0.61 · brain extraction, FLAIR space, FLAIR images, preprocessed, binary, mask
- [8] § Materials & Methods › Preprocessing › Step 3: Co-registration ↔ preprocessing/coregistration_and_brain_extraction.py, lines 1–30 · score 0.58 · FLAIR space, FSL, FLIRT, FLAIR images, masks
- [9] § Usage Notes ↔ old_scripts/models_runner.py, lines 1–86 · score 0.57 · TensorFlow, Deep learning, CUDA, libraries, brain
- [10] § Materials & Methods › Evaluation metrics ↔ utils/metrics.py, lines 57–98 · score 0.56 · percentile Hausdorff Distance, surfaces, metrics, HD95, boundary
- [11] § Materials & Methods › MRI Acquisition ↔ dataset_analysis/ms_imaging_table.py, lines 9–122 · score 0.56 · slice thickness, FA, TE, matrix, TI, DICOM
- [12] § Technical Validation › Experimental setup ↔ utils/data_loader.py, lines 185–237 · score 0.54 · cross validation split, fold cross validation, held, training, patient
- [13] § Data Records ↔ dataset_analysis/patient_encoder_v2.py, lines 253–314 · score 0.54 · nii.gz, NIfTI headers, anonymized, Patient
- [14] § Usage Notes ↔ preprocessing/coregistration_and_brain_extraction.py, lines 537–584 · score 0.53 · brain extraction, FSL, GB, installation, memory
- [15] § Materials & Methods › Preprocessing › Step 2: Format conversion ↔ preprocessing/dicom_to_nifti.py, lines 504–547 · score 0.52 · dcm2niix, compatibility, NIfTI, conversion, DICOM
- [16] § Materials & Methods › Evaluation metrics ↔ old_scripts/metrics_functions.py, lines 42–77 · score 0.51 · percentile Hausdorff Distance, metrics, HD95, boundary
- [17] § Materials & Methods › Annotation methodology › Annotation statistics ↔ dataset_analysis/ms_mask_analysis.py, lines 245–301 · score 0.51 · female patients, cohort, age, MS
Paper
Loaded from Europe PMC by your browser, not stored by OSCR: doi.org · Europe PMC
The paper is loaded when this pane is shown.
The authors' code
Python · 583 lines · 26 KB · MIT · 4 matches
- #!/usr/bin/env python3
- """
- MRI NIFTI File Creator from DICOMs - Final Production Version
- ====================================================
- This script converts the dicom files of a patient into a nifti file.
- Since many dicom header would be lost through this conversion, this script provides header information as in json files.
- System Requirements:
- - Python 3.9+
- Features:
- -
- Author: Mahdi Bashiri Bawil
- Date: September 2025
- Version: 1.0 (Production Ready)
- """
- import os
- import json
- import logging
- from pathlib import Path
- import subprocess
- import sys
- from datetime import datetime
- # Required libraries
- try:
- import pydicom
- import nibabel as nib
- import numpy as np
- from dicom2nifti import dicom_series_to_nifti
- from dicom2nifti.settings import disable_validate_slice_increment
- except ImportError as e:
- print(f"Missing required library: {e}")
- print("Install with: pip install pydicom nibabel dicom2nifti")
- sys.exit(1)
- # Set up logging with UTF-8 encoding to handle special characters
- logging.basicConfig(
- level=logging.INFO,
- format='%(asctime)s - %(levelname)s - %(message)s',
- handlers=[
- logging.FileHandler('ms_dicom_to_nifti_conversion.log', encoding='utf-8'),
- logging.StreamHandler()
- ]
- )
- # Set console output to UTF-8 if possible
- if hasattr(sys.stdout, 'reconfigure'):
- sys.stdout.reconfigure(encoding='utf-8')
- if hasattr(sys.stderr, 'reconfigure'):
- sys.stderr.reconfigure(encoding='utf-8')
- class MSDatasetDicomToNiftiConverter:
- """
- Specialized DICOM to NIfTI converter for MS dataset structure
- Handles the specific directory structure: PatientID/Protocol/DICOM_files
- Enhanced for research use with comprehensive metadata preservation
- """
- def __init__(self, input_directory, output_directory, method='dicom2nifti'):
- """
- Initialize MS dataset converter
- Args:
- input_directory (str): Root directory containing patient folders (6-digit IDs)
- output_directory (str): Output directory for NIfTI files
- method (str): Conversion method ('dicom2nifti', 'dcm2niix', 'nibabel')
- """
- self.input_dir = Path(input_directory)
- self.output_dir = Path(output_directory)
- self.method = method
- self.converted_series = 0
- self.failed_series = 0
- self.processed_patients = 0
- # Create output directory
- self.output_dir.mkdir(parents=True, exist_ok=True)
- # Disable strict validation for research data
- disable_validate_slice_increment()
- # MS protocol mappings for standardization
- self.protocol_mapping = {
- 'FLAIR': 'FLAIR',
- 'FLAIR_SG': 'FLAIR_SG',
- 'T1WI': 'T1WI',
- 'T2WI': 'T2WI',
- 't1wi': 'T1WI', # Handle case variations
- 't2wi': 'T2WI',
- 'flair': 'FLAIR',
- 'flair_sg': 'FLAIR_SG'
- }
- def find_patient_folders(self):
- """Find all patient folders (6-digit numeric folders)"""
- patient_folders = []
- for item in self.input_dir.iterdir():
- if item.is_dir() and item.name.isdigit() and len(item.name) == 6:
- patient_folders.append(item)
- return sorted(patient_folders)
- def find_protocol_folders(self, patient_folder):
- """Find protocol folders within a patient folder"""
- protocol_folders = []
- for item in patient_folder.iterdir():
- if item.is_dir():
- protocol_folders.append(item)
- return protocol_folders
- def get_dicom_files(self, protocol_folder):
- """Get all DICOM files from a protocol folder, excluding PNG files"""
- dicom_files = []
- for file in protocol_folder.iterdir():
- if file.is_file() and not file.suffix.lower() == '.png':
- if self.is_dicom_file(file):
- dicom_files.append(file)
- return sorted(dicom_files)
- def is_dicom_file(self, file_path):
- """Check if file is a valid DICOM file"""
- try:
- pydicom.dcmread(file_path, stop_before_pixels=True)
- return True
- except:
- return False
- def standardize_protocol_name(self, protocol_name):
- """Standardize protocol names using mapping"""
- return self.protocol_mapping.get(protocol_name, protocol_name.upper())
- def extract_comprehensive_metadata(self, protocol_folder, dicom_files):
- """Extract comprehensive metadata from DICOM series for MS research"""
- if not dicom_files:
- return None
- # Read first and last DICOM files for comprehensive metadata
- first_ds = pydicom.dcmread(dicom_files[0])
- last_ds = pydicom.dcmread(dicom_files[-1]) if len(dicom_files) > 1 else first_ds
- # Helper function to safely get DICOM attribute
- def safe_get(ds, attr, default=None):
- try:
- value = getattr(ds, attr, default)
- if hasattr(value, 'value'): # Handle DataElement objects
- return value.value
- return value
- except:
- return default
- # Convert MultiValue objects to lists
- def convert_multivalue(value):
- if hasattr(value, '__iter__') and not isinstance(value, (str, bytes)):
- try:
- return list(value)
- except:
- return str(value)
- return value
- metadata = {
- # === PATIENT INFORMATION ===
- "PatientID": safe_get(first_ds, 'PatientID', 'Unknown'),
- "PatientName": str(safe_get(first_ds, 'PatientName', 'Anonymous')),
- "PatientAge": safe_get(first_ds, 'PatientAge', 'Unknown'),
- "PatientSex": safe_get(first_ds, 'PatientSex', 'Unknown'),
- "PatientBirthDate": safe_get(first_ds, 'PatientBirthDate', 'Unknown'),
- "PatientWeight": safe_get(first_ds, 'PatientWeight', None),
- "PatientSize": safe_get(first_ds, 'PatientSize', None),
- "PatientPosition": safe_get(first_ds, 'PatientPosition', 'Unknown'),
- # === STUDY INFORMATION ===
- "StudyDate": safe_get(first_ds, 'StudyDate', 'Unknown'),
- "StudyTime": safe_get(first_ds, 'StudyTime', 'Unknown'),
- "StudyDescription": safe_get(first_ds, 'StudyDescription', 'Unknown'),
- "StudyInstanceUID": safe_get(first_ds, 'StudyInstanceUID', 'Unknown'),
- "StudyID": safe_get(first_ds, 'StudyID', 'Unknown'),
- "AccessionNumber": safe_get(first_ds, 'AccessionNumber', 'Unknown'),
- "ReferringPhysicianName": str(safe_get(first_ds, 'ReferringPhysicianName', 'Unknown')),
- "InstitutionName": safe_get(first_ds, 'InstitutionName', 'Unknown'),
- "InstitutionAddress": safe_get(first_ds, 'InstitutionAddress', 'Unknown'),
- "InstitutionalDepartmentName": safe_get(first_ds, 'InstitutionalDepartmentName', 'Unknown'),
- # === SERIES INFORMATION ===
- "SeriesDescription": safe_get(first_ds, 'SeriesDescription', 'Unknown'),
- "SeriesNumber": safe_get(first_ds, 'SeriesNumber', 'Unknown'),
- "SeriesInstanceUID": safe_get(first_ds, 'SeriesInstanceUID', 'Unknown'),
- "SeriesDate": safe_get(first_ds, 'SeriesDate', 'Unknown'),
- "SeriesTime": safe_get(first_ds, 'SeriesTime', 'Unknown'),
- "ProtocolName": safe_get(first_ds, 'ProtocolName', protocol_folder.name),
- "Modality": safe_get(first_ds, 'Modality', 'MR'),
- # === MR ACQUISITION PARAMETERS (Critical for MS research) ===
- "MagneticFieldStrength": safe_get(first_ds, 'MagneticFieldStrength', None),
- "SliceThickness": safe_get(first_ds, 'SliceThickness', None),
- "SpacingBetweenSlices": safe_get(first_ds, 'SpacingBetweenSlices', None),
- "RepetitionTime": safe_get(first_ds, 'RepetitionTime', None),
- "EchoTime": safe_get(first_ds, 'EchoTime', None),
- "InversionTime": safe_get(first_ds, 'InversionTime', None),
- "FlipAngle": safe_get(first_ds, 'FlipAngle', None),
- "EchoNumbers": safe_get(first_ds, 'EchoNumbers', None),
- "NumberOfAverages": safe_get(first_ds, 'NumberOfAverages', None),
- "ImagingFrequency": safe_get(first_ds, 'ImagingFrequency', None),
- "ImagedNucleus": safe_get(first_ds, 'ImagedNucleus', None),
- "MagneticFieldStrength": safe_get(first_ds, 'MagneticFieldStrength', None),
- # === SPATIAL INFORMATION ===
- "PixelSpacing": convert_multivalue(safe_get(first_ds, 'PixelSpacing', None)),
- "Rows": safe_get(first_ds, 'Rows', None),
- "Columns": safe_get(first_ds, 'Columns', None),
- "AcquisitionMatrix": convert_multivalue(safe_get(first_ds, 'AcquisitionMatrix', None)),
- "FOVDimensions": convert_multivalue(safe_get(first_ds, 'FOVDimensions', None)),
- "SliceLocation": safe_get(first_ds, 'SliceLocation', None),
- "ImageOrientationPatient": convert_multivalue(safe_get(first_ds, 'ImageOrientationPatient', None)),
- "ImagePositionPatient": convert_multivalue(safe_get(first_ds, 'ImagePositionPatient', None)),
- # === SEQUENCE INFORMATION (Important for MS protocols) ===
- "ImageType": convert_multivalue(safe_get(first_ds, 'ImageType', 'Unknown')),
- "ScanningSequence": convert_multivalue(safe_get(first_ds, 'ScanningSequence', 'Unknown')),
- "SequenceVariant": convert_multivalue(safe_get(first_ds, 'SequenceVariant', 'Unknown')),
- "ScanOptions": convert_multivalue(safe_get(first_ds, 'ScanOptions', 'Unknown')),
- "MRAcquisitionType": safe_get(first_ds, 'MRAcquisitionType', 'Unknown'),
- "SequenceName": safe_get(first_ds, 'SequenceName', 'Unknown'),
- "PulseSequenceName": safe_get(first_ds, 'PulseSequenceName', 'Unknown'),
- # === EQUIPMENT INFORMATION ===
- "Manufacturer": safe_get(first_ds, 'Manufacturer', 'Unknown'),
- "ManufacturerModelName": safe_get(first_ds, 'ManufacturerModelName', 'Unknown'),
- "SoftwareVersions": convert_multivalue(safe_get(first_ds, 'SoftwareVersions', 'Unknown')),
- "DeviceSerialNumber": safe_get(first_ds, 'DeviceSerialNumber', 'Unknown'),
- "StationName": safe_get(first_ds, 'StationName', 'Unknown'),
- # === CONTRAST AND IMAGE PARAMETERS ===
- "ContrastBolusAgent": safe_get(first_ds, 'ContrastBolusAgent', None),
- "ContrastBolusRoute": safe_get(first_ds, 'ContrastBolusRoute', None),
- "ContrastBolusVolume": safe_get(first_ds, 'ContrastBolusVolume', None),
- "WindowCenter": convert_multivalue(safe_get(first_ds, 'WindowCenter', None)),
- "WindowWidth": convert_multivalue(safe_get(first_ds, 'WindowWidth', None)),
- "RescaleIntercept": safe_get(first_ds, 'RescaleIntercept', None),
- "RescaleSlope": safe_get(first_ds, 'RescaleSlope', None),
- # === TIMING AND PHYSIOLOGICAL ===
- "AcquisitionTime": safe_get(first_ds, 'AcquisitionTime', None),
- "ContentTime": safe_get(first_ds, 'ContentTime', None),
- "TriggerTime": safe_get(first_ds, 'TriggerTime', None),
- "HeartRate": safe_get(first_ds, 'HeartRate', None),
- "CardiacNumberOfImages": safe_get(first_ds, 'CardiacNumberOfImages', None),
- # === BODY PART AND POSITIONING ===
- "BodyPartExamined": safe_get(first_ds, 'BodyPartExamined', 'Unknown'),
- "PatientPosition": safe_get(first_ds, 'PatientPosition', 'Unknown'),
- "ViewPosition": safe_get(first_ds, 'ViewPosition', None),
- # === SLICE INFORMATION ===
- "SliceLocation_First": safe_get(first_ds, 'SliceLocation', None),
- "SliceLocation_Last": safe_get(last_ds, 'SliceLocation', None),
- "InstanceNumber_First": safe_get(first_ds, 'InstanceNumber', None),
- "InstanceNumber_Last": safe_get(last_ds, 'InstanceNumber', None),
- # === FILE AND PROCESSING INFORMATION ===
- "NumberOfSlices": len(dicom_files),
- "DicomFiles": [f.name for f in dicom_files],
- "ProtocolFolder": protocol_folder.name,
- "OriginalPath": str(protocol_folder),
- "ConversionDate": datetime.now().isoformat(),
- "ConversionMethod": self.method,
- # === MS-SPECIFIC RESEARCH METADATA ===
- "MSProtocolType": self.standardize_protocol_name(protocol_folder.name),
- "IsFlairSequence": "FLAIR" in protocol_folder.name.upper(),
- "IsT1Weighted": "T1" in protocol_folder.name.upper(),
- "IsT2Weighted": "T2" in protocol_folder.name.upper(),
- "IsSuppressedFlair": "SG" in protocol_folder.name.upper(),
- # === ADDITIONAL TECHNICAL PARAMETERS ===
- "BitsAllocated": safe_get(first_ds, 'BitsAllocated', None),
- "BitsStored": safe_get(first_ds, 'BitsStored', None),
- "HighBit": safe_get(first_ds, 'HighBit', None),
- "PixelRepresentation": safe_get(first_ds, 'PixelRepresentation', None),
- "PhotometricInterpretation": safe_get(first_ds, 'PhotometricInterpretation', None),
- "SamplesPerPixel": safe_get(first_ds, 'SamplesPerPixel', None),
- # === RESEARCH-SPECIFIC QUALITY METRICS ===
- "SNR_Estimated": None, # Can be calculated post-conversion
- "ImageQualityScore": None, # For future quality assessment
- "MotionArtifacts": None, # For future artifact detection
- }
- # Convert numpy arrays and special types to JSON-serializable formats
- for key, value in metadata.items():
- if isinstance(value, np.ndarray):
- metadata[key] = value.tolist()
- elif hasattr(value, '__iter__') and not isinstance(value, (str, bytes)) and value is not None:
- try:
- metadata[key] = list(value)
- except:
- metadata[key] = str(value)
- elif value is not None and not isinstance(value, (int, float, str, bool, list, dict)):
- metadata[key] = str(value)
- return metadata
- def convert_with_dicom2nifti(self, protocol_folder, output_path):
- """Convert using dicom2nifti library (fixed - removed invalid reorient parameter)"""
- try:
- # Fixed: removed the invalid 'reorient' parameter
- dicom_series_to_nifti(str(protocol_folder), str(output_path))
- return True
- except Exception as e:
- logging.error(f"dicom2nifti conversion failed for {protocol_folder}: {e}")
- return False
- def convert_with_dcm2niix(self, protocol_folder, output_path):
- """Convert using dcm2niix"""
- try:
- # Check if dcm2niix is available
- subprocess.run(['dcm2niix', '-h'], capture_output=True, check=True)
- # Run dcm2niix with research-optimized settings
- cmd = [
- 'dcm2niix',
- '-z', 'y', # Compress output
- '-f', output_path.stem, # Output filename
- '-o', str(output_path.parent), # Output directory
- '-b', 'y', # Create BIDS sidecar JSON
- '-ba', 'y', # Anonymize BIDS
- '-v', 'y', # Verbose output
- str(protocol_folder)
- ]
- result = subprocess.run(cmd, capture_output=True, text=True)
- if result.returncode == 0:
- return True
- else:
- logging.error(f"dcm2niix failed for {protocol_folder}: {result.stderr}")
- return False
- except (subprocess.CalledProcessError, FileNotFoundError):
- logging.error("dcm2niix not found. Install from: https://github.com/rordenlab/dcm2niix")
- return False
- def convert_with_nibabel(self, protocol_folder, output_path):
- """Convert using nibabel with enhanced header preservation"""
- try:
- dicom_files = self.get_dicom_files(protocol_folder)
- if not dicom_files:
- return False
- # Read DICOM files
- slices = []
- for dicom_file in dicom_files:
- ds = pydicom.dcmread(dicom_file)
- slices.append(ds)
- # Sort by slice location or instance number
- try:
- slices.sort(key=lambda x: float(getattr(x, 'SliceLocation', 0)))
- except:
- try:
- slices.sort(key=lambda x: int(getattr(x, 'InstanceNumber', 0)))
- except:
- logging.warning(f"Could not sort slices for {protocol_folder}")
- # Create 3D array
- pixel_arrays = [s.pixel_array.astype(np.float32) for s in slices]
- volume = np.stack(pixel_arrays, axis=-1)
- # Get voxel spacing and create proper affine matrix
- ds = slices[0]
- pixel_spacing = getattr(ds, 'PixelSpacing', [1.0, 1.0])
- slice_thickness = getattr(ds, 'SliceThickness', 1.0)
- # Create more accurate affine matrix
- affine = np.eye(4)
- affine[0, 0] = float(pixel_spacing[0])
- affine[1, 1] = float(pixel_spacing[1])
- affine[2, 2] = float(slice_thickness)
- # Try to get image position for better spatial alignment
- try:
- img_pos = getattr(ds, 'ImagePositionPatient', [0, 0, 0])
- affine[0, 3] = float(img_pos[0])
- affine[1, 3] = float(img_pos[1])
- affine[2, 3] = float(img_pos[2])
- except:
- pass
- # Create NIfTI image with enhanced header
- nifti_img = nib.Nifti1Image(volume, affine)
- # Set additional header information
- header = nifti_img.header
- header.set_xyzt_units('mm', 'sec')
- # Set data type appropriately
- if volume.dtype == np.float32:
- header.set_data_dtype(np.float32)
- else:
- header.set_data_dtype(volume.dtype)
- nib.save(nifti_img, output_path)
- return True
- except Exception as e:
- logging.error(f"nibabel conversion failed for {protocol_folder}: {e}")
- return False
- def process_patient(self, patient_folder):
- """Process all protocols for a single patient"""
- patient_id = patient_folder.name
- logging.info(f"Processing patient: {patient_id}")
- # Create patient output directory
- patient_output_dir = self.output_dir / patient_id
- patient_output_dir.mkdir(parents=True, exist_ok=True)
- # Find protocol folders
- protocol_folders = self.find_protocol_folders(patient_folder)
- if not protocol_folders:
- logging.warning(f"No protocol folders found for patient {patient_id}")
- return
- patient_conversions = 0
- patient_failures = 0
- for protocol_folder in protocol_folders:
- protocol_name = protocol_folder.name
- standardized_protocol = self.standardize_protocol_name(protocol_name)
- # Check if folder contains DICOM files
- dicom_files = self.get_dicom_files(protocol_folder)
- if not dicom_files:
- logging.warning(f"No DICOM files found in {protocol_folder}")
- patient_failures += 1
- continue
- # Generate output filename: {6-digit patientID}_{protocol}.nii.gz
- filename = f"{patient_id}_{standardized_protocol}.nii.gz"
- nifti_path = patient_output_dir / filename
- json_path = patient_output_dir / filename.replace('.nii.gz', '.json')
- logging.info(f" Converting {protocol_name} -> {filename}")
- # Convert based on selected method
- success = False
- if self.method == 'dicom2nifti':
- success = self.convert_with_dicom2nifti(protocol_folder, nifti_path)
- elif self.method == 'dcm2niix':
- success = self.convert_with_dcm2niix(protocol_folder, nifti_path)
- elif self.method == 'nibabel':
- success = self.convert_with_nibabel(protocol_folder, nifti_path)
- if success:
- patient_conversions += 1
- self.converted_series += 1
- # Using regular characters instead of special Unicode characters
- logging.info(f" [SUCCESS] Successfully converted: {nifti_path}")
- # Save comprehensive metadata as JSON
- metadata = self.extract_comprehensive_metadata(protocol_folder, dicom_files)
- if metadata:
- with open(json_path, 'w', encoding='utf-8') as f:
- json.dump(metadata, f, indent=2, default=str, ensure_ascii=False)
- logging.info(f" [SUCCESS] Metadata saved: {json_path}")
- else:
- patient_failures += 1
- self.failed_series += 1
- # Using regular characters instead of special Unicode characters
- logging.error(f" [FAILED] Failed to convert: {protocol_folder}")
- logging.info(f"Patient {patient_id} completed: {patient_conversions} successful, {patient_failures} failed")
- self.processed_patients += 1
- def convert_all(self):
- """Convert all patients and protocols"""
- patient_folders = self.find_patient_folders()
- if not patient_folders:
- logging.error("No patient folders (6-digit numeric) found in input directory")
- return
- logging.info(f"Found {len(patient_folders)} patient folders to process")
- logging.info(f"Expected protocols per patient: FLAIR, FLAIR_SG, T1WI, T2WI")
- for i, patient_folder in enumerate(patient_folders, 1):
- logging.info(f"\nProcessing patient {i}/{len(patient_folders)}: {patient_folder.name}")
- self.process_patient(patient_folder)
- self.print_summary()
- def print_summary(self):
- """Print conversion summary"""
- print("\n" + "=" * 80)
- print("MS DATASET DICOM TO NIFTI CONVERSION SUMMARY")
- print("=" * 80)
- print(f"Input directory: {self.input_dir}")
- print(f"Output directory: {self.output_dir}")
- print(f"Conversion method: {self.method}")
- print("-" * 80)
- print(f"Patients processed: {self.processed_patients}")
- print(f"Protocol series successfully converted: {self.converted_series}")
- print(f"Protocol series failed: {self.failed_series}")
- print(f"Total protocol series: {self.converted_series + self.failed_series}")
- if (self.converted_series + self.failed_series) > 0:
- success_rate = (self.converted_series / (self.converted_series + self.failed_series) * 100)
- print(f"Success rate: {success_rate:.1f}%")
- else:
- print("Success rate: N/A")
- print("-" * 80)
- print("OUTPUT STRUCTURE:")
- print("Output_Directory/")
- print(" |-- 001/")
- print(" | |-- 001_FLAIR.nii.gz")
- print(" | |-- 001_FLAIR.json")
- print(" | |-- 001_FLAIR_SG.nii.gz")
- print(" | |-- 001_FLAIR_SG.json")
- print(" | |-- 001_T1WI.nii.gz")
- print(" | |-- 001_T1WI.json")
- print(" | |-- 001_T2WI.nii.gz")
- print(" | |-- 001_T2WI.json")
- print(" |-- 002/")
- print(" |-- ...")
- print("-" * 80)
- print("RESEARCH-READY FEATURES:")
- print("+ MS-specific protocol standardization")
- print("+ Comprehensive DICOM header preservation")
- print("+ Research-quality NIfTI format with proper spatial information")
- print("+ Detailed JSON metadata files with >50 DICOM attributes")
- print("+ Professional naming convention: {PatientID}_{Protocol}.nii.gz")
- print("+ UTF-8 encoding support for international characters")
- print("+ Enhanced spatial alignment and orientation")
- if self.method == 'dcm2niix':
- print("+ BIDS-compatible output")
- print("=" * 80)
- # Example usage
- if __name__ == "__main__":
- # MS Dataset directories
- input_directory = r"E:\MBashiri\Thesis\p6\Data\MS_100_patient_full"
- output_directory = r"E:\MBashiri\Thesis\p6\Data\MS_100_patient_nifti"
- print("MS DATASET DICOM TO NIFTI CONVERTER - RESEARCH EDITION")
- print("=" * 60)
- print("Directory Structure Expected:")
- print("Input/")
- print(" |-- 001/ # 6-digit patient ID")
- print(" | |-- FLAIR/ # Protocol folders")
- print(" | |-- FLAIR_SG/")
- print(" | |-- T1WI/")
- print(" | |-- T2WI/")
- print(" |-- 002/")
- print(" |-- ...")
- print("=" * 60)
- print("Available conversion methods:")
- print("1. 'dicom2nifti' - Reliable Python library (recommended)")
- print("2. 'dcm2niix' - Most comprehensive (requires installation)")
- print("3. 'nibabel' - Enhanced fallback method with better header preservation")
- print("=" * 60)
- # Initialize converter with dicom2nifti (recommended for MS research)
- converter = MSDatasetDicomToNiftiConverter(
- input_directory=input_directory,
- output_directory=output_directory,
- method='dicom2nifti' # Change to 'dcm2niix' if available
- )
- # Start conversion
- converter.convert_all()
dicom_to_nifti.py at commit c265bae, under MIT · at the source
Overview
- Biomedical Engineering Faculty, Sahand University of Technology,Tabriz, Iran
- Faculty of Physics, University of Tabriz,Tabriz, Iran
- Department of Engineering Sciences, Faculty of Advanced Technologies, University of Mohaghegh Ardabili,Namin, Iran
- Radiology Department, Tabriz University of Medical Sciences,Tabriz, Iran
Abstract
The abstract is not reproduced here: the paper's license (CC BY-NC-ND) does not allow it. Read it in the paper, at the publisher or on Europe PMC.
Repository
Its files are read in the Code ↔ Paper reader above, with 17 matches between paragraphs and lines of code.
Mahdi-Bashiri/MS3SEG
c265bae327691c279ff6651a98e264d70103def7, 14 February 2026Availability: 1 check, the latest on 29 September 2026: the link answers
- 29 September 2026: the link answers
26 files
- dataset_analysis/
file_renamer.py , Python, 630 lines - dataset_analysis/
ms_demographics_table.py , Python, 253 lines, 1 match - dataset_analysis/
ms_imaging_table.py , Python, 337 lines, 1 match - dataset_analysis/
ms_mask_analysis.py , Python, 305 lines, 1 match - dataset_analysis/
patient_encoder_v2.py , Python, 577 lines, 1 match - models/
__init__.py , Python, 44 lines - models/
swin_unetr.py , Python, 245 lines - models/
unet.py , Python, 108 lines - models/
unet_plusplus.py , Python, 140 lines - models/
unetr.py , Python, 152 lines - old_scripts/
loss_functions.py , Python, 104 lines - old_scripts/
metrics_functions.py , Python, 150 lines, 1 match - old_scripts/
model_architecturs.py , Python, 1,195 lines, 1 match - old_scripts/
models_runner.py , Python, 2,141 lines, 1 match - preprocessing/
anonymization.py , Python, 255 lines - preprocessing/
coregistration_and_brain , Python, 588 lines, 4 matches_extraction.py - preprocessing/
dicom_to_nifti.py , Python, 583 lines, 4 matches - preprocessing/
standardization.py , Python, 179 lines - training/
evaluate.py , Python, 334 lines - training/
train.py , Python, 357 lines - utils/
__init__.py , Python, 26 lines - utils/
data_loader.py , Python, 296 lines, 1 match - utils/
metrics.py , Python, 307 lines, 1 match - utils/
visualization.py , Python, 348 lines - LICENSE, License, 21 lines
- README.md, Text, 832 lines
Code availability statement
The paper has a code availability statement. Its license (CC BY-NC-ND) does not allow reproducing it here; in short, from what the harvester recognized in it:
- it points to the authors' code: Mahdi-Bashiri/
MS3SEG
Read it in the paper: doi.org/10.1038/s41597-026-07184-5.
Tracing map
Proposed by the machine: these links were found in the paper and verified at the source, without human review. The map will receive a Zenodo DOI once one of the paper's authors has validated it with their ORCID.
What the map holds:
- 1 repository of the authors' code, each at its verified commit, with its license and how the link was found in the paper;
- 24 scripts, each with its path and the digest of its content;
- 17 matches between paragraphs of the paper and lines of the code (method lexical-v1);
- neither the text of the paper nor the code itself.
Its JSON (tracing-map.json) is deposited on Zenodo with its DOI once the map is validated.
Data
Datasets cited
- figshare:30393475, at figshare; found in the references
Availability statements
The paper has a data availability statement and a data availability statement. Its license (CC BY-NC-ND) does not allow reproducing them here; in short, from what the harvester recognized in them:
- no repository, dataset or request procedure was recognized in them
Read them in the paper: doi.org/10.1038/s41597-026-07184-5.
Versions
The history of this record: each version stored by the harvester or made by a correction of its authors or of the maintainers of its code, and what changed in its facts. The texts of the paper (its abstract, its availability statements) are not part of it; versions that changed only those are not listed.
Version 1, 29 September 2026: the first record
Recorded: type, language, journal, volume, issue, pages, dates, 5 authors, 7 MeSH terms, 29 references.
Cite
This paper
Bawil, M. B., Shamsi, M., Ghalehasadi, A., Jafargholkhanloo, A. F., & Bavil, A. S. (2026). A Multiple Sclerosis MRI Dataset with Tri-Mask Annotations for Lesion Segmentation. Scientific data, 13(1), 867. https://
BibTeX
@article{bawil2026multip
author = {Bawil, Mahdi Bashiri and Shamsi, Mousa and Ghalehasadi, Aydin and Jafargholkhanloo, Ali Fahmi and Bavil, Abolhassan Shakeri},
title = {{A Multiple Sclerosis MRI Dataset with Tri-Mask Annotations for Lesion Segmentation}},
journal = {Scientific data},
year = {2026},
month = apr,
volume = {13},
number = {1},
pages = {867},
publisher = {Nature Publishing Group},
issn = {2052-4463},
doi = {10.1038/
url = {https://
pmid = {41980977},
pmcid = {PMC13249843}
}
RIS
TY - JOUR
AU - Bawil, Mahdi Bashiri
AU - Shamsi, Mousa
AU - Ghalehasadi, Aydin
AU - Jafargholkhanloo, Ali Fahmi
AU - Bavil, Abolhassan Shakeri
TI - A Multiple Sclerosis MRI Dataset with Tri-Mask Annotations for Lesion Segmentation
T2 - Scientific data
J2 - Sci Data
PY - 2026
DA - 2026/
VL - 13
IS - 1
SP - 867
SN - 2052-4463
PB - Nature Publishing Group
DO - 10.1038/
UR - https://
LA - en
ER -
CSL-JSON
{
"id": "10.1038/
"type": "article-journal",
"title": "A Multiple Sclerosis MRI Dataset with Tri-Mask Annotations for Lesion Segmentation",
"container-title": "Scientific data",
"author": [
{
"family": "Bawil",
"given": "Mahdi Bashiri"
},
{
"family": "Shamsi",
"given": "Mousa"
},
{
"family": "Ghalehasadi",
"given": "Aydin"
},
{
"family": "Jafargholkhanloo",
"given": "Ali Fahmi"
},
{
"family": "Bavil",
"given": "Abolhassan Shakeri"
}
],
"container-title-short":
"volume": "13",
"issue": "1",
"page": "867",
"DOI": "10.1038/
"PMID": "41980977",
"PMCID": "PMC13249843",
"ISSN": "2052-4463",
"publisher": "Nature Publishing Group",
"URL": "https://
"language": "en",
"issued": {
"date-parts": [
[
2026,
4,
14
]
]
}
}
The tracing map gets a citation of its own once an author has validated it and it has a DOI.
Similar papers
The papers with a page that share the most with this one: the tools found in their code, their categories, datasets, cited references and authors, the rarest counting most.
- [1] doi:10.1186/s12880-026-02481-2 [code]
- Deep learning-based neuroanatomical profiling reveals population-specific brain changes in multiple sclerosis: a large-scale Middle Eastern study.Journal: BMC medical imagingIn common: pydicom, Keras, TensorFlow, 9 other tools, multiple sclerosis, structural MRI / diffusion, 6 references, 3 authors
- [2] doi:10.1186/s12938-026-01555-0 [code]
- Incorporating normal periventricular changes for enhanced pathological white matter hyperintensity segmentation: on multiclass deep learning approaches.Journal: Biomedical engineering onlineIn common: Keras, TensorFlow, OpenCV, 7 other tools, methods / tools, structural MRI / diffusion, 3 references, 4 authors
- [3] doi:10.1371/journal.pdig.0001316 [code]
- Reliability of a convolutional neural network in segmenting multiple sclerosis lesions from MRI: Impact of data augmentation, image modality and tolerance with U-Net architecture.Journal: PLOS digital healthIn common: scikit-image, NiBabel, scikit-learn, 3 other tools, multiple sclerosis, methods / tools, structural MRI / diffusion, 6 references
- [4] doi:10.1038/s42003-026-10957-8 [code]
- Brain defence by the extracellular matrix protein Cochlin.Journal: Communications biologyIn common: pydicom, Keras, TensorFlow, 8 other tools
- [5] doi:10.1162/imag.a.1183 [code]
- Learning-based segmentation of diffusion-weighted MR images with arbitrary &
lt;i& gt;q& lt;/ i& gt;-space samplings. Journal: Imaging neuroscience (Cambridge, Mass.)In common: Keras, TensorFlow, scikit-image, 5 other tools, methods / tools, structural MRI / diffusion, 3 references - [6] doi:10.1080/07853890.2026.2685416 [code]
- Pulmonary and cerebral damage in COVID-19 survivors: is there any association?Journal: Annals of medicineIn common: pydicom, Keras, TensorFlow, 7 other tools, structural MRI / diffusion
- [7] doi:10.21037/qims-2026-0792 [code]
- An nnU-Net-based framework with adaptive feature representation for 3D brain tumor segmentation.Journal: Quantitative imaging in medicine and surgeryIn common: OpenCV, scikit-image, NiBabel, 6 other tools, methods / tools, structural MRI / diffusion, 2 references
- [8] doi:10.3389/frai.2026.1771088 [code]
- Few-shot deployment of pretrained MRI transformers in brain imaging tasks.Journal: Frontiers in artificial intelligenceIn common: pydicom, OpenCV, scikit-image, 7 other tools, methods / tools, structural MRI / diffusion
- [9] doi:10.64898/2026.07.15.26357954 [code]
- Portable Ultra-Low Field MRI Deep-Learning Algorithms for White Matter Lesion Segmentation Improve Accuracy and Reflect Clinical Disability in Multiple SclerosisJournal: medRxiv (preprint)In common: scikit-image, NiBabel, seaborn, 5 other tools, multiple sclerosis, structural MRI / diffusion, 2 references
- [10] doi:10.1002/epi.70296 [code]
- Fully automated three-dimensional deep learning-based magnetic resonance imaging segmentation of brain cavities in epilepsy surgery.Journal: EpilepsiaIn common: Keras, TensorFlow, OpenCV, 7 other tools, structural MRI / diffusion
Contribute
The authors of this paper can claim it, correct its record and validate its tracing map, and the maintainers of its code (its owner, or a public member of its organization) correct what it says of their repository; anyone signed in can ask for its removal. Every request goes to OSCR's own machine, which answers it; your account page follows them.
Sign in with ORCID to claim this paper as one of its authors, correct its record or validate its tracing map: when the paper's metadata lists your ORCID iD, you are recognized at once. Maintainers of its code: sign in with GitHub, then claim the repository on your account page.
Claim this paper
Correct its record
Say what each link of this record is, remove the ones that are not the paper's, add the ones that are missing. The correction becomes a new version of the record, in its Versions section.
Validate its tracing map
You validate the map as this page shows it: 1 repository of the authors' code, each at its verified commit and with its license, 24 scripts, and 17 matches between paragraphs and code (see the Code and Map sections). It then receives a DOI on Zenodo, with you (your ORCID iD) and OSCR as its creators; the code itself is not deposited.
The map's fingerprint: sha256:c9fe82a3cc636c07…
Add the badge to its README
The badge links the code to this page. Copy one of these into the README of the paper's code: only you decide where it goes, and nothing is changed for you.
Markdown
[, paste the snippet at the top, then “Commit changes…” and, to review it first, “Create a new branch and start a pull request”. You open the pull request; OSCR asks for no permission.
Request its removal
To ask OSCR to remove this record, the copies of its authors' scripts or its tracing map, use the removal request page: signed in, you say who you are, what to remove and why, then review and confirm the request. Published rules decide every request (how).
Discussion, reproductions, activity
Discussion: questions and error reports about this paper and its code, from signed-in readers and its authors. It opens with sign-in.
Reproductions: reports from readers who ran the authors' code: what they reproduced, with which environment, commit and data. It opens with sign-in.
Activity: what happens around this paper: new versions of its record, its map's validation, discussions and reproductions. It opens with sign-in.
