def write_header_cbct(ct, cbct, mid_slice, nSlices_wrong, path, output_prefix): # resample ct to cbct resolution new_volume = resample(ct, cbct) # new_z = resample_z( ct, cbct) new_cbct_images = cbct.images.copy() if not os.path.exists(path): os.mkdir(path) # CT_len = len( ct.images) #find the start slice in resample CT volume and cut from theree #due to resample new_mid_slice = mid_slice * len(new_volume) // len(ct.images) #number of slices in syth CBCT must be equal to CBCT nSlices = len(cbct.images) offset = new_mid_slice - nSlices // 2 # copy from ct to cbct startUID = random.randint(1, 1000) incUID = random.randint(1, 1000) #get current date today = date.today() dd = today.strftime('%Y%m%d') for i in range(nSlices): new_cbct_image = new_cbct_images[i] # new_cbct_image.pixel_array[:] = ct.images[i + offset].pixel_array[:] new_cbct_image.pixel_array[:] = new_volume[i + offset] new_cbct_image.PixelData = new_cbct_image.pixel_array.tobytes() # change UID # the matter here is the '2.' to make Aria think this is a new study of new patient # Aria still can locate to the exist patient but also have the option of create a new one new_cbct_image.SOPInstanceUID = str( startUID) + new_cbct_image.SOPInstanceUID new_cbct_image.StudyInstanceUID = str( startUID + incUID) + new_cbct_image.StudyInstanceUID new_cbct_image.SeriesInstanceUID = str( startUID) + new_cbct_image.SeriesInstanceUID # new_cbct_image.PatientID = "Pydicom2" #change the Date of creation so that it's display on Eclipse new_cbct_image.SeriesDate = dd new_cbct_image.AcquisitionDate = dd new_cbct_image.ContentDate = dd # change slope and intercept new_cbct_image.RescaleIntercept = ct.images[0].RescaleIntercept new_cbct_image.RescaleSlope = ct.images[0].RescaleSlope new_cbct_image.HighBit = ct.images[0].HighBit # write dicom.dcmwrite(os.path.join(path, output_prefix + str(i) + '.dcm'), new_cbct_image) return new_cbct_images
def datasetToBinary(ds: Dataset): fix_meta_info(ds) with DicomBytesIO() as dcmfile: dcmwrite(dcmfile, ds, write_like_original=False) dcmfile.seek(0) return dcmfile.read()
def test_retrieve_series(client, httpserver, cache_dir): cache_filename = str(cache_dir.joinpath('file.dcm')) with open(cache_filename, 'rb') as f: payload = f.read() content = b'' for i in range(3): content += b'\r\n--boundary\r\n' content += b'Content-Type: application/dicom\r\n\r\n' content += payload content += b'\r\n--boundary--' headers = { 'content-type': ('multipart/related; ' 'type="application/dicom"; ' 'boundary="boundary" '), } httpserver.serve_content(content=content, code=200, headers=headers) study_instance_uid = '1.2.3' series_instance_uid = '1.2.4' sop_instance_uid = '1.2.5' results = client.retrieve_series(study_instance_uid, series_instance_uid) results = list(results) assert len(results) == 3 for result in results: with BytesIO() as fp: pydicom.dcmwrite(fp, result) raw_result = fp.getvalue() assert raw_result == payload request = httpserver.requests[0] expected_path = ( '/studies/{study_instance_uid}/series/{series_instance_uid}'.format( **locals())) assert request.path == expected_path assert request.accept_mimetypes[0][0][:43] == headers['content-type'][:43]
def test_retrieve_instance(httpserver, client, cache_dir): cache_filename = str(cache_dir.joinpath('file.dcm')) with open(cache_filename, 'rb') as f: data = f.read() media_type = 'application/dicom' boundary = 'boundary' headers = { 'content-type': ('multipart/related; ' f'type="{media_type}"; ' f'boundary="{boundary}"'), } message = DICOMwebClient._encode_multipart_message( content=[data], content_type=headers['content-type']) httpserver.serve_content(content=message, code=200, headers=headers) study_instance_uid = '1.2.3' series_instance_uid = '1.2.4' sop_instance_uid = '1.2.5' response = client.retrieve_instance(study_instance_uid, series_instance_uid, sop_instance_uid) with BytesIO() as fp: pydicom.dcmwrite(fp, response) raw_result = fp.getvalue() assert raw_result == data request = httpserver.requests[0] expected_path = (f'/studies/{study_instance_uid}' f'/series/{series_instance_uid}' f'/instances/{sop_instance_uid}') assert request.path == expected_path assert request.accept_mimetypes[0][0][:43] == headers['content-type'][:43]
def test_retrieve_instance(httpserver, client, cache_dir): cache_filename = str(cache_dir.joinpath('file.dcm')) with open(cache_filename, 'rb') as f: content = f.read() headers = { 'content-type': ( 'multipart/related; ' 'type="application/dicom"' ), } httpserver.serve_content(content=content, code=200, headers=headers) study_instance_uid = '1.2.3' series_instance_uid = '1.2.4' sop_instance_uid = '1.2.5' result = client.retrieve_instance( study_instance_uid, series_instance_uid, sop_instance_uid ) with BytesIO() as fp: pydicom.dcmwrite(fp, result) raw_result = fp.getvalue() assert raw_result == content request = httpserver.requests[0] expected_path = ( '/studies/{study_instance_uid}/series/{series_instance_uid}/instances' '/{sop_instance_uid}'.format(**locals()) ) assert request.path == expected_path assert request.accept_mimetypes[0][0][:43] == headers['content-type'][:43]
def add_tag(image, tag): # add tag and save in another folder (target) #print(image, 'from add tag') img = pyd.dcmread(image) img.AccessionNumber = tag img.ImageComments = tag img.StudyID = tag pyd.dcmwrite(image, img)
def bufferize_instance(instance: Dataset, force=True, write_like_original=True): """Makes a copy of the ``instance``. Faster than deepcopy.""" with BytesIO() as buffer: dcmwrite(buffer, instance, write_like_original=write_like_original) buffer.seek(0) return dcmread(buffer, force=force)
def image_downsampling(im, work_dir='C:\\Users\\Haimin\\Dicom\\01'): # os.chdir(work_dir) ds = pyd.dcmread(im) data = ds.pixel_array data_downsampling = data[::8, ::8] ds.PixelData = data_downsampling.tostring() ds.Rows, ds.Columns = data_downsampling.shape pyd.dcmwrite(im, ds) print('convert from {} to {}'.format(data.shape, data_downsampling.shape))
def restruct(src, dest): """ Puts all data directly under dest folder src: source folder. All data will be searched recursively in it dest: destination folder """ for fn in src.glob('**/*dcm'): ds = pydicom.dcmread(str(fn)) pydicom.dcmwrite(str(dest / fn.name), ds)
def write_header_ct(ct, mid_slice, nSlices, path, output_prefix): offset = mid_slice - nSlices // 2 new_cbct_images = [] for i in range(nSlices): new_cbct_image = ct.images[i + offset] new_cbct_images.append(new_cbct_image) dicom.dcmwrite(os.path.join(path, output_prefix + str(i) + '.dcm'), new_cbct_image) return new_cbct_images
def write_dataset_to_bytes(dataset): # 버퍼 생성 with BytesIO() as buffer: # DicomFileLike 오브젝트 생성 memory_dataset = DicomFileLike(buffer) dcmwrite(memory_dataset, dataset) memory_dataset.seek(0) return memory_dataset.read()
def preprocessing(self): os.chdir(self.workdir) for name in os.listdir(self.workdir): ds = pyd.dcmread(name) data = ds.pixel_array data_downsampling = data[::8, ::8] # downsize in 8 times ds.PixelData = data_downsampling.tostring() ds.Rows, ds.Columns = data_downsampling.shape ds.AccessionNumber = '01' pyd.dcmwrite(name, ds) print('tag added and reshaped to', name)
def write_dataset_to_bytes(dataset): # create a buffer with BytesIO() as buffer: # create a DicomFileLike object that has some properties of DataSet memory_dataset = DicomFileLike(buffer) # write the dataset to the DicomFileLike object dcmwrite(memory_dataset, dataset) # to read from the object, you have to rewind it memory_dataset.seek(0) # read the contents as bytes return memory_dataset.read()
def write_dataset_to_bytes(dataset): # 버퍼를 생성한다. with BytesIO() as buffer: # Dataset의 속성들을 담을 DicomFileLike 객체를 만든다. memory_dataset = DicomFileLike(buffer) # Dataset을 DicomFileLike 객체에 write 한다. dcmwrite(memory_dataset, dataset) # 객체에서 읽어오기 위해 rewind 한다. memory_dataset.seek(0) # 바이트로 읽어서 리턴한다. return memory_dataset.read()
def create_rs(self ): ''' contours: structure need to be stored in dicom :param dc: :param generic_rs: :param contours: :return: ''' self.copy_info( ) self.copy_contours( ) # self.copy_from_rs() dicom.dcmwrite( self.rs.rs_file, self.rs.structure)
def to_bytes(dcm: pydicom.dataset.FileDataset): """Converts dicom object to byte sequence, source https://pydicom.github.io/pydicom/dev/auto_examples/memory_dataset.html""" with BytesIO() as buffer: memory_dataset = DicomFileLike( buffer ) # create a DicomFileLike object that has some properties of DataSet dcmwrite(memory_dataset, dcm) # write the dataset to the DicomFileLike object memory_dataset.seek( 0) # to read from the object, you have to rewind it return memory_dataset.read() # read the contents as bytes
def generate_images_for_single_image_masks(dicom_images, inference_results, response_json, output_folder): """ This function will save images to disk to preview how a mask looks on the input images. It saves one image for each input DICOM file with the corresponding `inference_results` mask applied as overlay. - dicom_images: Array of DCM_Image or path to a folder with images - inference_results: Array with mask buffers (one for each image) - response_json: The JSON response from the inference server - output_folder: Where the output images will be saved The difference with `generate_images_with_masks` is that `generate_images_with_masks` applies each mask to the whole volume while this functions applies each mask to one image. """ images, masks = _get_images_and_masks(dicom_images, inference_results) create_folder(output_folder) # Filter out secondary capture outputs all_mask_parts = filter_mask_parts(response_json) binary_masks, secondary_captures = filter_masks_by_binary_type( masks, all_mask_parts, response_json) # Create DICOM files for secondary capture outputs for index, sc in enumerate(secondary_captures): dcm = pydicom.read_file(BytesIO(sc.tobytes())) file_path = os.path.join(output_folder, 'sc_' + str(index) + '.dcm') pydicom.dcmwrite(file_path, dcm) for index, (image, mask, json_part) in enumerate( zip(images, binary_masks, all_mask_parts)): dcm = pydicom.dcmread(image.path) pixels = get_pixels(dcm) # Reshape and add alpha pixels = np.reshape(pixels, (-1, 3)) pixels = np.hstack( (pixels, np.reshape(np.full(pixels.shape[0], 255, dtype=np.uint8), (-1, 1)))) # get mask for this image pixels = _draw_mask_on_image(pixels, mask, json_part, response_json, index, 0) # write image to output folder output_filename = os.path.join( output_folder, str(index) + '_' + os.path.basename(os.path.normpath(image.path))) output_filename += '.png' pixels = np.reshape(pixels, (dcm.Rows, dcm.Columns, 4)) plt.imsave(output_filename, pixels)
def _send_c_move(self, move_dataset, output_dir): if self.process.returncode is not None: msg = 'dcmrecv is not running, rc {self.process.returncode}' logger.error(msg) raise Exception(msg) with tempfile.TemporaryDirectory() as tmpdirname: move_dataset_path = os.path.join(tmpdirname, 'move_dataset.dcm') os.makedirs(output_dir, exist_ok=True) move_dataset.is_little_endian = True move_dataset.is_implicit_VR = True pydicom.dcmwrite(move_dataset_path, move_dataset) # even though storescp has `--fork`, the move lock is needed to tell datasets # apart in the `dicom_tmp_dir` with move_lock: movescu_args = [ 'movescu', '--aetitle', self.client_ae, '--call', self.remote_ae, '--move', self.client_ae, '-S', # study query level *self.timeout_args, *self.logger_args, *self.movescu_extra_args, self.pacs_url, self.pacs_port, move_dataset_path ] result = subprocess.run(movescu_args, stdout=PIPE, stderr=PIPE, universal_newlines=True) logger.debug(result.args) logger.debug(result.stdout) logger.debug(result.stderr) for result_item in os.listdir(self.dicom_tmp_dir): # fully specify move destination to allow overwrites shutil.move(os.path.join(self.dicom_tmp_dir, result_item), os.path.join(output_dir, result_item)) if result.returncode != 0: logger.error( f'C-MOVE failure for query: rc {result.returncode}') return False return True
def create_rs(new_rs_file, structure, contours): #update structure #update structure name distort_contour_names = contours.keys() for i in range(len(structure.ROIContourSequence)): contour_name = structure.StructureSetROISequence[i].ROIName if contour_name in distort_contour_names: S = structure.ROIContourSequence[i].ContourSequence for slice_index in range( len(contours[contour_name]['contour'])): S[slice_index].ContourData = list( contours[contour_name]['contour'][slice_index]) pydicom.dcmwrite( new_rs_file, structure)
def save_segmentation(self): images, filenames, raw_data = self.dicom_reader.get_dataset() path = "segmented_images" if os.path.isdir('./' + path): shutil.rmtree('./' + path) os.mkdir(path) os.chdir('./' + path) for image, filename, raw in zip(images, filenames, raw_data): raw.PixelData = image #self.dicom_processing.segmentation(image) pydicom.dcmwrite(filename, raw) os.chdir('../') return path
def convert2ugly(src_path, ugly_path_fn, src_type_list=False): """ Converts contents of folder (if all dicom) to jpeg or PNG and saves to specified destination. input args: src_path = Specify the .dcm folder path dst_path = Specify the output folder path """ if src_type_list == True: images_path = src_path else: images_path = os.listdir(src_path) bar = ProgBar('Converting', max=len(images_path)) make_ugly = uglifier() for n, image in enumerate(images_path): if src_type_list == True: src_path_img = image src_path = os.path.dirname(image) image = os.path.basename(image) else: src_path_img = os.path.join(src_path, image) try: ds = pydicom.dcmread(str(src_path_img), force=True) data = ds.pixel_array original_type = data.dtype #pixel_array_numpy = rescale_array(data) #ugly_array_numpy = make_ugly.apply_transforms(pixel_array_numpy) ugly_array_numpy = make_ugly.apply_transforms(data) if src_type_list == True: ugly_path = ugly_path_fn(src_path_img) else: ugly_path = os.path.join(ugly_path_fn, image) ugly_img_src = os.path.dirname(ugly_path) if not os.path.exists(ugly_img_src): os.makedirs(ugly_img_src) ds.PixelData = ugly_array_numpy.astype(original_type).tobytes() ds.Rows, ds.Columns = ugly_array_numpy.shape pydicom.dcmwrite(ugly_path, ds, write_like_original=True) except: print(image) bar.next() bar.finish()
def create_train(full_size_path, path, size): """ Create size-specific train folder with resized images full_size_path: path to train folder with full size images path: path to destination folder size: size to which images are to be resize """ for fn in full_size_path.glob('**/*dcm'): ds = pydicom.dcmread(str(fn)) img = ds.pixel_array img = cv2.resize(img, (size, size), interpolation=cv2.INTER_AREA) ds.decompress() ds.PixelData = img.tobytes() ds.Rows, ds.Columns = img.shape pydicom.dcmwrite(str(path / fn.name), ds)
def create_rs_very_limited(new_rs_file, structure, contours): #update structure #update structure name structure.StructureSetLabel = "BladderandRectum" structure.StructureSetName = 'BladderandRectum' structure.SOPInstanceUID = '1.2.826.0.1.3680043.8.498.67063073255766457385690235251075316643' distort_contour_names = distort_params.keys() for i in range(len(structure.ROIContourSequence)): contour_name = structure.StructureSetROISequence[i].ROIName if contour_name in distort_contour_names: S = structure.ROIContourSequence[i].ContourSequence for slice_index in range( len(contours[contour_name]['contour'])): S[slice_index].ContourData = list( contours[contour_name]['contour'][slice_index]) pydicom.dcmwrite( new_rs_file, structure)
def test_retrieve_instance_singlepart(httpserver, client, cache_dir): cache_filename = str(cache_dir.joinpath('file.dcm')) with open(cache_filename, 'rb') as f: data = f.read() headers = {'content-type': 'application/dicom'} httpserver.serve_content(content=data, code=200, headers=headers) study_instance_uid = '1.2.3' series_instance_uid = '1.2.4' sop_instance_uid = '1.2.5' response = client.retrieve_instance(study_instance_uid, series_instance_uid, sop_instance_uid) with BytesIO() as fp: pydicom.dcmwrite(fp, response) raw_result = fp.getvalue() assert raw_result == data request = httpserver.requests[0] assert request.accept_mimetypes[0][0].startswith('multipart/related')
def test_iter_series(client, httpserver, cache_dir): cache_filename = str(cache_dir.joinpath('file.dcm')) with open(cache_filename, 'rb') as f: data = f.read() n_resources = 3 chunk_size = 10**3 media_type = 'application/dicom' boundary = 'boundary' headers = { 'content-type': ( 'multipart/related; ' f'type="{media_type}"; ' f'boundary="{boundary}"' ), 'transfer-encoding': 'chunked' } message = DICOMwebClient._encode_multipart_message( content=[data for _ in range(n_resources)], content_type=headers['content-type'] ) chunked_message = _chunk_message(message, chunk_size) httpserver.serve_content(content=chunked_message, code=200, headers=headers) study_instance_uid = '1.2.3' series_instance_uid = '1.2.4' iterator = client.iter_series( study_instance_uid, series_instance_uid ) assert isinstance(iterator, Generator) response = list(iterator) for instance in response: with BytesIO() as fp: pydicom.dcmwrite(fp, instance) raw_result = fp.getvalue() assert raw_result == data request = httpserver.requests[0] expected_path = ( f'/studies/{study_instance_uid}' f'/series/{series_instance_uid}' ) assert request.path == expected_path assert request.accept_mimetypes[0][0][:43] == headers['content-type'][:43] assert len(response) == n_resources
def write_dicom(): # load results str = '2019-07-22-14h,post' output_image = np.load( os.path.join(os.getcwd(), 'npy', str + ',output.npy')) # convert results into int16 output_image -= np.min(output_image) output_image /= np.max(output_image) output_image *= 255 output_image = output_image.astype('uint16') # write dicoms dicom_dir = '/Volumes/MRIClinical/Ricardo/BRAVO-newcases' exam_dir = '38069839/33224249/D2019_07_22/MR' series_dir = 'S0011_Axial BRAVO x4 acc' utils.makedirs(os.path.join(dicom_dir, exam_dir, series_dir)) for i in range(output_image.shape[2]): file = 'ax-2,sl-{:03d}.dcm'.format(i) write_dicom(output_image[:, :, i], os.path.join(dicom_dir, exam_dir, series_dir, file)) return # load one dicom dicom_dir = '/Volumes/MRIClinical/Ricardo/BRAVO-newcases' exam_dir = '38069839/33224249/D2019_07_22/MR' series_dir = 'S0011_Axial BRAVO' file = 'img_0001_2.789.dcm' ds = pydicom.dcmread(os.path.join(dicom_dir, exam_dir, series_dir, file)) # modify metadata ds.Columns = output_image.shape[0] ds.Rows = output_image.shape[1] ds.SeriesDescription = u'Axial BRAVO x4 acc' # write new dicoms series_dir = 'S0012_Axial BRAVO 4x-acc' utils.makedirs(os.path.join(dicom_dir, exam_dir, series_dir)) for i in range(output_image.shape[2]): ds.PixelData = output_image[:, :, i].tostring() file = 'ax-2,sl-{:03d}.dcm'.format(i) pydicom.dcmwrite(os.path.join(dicom_dir, exam_dir, series_dir, file), ds, write_like_original=False)
async def dcmhandler(channel, ds, uri, routing_key): if not Tag( "ImageType" ) in ds or not "RESAMPLED" in ds.ImageType: #only convert resampled data print( f"dicom2nii: {uri} ({ds.SeriesDescription}) is not a resampled image" ) return print(f"nii2dicom: converting {uri}") ni = nb.load(uri) dicoms = nii2dicom(ni, ds) refds = dicoms[0] outdir = f"{os.environ['HOME']}/.dcmq/derived/{refds.StudyInstanceUID}/{refds.SeriesInstanceUID}" pathlib.Path(outdir).mkdir(parents=True, exist_ok=True) for dcm in dicoms: filepath = outdir + "/" + dcm.SOPInstanceUID dcmwrite(filepath, dcm, write_like_original=False) await publish(channel, "stored.instance", dcm, uri=filepath) await publish(channel, "stored.series", refds, uri=outdir)
def __filter_dcm_anonym(self, ds, old_path): ds.PatientName = "" ds.PatientBirthDate = "" ds.PatientSex = "" ds.PatientAddress = "" ds.ReferringPhysicianName = "" ds.InstitutionName = "" ds.OperatorsName = "" ds.InstitutionalDepartmentName = "" ds.StudyDate = "" ds.SeriesDate = "" ds.ContentDate = "" ds.AcquisitionDate = "" ds.InstanceCreationDate = "" ds.AccessionNumber = "" ds.StudyID = "" ds.ScheduledProcedureStepID = "" ds.RequestedProcedureID = "" ds.PatientID = "" dicom.dcmwrite(old_path, ds)
def FilterDicom(dicomPath, stlfilepath, savepath, orderdir): new_path = savepath # 读取dicom文件 dicomImageData, m_Origin = ReadDicomFile(dicomPath) # 读取stl stlmapImageData = processStlToImageData(dicomImageData, m_Origin, stlfilepath) # 处理文件夹 checkAndMakeDir(new_path) # 获取stl和dicom的array数据 count, dicomArray, stlmapArray = getResharpedAryFromImageData( dicomImageData, stlmapImageData) # count等于0代表读取image文件存在问题 if count == 0: print("folder " + orderdir + " image size error!") return dicomshape = dicomArray.shape dicomfiles = os.listdir(dicomPath) # 操作numpy数据 for i in range(dicomshape[0]): train = stlmapArray[i, :, :] # 上下镜像翻转 train = train[::-1] train = np.where(train > 135, 1, 0) if np.any(train > 0): ori = dicomArray[i, :, :] ori = ori[::-1] dicom_full_path = os.path.join(dicomPath, dicomfiles[i]) ds = pydicom.dcmread(dicom_full_path) # 还原回无符号的正整数 new = (ori - ds.RescaleIntercept) / ds.RescaleSlope # 与label相乘 ori = ori * train.astype(np.uint16) new = new * train.astype(np.uint16) new = new.astype(np.uint16) ds.PixelData = new.tostring() pydicom.dcmwrite(dicom_full_path.replace(dicomPath, savepath), ds) io.imsave(new_path + orderdir + '-' + addPadding(str(i)) + '.png', winchange(ori, 0, 1000)) print("folder " + orderdir + " done!")
async def get(channel, ds): with tempfile.TemporaryDirectory() as tmpdirname: dcmpath = str(join(tmpdirname, "tmp.dcm")) pydicom.dcmwrite(dcmpath, ds) print(ds) if dimse_mode == "MOVE": cmd = f"movescu -v -aet {calling_ae} -aec {server_ae} -S -od {tmpdirname} --port {move_dest_port} {server_ip} {server_port} {dcmpath}" else: cmd = f"getscu -v -aet {calling_ae} -aec {server_ae} -S -od {tmpdirname} {server_ip} {server_port} {dcmpath}" print(cmd) os.system(cmd) onlyfiles = [ f for f in listdir(tmpdirname) if isfile(join(tmpdirname, f)) ] for f in onlyfiles: if f == "tmp.dcm": continue tmpfilepath = str(join(tmpdirname, f)) newds = pydicom.dcmread(tmpfilepath, stop_before_pixels=True) filepath = getFilename(newds) movefile(tmpfilepath, filepath) await publish(channel, "stored.instance", newds, uri=filepath)
def save_as(self, filename, write_like_original=True): """Write the Dataset to `filename`. Saving a Dataset requires that the Dataset.is_implicit_VR and Dataset.is_little_endian attributes exist and are set appropriately. If Dataset.file_meta.TransferSyntaxUID is present then it should be set to a consistent value to ensure conformance. Conformance with DICOM File Format ---------------------------------- If `write_like_original` is False, the Dataset will be stored in the DICOM File Format in accordance with DICOM Standard Part 10 Section 7. To do so requires that the `Dataset.file_meta` attribute exists and contains a Dataset with the required (Type 1) File Meta Information Group elements (see pydicom.filewriter.dcmwrite and pydicom.filewriter.write_file_meta_info for more information). If `write_like_original` is True then the Dataset will be written as is (after minimal validation checking) and may or may not contain all or parts of the File Meta Information (and hence may or may not be conformant with the DICOM File Format). Parameters ---------- filename : str or file-like Name of file or the file-like to write the new DICOM file to. write_like_original : bool If True (default), preserves the following information from the Dataset (and may result in a non-conformant file): - preamble -- if the original file has no preamble then none will be written. - file_meta -- if the original file was missing any required File Meta Information Group elements then they will not be added or written. If (0002,0000) 'File Meta Information Group Length' is present then it may have its value updated. - seq.is_undefined_length -- if original had delimiters, write them now too, instead of the more sensible length characters - is_undefined_length_sequence_item -- for datasets that belong to a sequence, write the undefined length delimiters if that is what the original had. If False, produces a file conformant with the DICOM File Format, with explicit lengths for all elements. See Also -------- pydicom.filewriter.write_dataset Write a DICOM Dataset to a file. pydicom.filewriter.write_file_meta_info Write the DICOM File Meta Information Group elements to a file. pydicom.filewriter.dcmwrite Write a DICOM file from a FileDataset instance. """ # Ensure is_little_endian and is_implicit_VR exist if not (hasattr(self, 'is_little_endian') and hasattr(self, 'is_implicit_VR')): raise AttributeError("'{0}.is_little_endian' and " "'{0}.is_implicit_VR' must exist and be " "set appropriately before " "saving.".format(self.__class__.__name__)) pydicom.dcmwrite(filename, self, write_like_original)