def gen_dicom_list(DicomDir, refSeries): from pydicom.filereader import read_dicomdir basedir = os.path.dirname(DicomDir) + '/DICOM' lstFilesDCM = [] # create an empty list dicom_dir = read_dicomdir(DicomDir) for patient_record in dicom_dir.patient_records: if (hasattr(patient_record, 'PatientID') and hasattr(patient_record, 'PatientName')): studies = patient_record.children for study in studies: all_series = study.children for series in all_series: if (int(series.SeriesNumber) == int(refSeries)): data = series.children for img in data: fileID = img.ReferencedFileID imgtype = img.DirectoryRecordType if (fileID[0] == 'DICOM' and imgtype == 'IMAGE'): if (len(fileID) == 3): filename = basedir + '/' + fileID[ 1] + '/' + fileID[2] else: filename = basedir + '/' + fileID[1] lstFilesDCM.append(filename) return lstFilesDCM
def sortsessions(session: str, subjectid: str='', sessionid: str='', rename: bool=False, ext: str='', nosort: bool=False, pattern: str='.*\.(IMA|dcm)$') -> None: """ :param session: The root folder containing the source [sub/][ses/]dicomfiles or the DICOMDIR file :param subjectid: The prefix of the sub folders in session :param sessionid: The prefix of the ses folders in sub folder :param rename: Boolean to rename the DICOM files to a PatientName_SeriesNumber_SeriesDescription_AcquisitionNumber_InstanceNumber scheme :param ext: The file extension after sorting (empty value keeps original file extension) :param nosort: Boolean to skip sorting of DICOM files into SeriesNumber-SeriesDescription directories (useful in combination with -r for renaming only) :param pattern: The regular expression pattern used in re.match() to select the dicom files :return: Nothing """ # Input checking session = os.path.abspath(os.path.expanduser(session)) # Define the sessionfolder, collect all DICOM files and run sortsession() if subjectid: # Do a recursive search, assuming session is a foldername, not a DICOMDIR file for subfolder in bids.lsdirs(session, subjectid + '*'): if sessionid: sessionfolders = bids.lsdirs(subfolder, sessionid + '*') else: sessionfolders = [subfolder] for sessionfolder in sessionfolders: dicomfiles = [os.path.join(sessionfolder, dcmfile) for dcmfile in os.listdir(sessionfolder) if re.match(pattern, dcmfile)] sortsession(sessionfolder, dicomfiles, rename, ext, nosort) else: if os.path.basename(session) == 'DICOMDIR': from pydicom.filereader import read_dicomdir dicomdir = read_dicomdir(session) sessionfolder = os.path.dirname(session) sessionfolder_ = sessionfolder for patient in dicomdir.patient_records: if len(dicomdir.patient_records) > 1: sessionfolder = os.path.join(sessionfolder_, f'sub-{cleanup(str(patient.PatientName))}') for n, study in enumerate(patient.children, 1): # TODO: Check order if len(patient.children) > 1: sessionfolder = os.path.join(sessionfolder_, f'ses-{n:02}{cleanup(str(study.StudyDescription))}') # TODO: Leave out StudyDescrtiption? print(f'WARNING: the session index-number "{n:02}" is not necessarily meaningful: {sessionfolder}') dicomfiles = [] for series in study.children: dicomfiles.extend([os.path.join(sessionfolder_, *image.ReferencedFileID) for image in series.children]) sortsession(sessionfolder, dicomfiles, rename, ext, nosort) else: sessionfolder = session dicomfiles = [os.path.join(sessionfolder,dcmfile) for dcmfile in os.listdir(sessionfolder) if re.match(pattern, dcmfile)] sortsession(sessionfolder, dicomfiles, rename, ext, nosort)
def run(self): if self.dicomdir.endswith('DICOMDIR'): dicomDir = read_dicomdir(self.dicomdir) self.parserDICOMDIR(dicomDir,os.path.dirname(self.dicomdir)) logging.info('DICOMFileDirectory: Parsing of DICOMDIR completed') else: if not os.path.isdir(self.dicomdir): raise DicomException('%s is not a directory!' % self.dicomdir) else: self.loadFilesDirectory() logging.info('DICOMFileDirectory: Parsing of dicom directory completed')
def run(self): if self.dicomdir.endswith('DICOMDIR'): dicomDir = read_dicomdir(self.dicomdir) self.parserDICOMDIR(dicomDir, os.path.dirname(self.dicomdir)) logging.info('DICOMFileDirectory: Parsing of DICOMDIR completed') else: if not os.path.isdir(self.dicomdir): raise DicomException('%s is not a directory!' % self.dicomdir) else: self.loadFilesDirectory() logging.info( 'DICOMFileDirectory: Parsing of dicom directory completed')
def __init__(self, source='', destination=''): self.inputPath = Path(source).expanduser() self.outputPath = Path(destination).expanduser() # self.dcmDirFilePath = self.inputPath self.dcmDirFilePath = self.inputPath / "DICOMDIR" # 測試用路徑, 自動加上DICOMDIR """讀取DICOMDIR檔案,下一行是讀取 DICOMDIR 檔案的物件""" self.DICOMDIRFILE = read_dicomdir(self.dcmDirFilePath) self.pathL1 = '' self.pathL2 = '' self.pathL3 = '' DcmDIRlDict = {}
def setPatientView(self): self.patientModel.clear() dialog = FileDialog() self.filepath = dialog.openFileNameDialog(title="Open DICOMDIR", typeFile=CS_DICOMDIR) if self.filepath: self.base_dir = dirname(self.filepath) self.dicom_dir = read_dicomdir(self.filepath) for patient in range(len(self.dicom_dir.patient_records)): ID = self.dicom_dir.patient_records[patient].PatientID NAME = str(self.dicom_dir.patient_records[patient].PatientName ).replace('^', ' ') it = QtGui.QStandardItem("%s\t%s" % (ID, NAME)) self.patientModel.appendRow(it)
def get_series_info(DicomDir): # adapted from plot_read_dicom_directory at # https://pydicom.github.io/pydicom/stable/auto_examples/input_output/plot_read_dicom_directory.html from pydicom.filereader import read_dicomdir info = {} series_num = [] protocols = [] #create an empty list # find all Series in the folder dicom_dir = read_dicomdir(DicomDir) for patient_record in dicom_dir.patient_records: if (hasattr(patient_record, 'PatientID') and hasattr(patient_record, 'PatientName')): studies = patient_record.children for study in studies: all_series = study.children for series in all_series: if (hasattr(series, 'SeriesNumber') and hasattr(series, 'ProtocolName')): if int(series.SeriesNumber) > 0: series_num.append(series.SeriesNumber) protocols.append(series.ProtocolName) info['series'] = series_num info['protocol'] = protocols return info
import pydicom from pydicom.filereader import read_dicomdir # pydicom.debug() if __name__ == "__main__": print("------------------------------------------------------------") print("Example program showing DICOMDIR contents, assuming standard") print("Patient -> Study -> Series -> Images hierarchy") print("------------------------------------------------------------") print() if len(sys.argv) > 1: filepath = sys.argv[1] if os.path.isdir(filepath): # only gave directory, add standard name filepath = os.path.join(filepath, "DICOMDIR") dcmdir = read_dicomdir(filepath) base_dir = os.path.dirname(filepath) else: # Read standard "DICOMDIR" filename from current directory dcmdir = pydicom.read_dicomdir() base_dir = "." for patrec in dcmdir.patient_records: if hasattr(patrec, 'PatientID') and hasattr(patrec, 'PatientsName'): print("Patient: {0.PatientID}: {0.PatientsName}".format(patrec)) studies = patrec.children for study in studies: print(" Study {0.StudyID}: {0.StudyDate}:" " {0.StudyDescription}".format(study)) all_series = study.children for series in all_series:
dicompath = '/home/seolen/disk/CTav/DICOMDIR' import pydicom from pydicom.filereader import read_dicomdir from os.path import dirname, join dicom_dir = read_dicomdir(dicompath) base_dir = dirname(dicompath) # patients.txt log_filename = './patients2.txt' open(log_filename, 'w+').close log = open(log_filename, 'a+') for patient_record in dicom_dir.patient_records: if (hasattr(patient_record, 'PatientID') and hasattr(patient_record, 'PatientName')): print("Patient: {}: {}".format(patient_record.PatientID, patient_record.PatientName)) studies = patient_record.children # got through each serie for study in studies: print(" " * 4 + "Study {}: {}: {}".format(study.StudyID, study.StudyDate, study.StudyDescription)) all_series = study.children # go through each serie for series in all_series: image_count = len(series.children) # Write basic series info and image count
# fetch the path to the test data flesh_threshold = -200 bone_threshold = 220 correctedHeight = 550 zoom_scaling = .125 SAVEPATH = "/path/to/save/" LOADPATH = "/path/to/load/" DICOMDIRS_PATHS = [] # Complete with DICOM directories # Read the DICOM directories dicom_dirs = [] for path in DICOMDIRS_PATHS: dicom_dirs.append({ "dicom": read_dicomdir(LOADPATH + path + "/DICOMDIR"), "path": LOADPATH + path }) # find the maximum height in the scans maxHeight = 0 scans = [] for d in dicom_dirs: for patient_record in d["dicom"].patient_records: for study in patient_record.children: for series in study.children: if len(series.children) > 10: maxHeight = max(maxHeight, len(series.children)) scans.append({'path': d['path'], 'series': series})
def write_message(self, line): self.handler.writelines(line) def close(self): self.handler.close() if __name__ == "__main__": args = argparse.ArgumentParser(description="anonymization program") args.add_argument("--dicomdir_path", help="full path to DICOMDIR" ) #"/raid/seanyu/check_hemmo/Image/0709_dicom-dir/" args = args.parse_args() print(args) dicomdir_file = read_dicomdir(os.path.join(args.dicomdir_path, "DICOMDIR")) file_object = Filehandler( filename=os.path.join(args.dicomdir_path, "anonymous_mapping.csv")) file_object.write_message( "select,subject_id,dir_order,date,time,series_num,series_modality,series_description,n_images,origin_file_start,origin_file_end\n" ) for patient in dicomdir_file.patient_records: these_studies, this_pid, *_ = parse_patient_record(patient) print("Processing Subject: %s" % (this_pid)) subj_path = os.path.join(args.dicomdir_path, "anonymous", this_pid) try: os.makedirs(subj_path) except: pass
# authors : Guillaume Lemaitre <*****@*****.**> # license : MIT from os.path import dirname, join from pprint import pprint import pydicom from pydicom.data import get_testdata_files from pydicom.filereader import read_dicomdir # fetch the path to the test data filepath = get_testdata_files('DICOMDIR')[0] print('Path to the DICOM directory: {}'.format(filepath)) # load the data dicom_dir = read_dicomdir(filepath) base_dir = dirname(filepath) # go through the patient record and print information for patient_record in dicom_dir.patient_records: if (hasattr(patient_record, 'PatientID') and hasattr(patient_record, 'PatientName')): print("Patient: {}: {}".format(patient_record.PatientID, patient_record.PatientName)) studies = patient_record.children # got through each serie for study in studies: print(" " * 4 + "Study {}: {}: {}".format(study.StudyID, study.StudyDate, study.StudyDescription)) all_series = study.children
def load_dicom_dir_file(self): # plt.imshow(dcm_dataset.pixel_array, cmap=plt.cm.bone) # plt.show() # fetch the path to the test data # filepath = get_testdata_files('DICOMDIR')[0] # filepath = 'D:/Projects/C++/Qt/5/BodySnitches/Builds/BodySnitches/!DicomDatasets/FantasticNine/09-Kydryavcev/2011.12.09/DICOMDIR' filepath = 'd:/Projects/BodySnitches/Builds/BodySnitches/DicomDatasets/FantasticNine/09-Kydryavcev/2011.12.09/DICOMDIR' print('Path to the DICOM directory: {}'.format(filepath)) # load the data dicom_dir = read_dicomdir(filepath) print('dicom_dir', dicom_dir) base_dir = dirname(filepath) print('base_dir', base_dir) # go through the patient record and print information print('patient_records type', type(dicom_dir.patient_records)) for patient_record in dicom_dir.patient_records: print('rrr:', type(patient_record)) if (hasattr(patient_record, 'PatientID') and hasattr(patient_record, 'PatientName')): print("Patient: {}: {}".format(patient_record.PatientID, patient_record.PatientName)) studies = patient_record.children # got through each serie for study in studies: print('sss:', type(study)) print(" " * 4 + "Study {}: {}: {}".format(study.StudyID, study.StudyDate, study.StudyDescription)) all_series = study.children # go through each serie for series in all_series: image_count = len(series.children) plural = ('', 's')[image_count > 1] # Write basic series info and image count # Put N/A in if no Series Description if 'SeriesDescription' not in series: series.SeriesDescription = "N/A" print(" " * 8 + "Series {}: {}: {} ({} image{})".format( series.SeriesNumber, series.Modality, series.SeriesDescription, image_count, plural)) # Open and read something from each image, for demonstration # purposes. For file quick overview of DICOMDIR, leave the # following out print(" " * 12 + "Reading images...") image_records = series.children image_filenames = [join(base_dir, *image_rec.ReferencedFileID) for image_rec in image_records] datasets = [pydicom.dcmread(image_filename) for image_filename in image_filenames] patient_names = set(ds.PatientName for ds in datasets) patient_IDs = set(ds.PatientID for ds in datasets) # List the image filenames print("\n" + " " * 12 + "Image filenames:") print(" " * 12, end=' ') pprint(image_filenames, indent=12) # Expect all images to have same patient name, id # Show the set of all names, IDs found (should each have one) print(" " * 12 + "Patient Names in images..: {}".format( patient_names)) print(" " * 12 + "Patient IDs in images..: {}".format( patient_IDs))
import matplotlib.pyplot as plt import pydicom import os from pydicom.filereader import dcmread, read_dicomdir from glob import glob import cv2 import numpy as np import shutil filepath = r"E:\BTSynchSGH\datasets\necklysis\input\mr\DICOMDIR" ds = read_dicomdir(filepath) base_dir = os.path.dirname(filepath) fps = [] for record in ds.DirectoryRecordSequence: if record.DirectoryRecordType == "IMAGE": # Extract the relative path to the DICOM file fps.append(os.path.join(base_dir, *record.ReferencedFileID)) num_images = len(fps) key = '' counter = 0 current_window_name = '' while counter < num_images: image = dcmread(fps[counter]).pixel_array image = np.stack([image] * 3, axis=-1) # stack for bgr/rgb image = cv2.normalize(image, dst=None, alpha=0,
def sortsessions(session: Path, subprefix: str = '', sesprefix: str = '', dicomfield: str = 'SeriesDescription', rename: bool = False, ext: str = '', nosort: bool = False, pattern: str = '.*\.(IMA|dcm)$', dryrun: bool = False) -> None: """ :param session: The root folder containing the source [sub/][ses/]dicomfiles or the DICOMDIR file :param subprefix: The prefix for searching the sub folders in session :param sesprefix: The prefix for searching the ses folders in sub folder :param dicomfield: The dicomfield that is used to construct the series folder name (e.g. SeriesDescription or ProtocolName, which are both used as fallback) :param rename: Boolean to rename the DICOM files to a PatientName_SeriesNumber_SeriesDescription_AcquisitionNumber_InstanceNumber scheme :param ext: The file extension after sorting (empty value keeps original file extension) :param nosort: Boolean to skip sorting of DICOM files into SeriesNumber-SeriesDescription directories (useful in combination with -r for renaming only) :param pattern: The regular expression pattern used in re.match() to select the dicom files :param dryrun: Boolean to just display the action :return: Nothing """ # Input checking session = Path(session) # Start logging bids.setup_logging() # Do a recursive call if subprefix is given if subprefix: for subfolder in bids.lsdirs(session, subprefix + '*'): if sesprefix: sessionfolders = bids.lsdirs(subfolder, sesprefix + '*') else: sessionfolders = [subfolder] for sessionfolder in sessionfolders: sortsessions(session=sessionfolder, dicomfield=dicomfield, rename=rename, ext=ext, nosort=nosort, pattern=pattern, dryrun=dryrun) # Use the DICOMDIR file if it is there if (session / 'DICOMDIR').is_file(): dicomdir = read_dicomdir(str(session / 'DICOMDIR')) sessionfolder = session for patient in dicomdir.patient_records: if len(dicomdir.patient_records) > 1: sessionfolder = session / f"sub-{cleanup(patient.PatientName)}" for n, study in enumerate(patient.children, 1): # TODO: Check order if len(patient.children) > 1: sessionfolder = session / f"ses-{n:02}{cleanup(study.StudyDescription)}" # TODO: Leave out StudyDescrtiption? Include PatientName/StudiesDescription? LOGGER.warning( f"The session index-number '{n:02}' is not necessarily meaningful: {sessionfolder}" ) dicomfiles = [ session.joinpath(*image.ReferencedFileID) for series in study.children for image in series.children ] sortsession(sessionfolder, dicomfiles, dicomfield, rename, ext, nosort, dryrun) else: dicomfiles = [ dcmfile for dcmfile in session.iterdir() if dcmfile.is_file() and re.match(pattern, str(dcmfile)) ] sortsession(session, dicomfiles, dicomfield, rename, ext, nosort, dryrun)
import pydicom from pydicom.filereader import read_dicomdir # pydicom.debug() if __name__ == "__main__": print("------------------------------------------------------------") print("Example program showing DICOMDIR contents, assuming standard") print("Patient -> Study -> Series -> Images hierarchy") print("------------------------------------------------------------") print() if len(sys.argv) > 1: filepath = sys.argv[1] if os.path.isdir(filepath): # only gave directory, add standard name filepath = os.path.join(filepath, "DICOMDIR") dcmdir = read_dicomdir(filepath) base_dir = os.path.dirname(filepath) else: # Read standard "DICOMDIR" filename from current directory dcmdir = read_dicomdir() base_dir = "." for patrec in dcmdir.patient_records: if hasattr(patrec, 'PatientID') and hasattr(patrec, 'PatientsName'): print("Patient: {0.PatientID}: {0.PatientsName}".format(patrec)) studies = patrec.children for study in studies: print(" Study {0.StudyID}: {0.StudyDate}:" " {0.StudyDescription}".format(study)) all_series = study.children for series in all_series:
print(t, loss.item()) optimizer.zero_grad() loss.backward() optimizer.step() import pathlib file = pathlib.Path.cwd().parent.parent/'PAVES Challenge' file=file.rglob('') for i in file: print(i) imgs = [i for i in file] print(i) import pydicom from pydicom.data import get_testdata_files from pydicom.filereader import read_dicomdir dicom_dir = read_dicomdir(file.absolute()) #ds = pydicom.dcmread("C:\Users\animeshs\OneDrive - NTNU\PAVES Challenge\Case 9") import cv2 import matplotlib.pylab as plt %matplotlib inline cvimg = cv2.imread(i,1) plt.imshow(i) import numpy as np Xrays256 = np.array([cv2.resize(cv2.imread(img,0), (256, 256), interpolation = cv2.INTER_AREA)/255 for img in imgs[:]]) print(Xrays256.shape) import pandas as pd validation = pd.read_table(dataP+'labels/val_list.txt.sel', sep=' ', header=None, index_col=0) train = pd.read_table(dataP+"labels/train_list.txt.sel", sep=' ',index_col=0,header=None)
import SimpleITK as sitk import numpy as np import cv2 import pydicom from os.path import dirname, join from pprint import pprint from pydicom.filereader import read_dicomdir case_path = r'D:\文件\毕设\DICOMDIR ' dicom_dir = read_dicomdir(case_path) base_dir = dirname(case_path) dirnames = "" for patient_record in dicom_dir.patient_records: if (hasattr(patient_record, 'PatientID') and hasattr(patient_record, 'PatientsName')): print("Patient: {}: {}".format(patient_record.PatientID, patient_record.PatientsName)) studies = patient_record.children # got through each serie for study in studies: print(" " * 4 + "Study {}: {}: {}".format(study.StudyID, study.StudyDate, study.StudyDescription)) all_series = study.children # go through each serie for series in all_series: image_count = len(series.children) plural = ('', 's')[image_count > 1]
def _getstudies(filepath): filepath = filepath dicom_dir = read_dicomdir(filepath) base_dir = dirname(filepath) allstudies = {} # go through the patient record and print information for patient_record in dicom_dir.patient_records: #if (hasattr(patient_record, 'PatientID') and hasattr(patient_record, 'PatientName')): #print("Patient: {}: {}".format(patient_record.PatientID, # patient_record.PatientName)) studies = patient_record.children # got through each serie for study in studies: #print(" " * 4 + "Study {}: {}: {}".format(study.StudyID, # study.StudyDate, # study.StudyDescription)) allstudies[study.StudyID] = [] all_series = study.children # go through each serie tmpseries = {} for series in all_series: image_count = len(series.children) plural = ('', 's')[image_count > 1] # Write basic series info and image count # Put N/A in if no Series Description if 'SeriesDescription' not in series: series.SeriesDescription = "N/A" #print(" " * 8 + "Series {}: {}: {} ({} image{})".format( # series.SeriesNumber, series.Modality, series.SeriesDescription, # image_count, plural)) # Open and read something from each image, for demonstration # purposes. For simple quick overview of DICOMDIR, leave the # following out #print(" " * 12 + "Reading images...") image_records = series.children image_filenames = [ join(base_dir, *image_rec.ReferencedFileID) for image_rec in image_records ] datasets = [ pydicom.dcmread(image_filename) for image_filename in image_filenames ] patient_names = set(ds.PatientName for ds in datasets) patient_IDs = set(ds.PatientID for ds in datasets) # List the image filenames #print("\n" + " " * 12 + "Image filenames:") #print(" " * 12, end=' ') #pprint(image_filenames, indent=12) # Expect all images to have same patient name, id # Show the set of all names, IDs found (should each have one) #print(" " * 12 + "Patient Names in images..: {}".format( # patient_names)) #print(" " * 12 + "Patient IDs in images..: {}".format( # patient_IDs)) tmpseries[int(series.SeriesNumber)] = datasets allstudies[study.StudyID].append(tmpseries) return allstudies