OSCR

A Multiple Sclerosis MRI Dataset with Tri-Mask Annotations for Lesion Segmentation.

Code ↔ Paper

17 matches between paragraphs of the paper and lines of its authors' code, computed by the harvester (lexical-v1). Click a colored paragraph or line to see its counterpart.

The 17 matches
  1. [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. [2] § Background & Summary ↔ preprocessing/dicom_to_nifti.py, lines 235–310 · score 0.69 · T1 weighted, T2 weighted, FLAIR sequences, suppresses, detection, protocols
  3. [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. [4] § Data Records ↔ preprocessing/dicom_to_nifti.py, lines 352–417 · score 0.63 · voxel spacing, headers preserve, NIfTI, matrices, preprocessed, Patient
  5. [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. [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. [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. [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. [9] § Usage Notes ↔ old_scripts/models_runner.py, lines 1–86 · score 0.57 · TensorFlow, Deep learning, CUDA, libraries, brain
  10. [10] § Materials & Methods › Evaluation metrics ↔ utils/metrics.py, lines 57–98 · score 0.56 · percentile Hausdorff Distance, surfaces, metrics, HD95, boundary
  11. [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. [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. [13] § Data Records ↔ dataset_analysis/patient_encoder_v2.py, lines 253–314 · score 0.54 · nii.gz, NIfTI headers, anonymized, Patient
  14. [14] § Usage Notes ↔ preprocessing/coregistration_and_brain_extraction.py, lines 537–584 · score 0.53 · brain extraction, FSL, GB, installation, memory
  15. [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. [16] § Materials & Methods › Evaluation metrics ↔ old_scripts/metrics_functions.py, lines 42–77 · score 0.51 · percentile Hausdorff Distance, metrics, HD95, boundary
  17. [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

  1. #!/usr/bin/env python3
  2. """
  3. MRI NIFTI File Creator from DICOMs - Final Production Version
  4. ====================================================
  5. This script converts the dicom files of a patient into a nifti file.
  6. Since many dicom header would be lost through this conversion, this script provides header information as in json files.
  7. System Requirements:
  8. - Python 3.9+
  9. Features:
  10. -
  11. Author: Mahdi Bashiri Bawil
  12. Date: September 2025
  13. Version: 1.0 (Production Ready)
  14. """
  15. import os
  16. import json
  17. import logging
  18. from pathlib import Path
  19. import subprocess
  20. import sys
  21. from datetime import datetime
  22. # Required libraries
  23. try:
  24. import pydicom
  25. import nibabel as nib
  26. import numpy as np
  27. from dicom2nifti import dicom_series_to_nifti
  28. from dicom2nifti.settings import disable_validate_slice_increment
  29. except ImportError as e:
  30. print(f"Missing required library: {e}")
  31. print("Install with: pip install pydicom nibabel dicom2nifti")
  32. sys.exit(1)
  33. # Set up logging with UTF-8 encoding to handle special characters
  34. logging.basicConfig(
  35. level=logging.INFO,
  36. format='%(asctime)s - %(levelname)s - %(message)s',
  37. handlers=[
  38. logging.FileHandler('ms_dicom_to_nifti_conversion.log', encoding='utf-8'),
  39. logging.StreamHandler()
  40. ]
  41. )
  42. # Set console output to UTF-8 if possible
  43. if hasattr(sys.stdout, 'reconfigure'):
  44. sys.stdout.reconfigure(encoding='utf-8')
  45. if hasattr(sys.stderr, 'reconfigure'):
  46. sys.stderr.reconfigure(encoding='utf-8')
  47. class MSDatasetDicomToNiftiConverter:
  48. """
  49. Specialized DICOM to NIfTI converter for MS dataset structure
  50. Handles the specific directory structure: PatientID/Protocol/DICOM_files
  51. Enhanced for research use with comprehensive metadata preservation
  52. """
  53. def __init__(self, input_directory, output_directory, method='dicom2nifti'):
  54. """
  55. Initialize MS dataset converter
  56. Args:
  57. input_directory (str): Root directory containing patient folders (6-digit IDs)
  58. output_directory (str): Output directory for NIfTI files
  59. method (str): Conversion method ('dicom2nifti', 'dcm2niix', 'nibabel')
  60. """
  61. self.input_dir = Path(input_directory)
  62. self.output_dir = Path(output_directory)
  63. self.method = method
  64. self.converted_series = 0
  65. self.failed_series = 0
  66. self.processed_patients = 0
  67. # Create output directory
  68. self.output_dir.mkdir(parents=True, exist_ok=True)
  69. # Disable strict validation for research data
  70. disable_validate_slice_increment()
  71. # MS protocol mappings for standardization
  72. self.protocol_mapping = {
  73. 'FLAIR': 'FLAIR',
  74. 'FLAIR_SG': 'FLAIR_SG',
  75. 'T1WI': 'T1WI',
  76. 'T2WI': 'T2WI',
  77. 't1wi': 'T1WI', # Handle case variations
  78. 't2wi': 'T2WI',
  79. 'flair': 'FLAIR',
  80. 'flair_sg': 'FLAIR_SG'
  81. }
  82. def find_patient_folders(self):
  83. """Find all patient folders (6-digit numeric folders)"""
  84. patient_folders = []
  85. for item in self.input_dir.iterdir():
  86. if item.is_dir() and item.name.isdigit() and len(item.name) == 6:
  87. patient_folders.append(item)
  88. return sorted(patient_folders)
  89. def find_protocol_folders(self, patient_folder):
  90. """Find protocol folders within a patient folder"""
  91. protocol_folders = []
  92. for item in patient_folder.iterdir():
  93. if item.is_dir():
  94. protocol_folders.append(item)
  95. return protocol_folders
  96. def get_dicom_files(self, protocol_folder):
  97. """Get all DICOM files from a protocol folder, excluding PNG files"""
  98. dicom_files = []
  99. for file in protocol_folder.iterdir():
  100. if file.is_file() and not file.suffix.lower() == '.png':
  101. if self.is_dicom_file(file):
  102. dicom_files.append(file)
  103. return sorted(dicom_files)
  104. def is_dicom_file(self, file_path):
  105. """Check if file is a valid DICOM file"""
  106. try:
  107. pydicom.dcmread(file_path, stop_before_pixels=True)
  108. return True
  109. except:
  110. return False
  111. def standardize_protocol_name(self, protocol_name):
  112. """Standardize protocol names using mapping"""
  113. return self.protocol_mapping.get(protocol_name, protocol_name.upper())
  114. def extract_comprehensive_metadata(self, protocol_folder, dicom_files):
  115. """Extract comprehensive metadata from DICOM series for MS research"""
  116. if not dicom_files:
  117. return None
  118. # Read first and last DICOM files for comprehensive metadata
  119. first_ds = pydicom.dcmread(dicom_files[0])
  120. last_ds = pydicom.dcmread(dicom_files[-1]) if len(dicom_files) > 1 else first_ds
  121. # Helper function to safely get DICOM attribute
  122. def safe_get(ds, attr, default=None):
  123. try:
  124. value = getattr(ds, attr, default)
  125. if hasattr(value, 'value'): # Handle DataElement objects
  126. return value.value
  127. return value
  128. except:
  129. return default
  130. # Convert MultiValue objects to lists
  131. def convert_multivalue(value):
  132. if hasattr(value, '__iter__') and not isinstance(value, (str, bytes)):
  133. try:
  134. return list(value)
  135. except:
  136. return str(value)
  137. return value
  138. metadata = {
  139. # === PATIENT INFORMATION ===
  140. "PatientID": safe_get(first_ds, 'PatientID', 'Unknown'),
  141. "PatientName": str(safe_get(first_ds, 'PatientName', 'Anonymous')),
  142. "PatientAge": safe_get(first_ds, 'PatientAge', 'Unknown'),
  143. "PatientSex": safe_get(first_ds, 'PatientSex', 'Unknown'),
  144. "PatientBirthDate": safe_get(first_ds, 'PatientBirthDate', 'Unknown'),
  145. "PatientWeight": safe_get(first_ds, 'PatientWeight', None),
  146. "PatientSize": safe_get(first_ds, 'PatientSize', None),
  147. "PatientPosition": safe_get(first_ds, 'PatientPosition', 'Unknown'),
  148. # === STUDY INFORMATION ===
  149. "StudyDate": safe_get(first_ds, 'StudyDate', 'Unknown'),
  150. "StudyTime": safe_get(first_ds, 'StudyTime', 'Unknown'),
  151. "StudyDescription": safe_get(first_ds, 'StudyDescription', 'Unknown'),
  152. "StudyInstanceUID": safe_get(first_ds, 'StudyInstanceUID', 'Unknown'),
  153. "StudyID": safe_get(first_ds, 'StudyID', 'Unknown'),
  154. "AccessionNumber": safe_get(first_ds, 'AccessionNumber', 'Unknown'),
  155. "ReferringPhysicianName": str(safe_get(first_ds, 'ReferringPhysicianName', 'Unknown')),
  156. "InstitutionName": safe_get(first_ds, 'InstitutionName', 'Unknown'),
  157. "InstitutionAddress": safe_get(first_ds, 'InstitutionAddress', 'Unknown'),
  158. "InstitutionalDepartmentName": safe_get(first_ds, 'InstitutionalDepartmentName', 'Unknown'),
  159. # === SERIES INFORMATION ===
  160. "SeriesDescription": safe_get(first_ds, 'SeriesDescription', 'Unknown'),
  161. "SeriesNumber": safe_get(first_ds, 'SeriesNumber', 'Unknown'),
  162. "SeriesInstanceUID": safe_get(first_ds, 'SeriesInstanceUID', 'Unknown'),
  163. "SeriesDate": safe_get(first_ds, 'SeriesDate', 'Unknown'),
  164. "SeriesTime": safe_get(first_ds, 'SeriesTime', 'Unknown'),
  165. "ProtocolName": safe_get(first_ds, 'ProtocolName', protocol_folder.name),
  166. "Modality": safe_get(first_ds, 'Modality', 'MR'),
  167. # === MR ACQUISITION PARAMETERS (Critical for MS research) ===
  168. "MagneticFieldStrength": safe_get(first_ds, 'MagneticFieldStrength', None),
  169. "SliceThickness": safe_get(first_ds, 'SliceThickness', None),
  170. "SpacingBetweenSlices": safe_get(first_ds, 'SpacingBetweenSlices', None),
  171. "RepetitionTime": safe_get(first_ds, 'RepetitionTime', None),
  172. "EchoTime": safe_get(first_ds, 'EchoTime', None),
  173. "InversionTime": safe_get(first_ds, 'InversionTime', None),
  174. "FlipAngle": safe_get(first_ds, 'FlipAngle', None),
  175. "EchoNumbers": safe_get(first_ds, 'EchoNumbers', None),
  176. "NumberOfAverages": safe_get(first_ds, 'NumberOfAverages', None),
  177. "ImagingFrequency": safe_get(first_ds, 'ImagingFrequency', None),
  178. "ImagedNucleus": safe_get(first_ds, 'ImagedNucleus', None),
  179. "MagneticFieldStrength": safe_get(first_ds, 'MagneticFieldStrength', None),
  180. # === SPATIAL INFORMATION ===
  181. "PixelSpacing": convert_multivalue(safe_get(first_ds, 'PixelSpacing', None)),
  182. "Rows": safe_get(first_ds, 'Rows', None),
  183. "Columns": safe_get(first_ds, 'Columns', None),
  184. "AcquisitionMatrix": convert_multivalue(safe_get(first_ds, 'AcquisitionMatrix', None)),
  185. "FOVDimensions": convert_multivalue(safe_get(first_ds, 'FOVDimensions', None)),
  186. "SliceLocation": safe_get(first_ds, 'SliceLocation', None),
  187. "ImageOrientationPatient": convert_multivalue(safe_get(first_ds, 'ImageOrientationPatient', None)),
  188. "ImagePositionPatient": convert_multivalue(safe_get(first_ds, 'ImagePositionPatient', None)),
  189. # === SEQUENCE INFORMATION (Important for MS protocols) ===
  190. "ImageType": convert_multivalue(safe_get(first_ds, 'ImageType', 'Unknown')),
  191. "ScanningSequence": convert_multivalue(safe_get(first_ds, 'ScanningSequence', 'Unknown')),
  192. "SequenceVariant": convert_multivalue(safe_get(first_ds, 'SequenceVariant', 'Unknown')),
  193. "ScanOptions": convert_multivalue(safe_get(first_ds, 'ScanOptions', 'Unknown')),
  194. "MRAcquisitionType": safe_get(first_ds, 'MRAcquisitionType', 'Unknown'),
  195. "SequenceName": safe_get(first_ds, 'SequenceName', 'Unknown'),
  196. "PulseSequenceName": safe_get(first_ds, 'PulseSequenceName', 'Unknown'),
  197. # === EQUIPMENT INFORMATION ===
  198. "Manufacturer": safe_get(first_ds, 'Manufacturer', 'Unknown'),
  199. "ManufacturerModelName": safe_get(first_ds, 'ManufacturerModelName', 'Unknown'),
  200. "SoftwareVersions": convert_multivalue(safe_get(first_ds, 'SoftwareVersions', 'Unknown')),
  201. "DeviceSerialNumber": safe_get(first_ds, 'DeviceSerialNumber', 'Unknown'),
  202. "StationName": safe_get(first_ds, 'StationName', 'Unknown'),
  203. # === CONTRAST AND IMAGE PARAMETERS ===
  204. "ContrastBolusAgent": safe_get(first_ds, 'ContrastBolusAgent', None),
  205. "ContrastBolusRoute": safe_get(first_ds, 'ContrastBolusRoute', None),
  206. "ContrastBolusVolume": safe_get(first_ds, 'ContrastBolusVolume', None),
  207. "WindowCenter": convert_multivalue(safe_get(first_ds, 'WindowCenter', None)),
  208. "WindowWidth": convert_multivalue(safe_get(first_ds, 'WindowWidth', None)),
  209. "RescaleIntercept": safe_get(first_ds, 'RescaleIntercept', None),
  210. "RescaleSlope": safe_get(first_ds, 'RescaleSlope', None),
  211. # === TIMING AND PHYSIOLOGICAL ===
  212. "AcquisitionTime": safe_get(first_ds, 'AcquisitionTime', None),
  213. "ContentTime": safe_get(first_ds, 'ContentTime', None),
  214. "TriggerTime": safe_get(first_ds, 'TriggerTime', None),
  215. "HeartRate": safe_get(first_ds, 'HeartRate', None),
  216. "CardiacNumberOfImages": safe_get(first_ds, 'CardiacNumberOfImages', None),
  217. # === BODY PART AND POSITIONING ===
  218. "BodyPartExamined": safe_get(first_ds, 'BodyPartExamined', 'Unknown'),
  219. "PatientPosition": safe_get(first_ds, 'PatientPosition', 'Unknown'),
  220. "ViewPosition": safe_get(first_ds, 'ViewPosition', None),
  221. # === SLICE INFORMATION ===
  222. "SliceLocation_First": safe_get(first_ds, 'SliceLocation', None),
  223. "SliceLocation_Last": safe_get(last_ds, 'SliceLocation', None),
  224. "InstanceNumber_First": safe_get(first_ds, 'InstanceNumber', None),
  225. "InstanceNumber_Last": safe_get(last_ds, 'InstanceNumber', None),
  226. # === FILE AND PROCESSING INFORMATION ===
  227. "NumberOfSlices": len(dicom_files),
  228. "DicomFiles": [f.name for f in dicom_files],
  229. "ProtocolFolder": protocol_folder.name,
  230. "OriginalPath": str(protocol_folder),
  231. "ConversionDate": datetime.now().isoformat(),
  232. "ConversionMethod": self.method,
  233. # === MS-SPECIFIC RESEARCH METADATA ===
  234. "MSProtocolType": self.standardize_protocol_name(protocol_folder.name),
  235. "IsFlairSequence": "FLAIR" in protocol_folder.name.upper(),
  236. "IsT1Weighted": "T1" in protocol_folder.name.upper(),
  237. "IsT2Weighted": "T2" in protocol_folder.name.upper(),
  238. "IsSuppressedFlair": "SG" in protocol_folder.name.upper(),
  239. # === ADDITIONAL TECHNICAL PARAMETERS ===
  240. "BitsAllocated": safe_get(first_ds, 'BitsAllocated', None),
  241. "BitsStored": safe_get(first_ds, 'BitsStored', None),
  242. "HighBit": safe_get(first_ds, 'HighBit', None),
  243. "PixelRepresentation": safe_get(first_ds, 'PixelRepresentation', None),
  244. "PhotometricInterpretation": safe_get(first_ds, 'PhotometricInterpretation', None),
  245. "SamplesPerPixel": safe_get(first_ds, 'SamplesPerPixel', None),
  246. # === RESEARCH-SPECIFIC QUALITY METRICS ===
  247. "SNR_Estimated": None, # Can be calculated post-conversion
  248. "ImageQualityScore": None, # For future quality assessment
  249. "MotionArtifacts": None, # For future artifact detection
  250. }
  251. # Convert numpy arrays and special types to JSON-serializable formats
  252. for key, value in metadata.items():
  253. if isinstance(value, np.ndarray):
  254. metadata[key] = value.tolist()
  255. elif hasattr(value, '__iter__') and not isinstance(value, (str, bytes)) and value is not None:
  256. try:
  257. metadata[key] = list(value)
  258. except:
  259. metadata[key] = str(value)
  260. elif value is not None and not isinstance(value, (int, float, str, bool, list, dict)):
  261. metadata[key] = str(value)
  262. return metadata
  263. def convert_with_dicom2nifti(self, protocol_folder, output_path):
  264. """Convert using dicom2nifti library (fixed - removed invalid reorient parameter)"""
  265. try:
  266. # Fixed: removed the invalid 'reorient' parameter
  267. dicom_series_to_nifti(str(protocol_folder), str(output_path))
  268. return True
  269. except Exception as e:
  270. logging.error(f"dicom2nifti conversion failed for {protocol_folder}: {e}")
  271. return False
  272. def convert_with_dcm2niix(self, protocol_folder, output_path):
  273. """Convert using dcm2niix"""
  274. try:
  275. # Check if dcm2niix is available
  276. subprocess.run(['dcm2niix', '-h'], capture_output=True, check=True)
  277. # Run dcm2niix with research-optimized settings
  278. cmd = [
  279. 'dcm2niix',
  280. '-z', 'y', # Compress output
  281. '-f', output_path.stem, # Output filename
  282. '-o', str(output_path.parent), # Output directory
  283. '-b', 'y', # Create BIDS sidecar JSON
  284. '-ba', 'y', # Anonymize BIDS
  285. '-v', 'y', # Verbose output
  286. str(protocol_folder)
  287. ]
  288. result = subprocess.run(cmd, capture_output=True, text=True)
  289. if result.returncode == 0:
  290. return True
  291. else:
  292. logging.error(f"dcm2niix failed for {protocol_folder}: {result.stderr}")
  293. return False
  294. except (subprocess.CalledProcessError, FileNotFoundError):
  295. logging.error("dcm2niix not found. Install from: https://github.com/rordenlab/dcm2niix")
  296. return False
  297. def convert_with_nibabel(self, protocol_folder, output_path):
  298. """Convert using nibabel with enhanced header preservation"""
  299. try:
  300. dicom_files = self.get_dicom_files(protocol_folder)
  301. if not dicom_files:
  302. return False
  303. # Read DICOM files
  304. slices = []
  305. for dicom_file in dicom_files:
  306. ds = pydicom.dcmread(dicom_file)
  307. slices.append(ds)
  308. # Sort by slice location or instance number
  309. try:
  310. slices.sort(key=lambda x: float(getattr(x, 'SliceLocation', 0)))
  311. except:
  312. try:
  313. slices.sort(key=lambda x: int(getattr(x, 'InstanceNumber', 0)))
  314. except:
  315. logging.warning(f"Could not sort slices for {protocol_folder}")
  316. # Create 3D array
  317. pixel_arrays = [s.pixel_array.astype(np.float32) for s in slices]
  318. volume = np.stack(pixel_arrays, axis=-1)
  319. # Get voxel spacing and create proper affine matrix
  320. ds = slices[0]
  321. pixel_spacing = getattr(ds, 'PixelSpacing', [1.0, 1.0])
  322. slice_thickness = getattr(ds, 'SliceThickness', 1.0)
  323. # Create more accurate affine matrix
  324. affine = np.eye(4)
  325. affine[0, 0] = float(pixel_spacing[0])
  326. affine[1, 1] = float(pixel_spacing[1])
  327. affine[2, 2] = float(slice_thickness)
  328. # Try to get image position for better spatial alignment
  329. try:
  330. img_pos = getattr(ds, 'ImagePositionPatient', [0, 0, 0])
  331. affine[0, 3] = float(img_pos[0])
  332. affine[1, 3] = float(img_pos[1])
  333. affine[2, 3] = float(img_pos[2])
  334. except:
  335. pass
  336. # Create NIfTI image with enhanced header
  337. nifti_img = nib.Nifti1Image(volume, affine)
  338. # Set additional header information
  339. header = nifti_img.header
  340. header.set_xyzt_units('mm', 'sec')
  341. # Set data type appropriately
  342. if volume.dtype == np.float32:
  343. header.set_data_dtype(np.float32)
  344. else:
  345. header.set_data_dtype(volume.dtype)
  346. nib.save(nifti_img, output_path)
  347. return True
  348. except Exception as e:
  349. logging.error(f"nibabel conversion failed for {protocol_folder}: {e}")
  350. return False
  351. def process_patient(self, patient_folder):
  352. """Process all protocols for a single patient"""
  353. patient_id = patient_folder.name
  354. logging.info(f"Processing patient: {patient_id}")
  355. # Create patient output directory
  356. patient_output_dir = self.output_dir / patient_id
  357. patient_output_dir.mkdir(parents=True, exist_ok=True)
  358. # Find protocol folders
  359. protocol_folders = self.find_protocol_folders(patient_folder)
  360. if not protocol_folders:
  361. logging.warning(f"No protocol folders found for patient {patient_id}")
  362. return
  363. patient_conversions = 0
  364. patient_failures = 0
  365. for protocol_folder in protocol_folders:
  366. protocol_name = protocol_folder.name
  367. standardized_protocol = self.standardize_protocol_name(protocol_name)
  368. # Check if folder contains DICOM files
  369. dicom_files = self.get_dicom_files(protocol_folder)
  370. if not dicom_files:
  371. logging.warning(f"No DICOM files found in {protocol_folder}")
  372. patient_failures += 1
  373. continue
  374. # Generate output filename: {6-digit patientID}_{protocol}.nii.gz
  375. filename = f"{patient_id}_{standardized_protocol}.nii.gz"
  376. nifti_path = patient_output_dir / filename
  377. json_path = patient_output_dir / filename.replace('.nii.gz', '.json')
  378. logging.info(f" Converting {protocol_name} -> {filename}")
  379. # Convert based on selected method
  380. success = False
  381. if self.method == 'dicom2nifti':
  382. success = self.convert_with_dicom2nifti(protocol_folder, nifti_path)
  383. elif self.method == 'dcm2niix':
  384. success = self.convert_with_dcm2niix(protocol_folder, nifti_path)
  385. elif self.method == 'nibabel':
  386. success = self.convert_with_nibabel(protocol_folder, nifti_path)
  387. if success:
  388. patient_conversions += 1
  389. self.converted_series += 1
  390. # Using regular characters instead of special Unicode characters
  391. logging.info(f" [SUCCESS] Successfully converted: {nifti_path}")
  392. # Save comprehensive metadata as JSON
  393. metadata = self.extract_comprehensive_metadata(protocol_folder, dicom_files)
  394. if metadata:
  395. with open(json_path, 'w', encoding='utf-8') as f:
  396. json.dump(metadata, f, indent=2, default=str, ensure_ascii=False)
  397. logging.info(f" [SUCCESS] Metadata saved: {json_path}")
  398. else:
  399. patient_failures += 1
  400. self.failed_series += 1
  401. # Using regular characters instead of special Unicode characters
  402. logging.error(f" [FAILED] Failed to convert: {protocol_folder}")
  403. logging.info(f"Patient {patient_id} completed: {patient_conversions} successful, {patient_failures} failed")
  404. self.processed_patients += 1
  405. def convert_all(self):
  406. """Convert all patients and protocols"""
  407. patient_folders = self.find_patient_folders()
  408. if not patient_folders:
  409. logging.error("No patient folders (6-digit numeric) found in input directory")
  410. return
  411. logging.info(f"Found {len(patient_folders)} patient folders to process")
  412. logging.info(f"Expected protocols per patient: FLAIR, FLAIR_SG, T1WI, T2WI")
  413. for i, patient_folder in enumerate(patient_folders, 1):
  414. logging.info(f"\nProcessing patient {i}/{len(patient_folders)}: {patient_folder.name}")
  415. self.process_patient(patient_folder)
  416. self.print_summary()
  417. def print_summary(self):
  418. """Print conversion summary"""
  419. print("\n" + "=" * 80)
  420. print("MS DATASET DICOM TO NIFTI CONVERSION SUMMARY")
  421. print("=" * 80)
  422. print(f"Input directory: {self.input_dir}")
  423. print(f"Output directory: {self.output_dir}")
  424. print(f"Conversion method: {self.method}")
  425. print("-" * 80)
  426. print(f"Patients processed: {self.processed_patients}")
  427. print(f"Protocol series successfully converted: {self.converted_series}")
  428. print(f"Protocol series failed: {self.failed_series}")
  429. print(f"Total protocol series: {self.converted_series + self.failed_series}")
  430. if (self.converted_series + self.failed_series) > 0:
  431. success_rate = (self.converted_series / (self.converted_series + self.failed_series) * 100)
  432. print(f"Success rate: {success_rate:.1f}%")
  433. else:
  434. print("Success rate: N/A")
  435. print("-" * 80)
  436. print("OUTPUT STRUCTURE:")
  437. print("Output_Directory/")
  438. print(" |-- 001/")
  439. print(" | |-- 001_FLAIR.nii.gz")
  440. print(" | |-- 001_FLAIR.json")
  441. print(" | |-- 001_FLAIR_SG.nii.gz")
  442. print(" | |-- 001_FLAIR_SG.json")
  443. print(" | |-- 001_T1WI.nii.gz")
  444. print(" | |-- 001_T1WI.json")
  445. print(" | |-- 001_T2WI.nii.gz")
  446. print(" | |-- 001_T2WI.json")
  447. print(" |-- 002/")
  448. print(" |-- ...")
  449. print("-" * 80)
  450. print("RESEARCH-READY FEATURES:")
  451. print("+ MS-specific protocol standardization")
  452. print("+ Comprehensive DICOM header preservation")
  453. print("+ Research-quality NIfTI format with proper spatial information")
  454. print("+ Detailed JSON metadata files with >50 DICOM attributes")
  455. print("+ Professional naming convention: {PatientID}_{Protocol}.nii.gz")
  456. print("+ UTF-8 encoding support for international characters")
  457. print("+ Enhanced spatial alignment and orientation")
  458. if self.method == 'dcm2niix':
  459. print("+ BIDS-compatible output")
  460. print("=" * 80)
  461. # Example usage
  462. if __name__ == "__main__":
  463. # MS Dataset directories
  464. input_directory = r"E:\MBashiri\Thesis\p6\Data\MS_100_patient_full"
  465. output_directory = r"E:\MBashiri\Thesis\p6\Data\MS_100_patient_nifti"
  466. print("MS DATASET DICOM TO NIFTI CONVERTER - RESEARCH EDITION")
  467. print("=" * 60)
  468. print("Directory Structure Expected:")
  469. print("Input/")
  470. print(" |-- 001/ # 6-digit patient ID")
  471. print(" | |-- FLAIR/ # Protocol folders")
  472. print(" | |-- FLAIR_SG/")
  473. print(" | |-- T1WI/")
  474. print(" | |-- T2WI/")
  475. print(" |-- 002/")
  476. print(" |-- ...")
  477. print("=" * 60)
  478. print("Available conversion methods:")
  479. print("1. 'dicom2nifti' - Reliable Python library (recommended)")
  480. print("2. 'dcm2niix' - Most comprehensive (requires installation)")
  481. print("3. 'nibabel' - Enhanced fallback method with better header preservation")
  482. print("=" * 60)
  483. # Initialize converter with dicom2nifti (recommended for MS research)
  484. converter = MSDatasetDicomToNiftiConverter(
  485. input_directory=input_directory,
  486. output_directory=output_directory,
  487. method='dicom2nifti' # Change to 'dcm2niix' if available
  488. )
  489. # Start conversion
  490. converter.convert_all()

dicom_to_nifti.py at commit c265bae, under MIT · at the source

Overview

  1. Biomedical Engineering Faculty, Sahand University of Technology,Tabriz, Iran
  2. Faculty of Physics, University of Tabriz,Tabriz, Iran
  3. Department of Engineering Sciences, Faculty of Advanced Technologies, University of Mohaghegh Ardabili,Namin, Iran
  4. Radiology Department, Tabriz University of Medical Sciences,Tabriz, Iran
Journal: Scientific data, volume 13, issue 1, article 867
Dates: received 11 October 2025; accepted 31 March 2026; published online 14 April 2026
Type: Data paper · Language: English
License: CC BY-NC-ND
Identifiers: DOI 10.1038/s41597-026-07184-5 · PMID 41980977 · PMCID PMC13249843 · OpenAlex W7154269800
Open access: gold, a free copy (OpenAlex)
Status: code verified
Categories: structural MRI / diffusion (modality), human (organism), multiple sclerosis (population), methods / tools (subfield)
Methods: Connectivity
MeSH: Magnetic Resonance Imaging*, Multiple Sclerosis*, Datasets as Topic, Female, Humans, Male, White Matter (* major topic)
Journal subjects: Data Descriptor
Topic: Medical Image Segmentation Techniques (Computer Vision and Pattern Recognition, Computer Science), according to OpenAlex
Citations: cited by 4 papers (Europe PMC); 30 references in the paper

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

License: MIT
State: the link answers, verified on 29 September 2026
Evidence: files inventoried
Commit: c265bae327691c279ff6651a98e264d70103def7, 14 February 2026
Languages: Python (24)
Size: 43 files, 24 scripts
Software Heritage: not archived
Found in: “Code availability”
Holds: README, license file, environment (requirements.txt)
Not found: CITATION.cff, tests, continuous integration, documentation
Tools: NumPy (15 files), Keras (10 files), TensorFlow (10 files), NiBabel (6 files), pandas (6 files), pydicom (6 files), SciPy (4 files), OpenCV (3 files), Matplotlib (2 files), scikit-image (2 files), scikit-learn (2 files), seaborn (2 files), dcm2niix (1 file)
Availability: 1 check, the latest on 29 September 2026: the link answers
  • 29 September 2026: the link answers
26 files

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:

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

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://doi.org/10.1038/s41597-026-07184-5

BibTeX

@article{bawil2026multiple,
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/s41597-026-07184-5},
url = {https://doi.org/10.1038/s41597-026-07184-5},
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/04/14
VL - 13
IS - 1
SP - 867
SN - 2052-4463
PB - Nature Publishing Group
DO - 10.1038/s41597-026-07184-5
UR - https://doi.org/10.1038/s41597-026-07184-5
LA - en
ER -

CSL-JSON

{
"id": "10.1038/s41597-026-07184-5",
"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": "Sci Data",
"volume": "13",
"issue": "1",
"page": "867",
"DOI": "10.1038/s41597-026-07184-5",
"PMID": "41980977",
"PMCID": "PMC13249843",
"ISSN": "2052-4463",
"publisher": "Nature Publishing Group",
"URL": "https://doi.org/10.1038/s41597-026-07184-5",
"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 imaging
In 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 online
In 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 health
In 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 biology
In 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 <i>q</i>-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 medicine
In 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 surgery
In 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 intelligence
In 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 Sclerosis
Journal: 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: Epilepsia
In 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.

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.