This function can be used to convert a folder of jpeg compressed images to an uncompressed ones

    :param dicom_directory: directory of dicom files to compress
437541
def compress_directory(dicom_directory):
    
    if _is_compressed(dicom_directory):
        return

    logger.info('Compressing dicom files in %s' % dicom_directory)
    for root, _, files in os.walk(dicom_directory):
        for dicom_file in files:
            if is_dicom_file(os.path.join(root, dicom_file)):
                _compress_dicom(os.path.join(root, dicom_file))
688441
def compress_to(self, archive_path=None):
        
        if archive_path is None:
            archive = tempfile.NamedTemporaryFile(delete=False)
            tar_args = ()
            tar_kwargs = {'fileobj': archive}
            _return = archive.name
        else:
            tar_args = (archive_path)
            tar_kwargs = {}
            _return = archive_path
        tar_kwargs.update({'mode': 'w:gz'})
        with closing(tarfile.open(*tar_args, **tar_kwargs)) as tar:
            tar.add(self.path, arcname=self.file)

        return _return
359504
def from_kirbidir(directory_path):
		
		cc = CCACHE()
		dir_path = os.path.join(os.path.abspath(directory_path), '*.kirbi')
		for filename in glob.glob(dir_path):
			with open(filename, 'rb') as f:
				kirbidata = f.read()
				kirbi = KRBCRED.load(kirbidata).native
				cc.add_kirbi(kirbi)
		
		return cc
1117237
def _remove_duplicate_slices(dicoms):
    
    # Loop overall files and build dict

    dicoms_dict = {}
    filtered_dicoms = []
    for dicom_ in dicoms:
        if tuple(dicom_.ImagePositionPatient) not in dicoms_dict:
            dicoms_dict[tuple(dicom_.ImagePositionPatient)] = dicom_
            filtered_dicoms.append(dicom_)
        else:
            if numpy.array_equal(dicom_.pixel_array,
                                 dicoms_dict[tuple(dicom_.ImagePositionPatient)].pixel_array):
                logger.warning('Removing duplicate slice from series')
            else:
                filtered_dicoms.append(dicom_)
    return filtered_dicoms
764061
def save_to_files(self, directory: str) -> None:
        
        os.makedirs(directory, exist_ok=True)
        if os.listdir(directory):
            logging.warning("vocabulary serialization directory %s is not empty", directory)

        with codecs.open(os.path.join(directory, NAMESPACE_PADDING_FILE), 'w', 'utf-8') as namespace_file:
            for namespace_str in self._non_padded_namespaces:
                print(namespace_str, file=namespace_file)

        for namespace, mapping in self._index_to_token.items():
            # Each namespace gets written to its own file, in index order.
            with codecs.open(os.path.join(directory, namespace + '.txt'), 'w', 'utf-8') as token_file:
                num_tokens = len(mapping)
                start_index = 1 if mapping[0] == self._padding_token else 0
                for i in range(start_index, num_tokens):
                    print(mapping[i].replace('\n', '@@NEWLINE@@'), file=token_file)
17130
def set_cache_dir(directory):
    
    global cache_dir

    if directory is None:
        cache_dir = None
        return

    if not os.path.exists(directory):
        os.makedirs(directory)
    if not os.path.isdir(directory):
        raise ValueError("not a directory")
    cache_dir = directory
1312137
def compress(samples, run_parallel):
    
    to_cram = []
    finished = []
    for data in [x[0] for x in samples]:
        if "cram" in dd.get_archive(data) or "cram-lossless" in dd.get_archive(data):
            to_cram.append([data])
        else:
            finished.append([data])
    crammed = run_parallel("archive_to_cram", to_cram)
    return finished + crammed
695111
def put_directory(self, mdir):
        
        log.debug('PutDirectory %r', mdir)
        headers = {"Content-Type": "application/json; type=directory"}
        res, content = self._request(mdir, "PUT", headers=headers)
        if res["status"] != "204":
            raise errors.MantaAPIError(res, content)
715756
def get_compression_type(self, file_name):
        

        ext = os.path.splitext(file_name)[1]

        if ext == '.gz':
            self.ctype = 'gzip'
        elif ext == '.bz2':
            self.ctype = 'bzip2'
        elif ext in ('.xz', '.lzma'):
            self.ctype = 'lzma'
        else:
            self.ctype = None
293149
def export(self, nidm_version, export_dir):
        
        if self.file is not None:
            self.add_attributes([
                (PROV['type'], self.type),
                (DCT['format'], "image/png"),
            ])
448691
def invert_images(self, image_directory: str, image_file_ending: str = "*.bmp"):
        
        image_paths = [y for x in os.walk(image_directory) for y in glob(os.path.join(x[0], image_file_ending))]
        for image_path in tqdm(image_paths, desc="Inverting all images in directory {0}".format(image_directory)):
            white_on_black_image = Image.open(image_path).convert("L")
            black_on_white_image = ImageOps.invert(white_on_black_image)
            black_on_white_image.save(os.path.splitext(image_path)[0] + ".png")
790628
def epub_zip(outdirect):
    

    def recursive_zip(zipf, directory, folder=None):
        if folder is None:
            folder = ''
        for item in os.listdir(directory):
            if os.path.isfile(os.path.join(directory, item)):
                zipf.write(os.path.join(directory, item),
                           os.path.join(directory, item))
            elif os.path.isdir(os.path.join(directory, item)):
                recursive_zip(zipf, os.path.join(directory, item),
                              os.path.join(folder, item))

    log.info('Zipping up the directory {0}'.format(outdirect))
    epub_filename = outdirect + '.epub'
    epub = zipfile.ZipFile(epub_filename, 'w')
    current_dir = os.getcwd()
    os.chdir(outdirect)
    epub.write('mimetype')
    log.info('Recursively zipping META-INF and EPUB')
    for item in os.listdir('.'):
        if item == 'mimetype':
            continue
        recursive_zip(epub, item)
    os.chdir(current_dir)
    epub.close()
67424
def convert(files, **kwargs):
    

    if len(files) < 1:
        raise ValueError("Files needs to be a non-empty list")

    if len(files) == 1:
        if os.path.isfile(files[0]):
            return files_to_pif(files, **kwargs)
        else:
            return directory_to_pif(files[0], **kwargs)
    else:
        return files_to_pif([x for x in files if os.path.isfile(x)], **kwargs)
1355980
def dcmsort(folder, copy_series=False, verbose=False):
    ''' 
    '''

    # list files in the input folder
    files = os.listdir(folder)

    srs = {}
    for f in files:
        if os.path.isfile(os.path.join(folder, f)) and f.endswith(dcmext):
            dhdr = dcm.read_file(os.path.join(folder, f))
            #---------------------------------
            # image size
            imsz = np.zeros(2, dtype=np.int64)
            if [0x028,0x010] in dhdr:
                imsz[0] = dhdr[0x028,0x010].value
            if [0x028,0x011] in dhdr:
                imsz[1] = dhdr[0x028,0x011].value
            # voxel size
            vxsz = np.zeros(3, dtype=np.float64)
            if [0x028,0x030] in dhdr and [0x018,0x050] in dhdr:
                pxsz =  np.array([float(e) for e in dhdr[0x028,0x030].value])
                vxsz[:2] = pxsz
                vxsz[2] = float(dhdr[0x018,0x050].value)
            # orientation
            ornt = np.zeros(6, dtype=np.float64)
            if [0x020,0x037] in dhdr:
                ornt = np.array([float(e) for e in dhdr[0x20,0x37].value])
            # seires description, time and study time
            srs_dcrp = dhdr[0x0008, 0x103e].value
            srs_time = dhdr[0x0008, 0x0031].value[:6]
            std_time = dhdr[0x0008, 0x0030].value[:6]

            if verbose:
                print 'series desciption:', srs_dcrp
                print 'series time:', srs_time
                print 'study  time:', std_time
                print '---------------------------------------------------'

            #----------
            # series for any category (can be multiple scans within the same category)
            recognised_series = False
            srs_k = srs.keys()
            for s in srs_k:
                if  np.array_equal(srs[s]['imorient'],  ornt) and \
                    np.array_equal(srs[s]['imsize'],    imsz) and \
                    np.array_equal(srs[s]['voxsize'],   vxsz) and \
                    srs[s]['tseries'] == srs_time:
                    recognised_series = True
                    break
            # if series was not found, create one
            if not recognised_series:
                s = srs_dcrp + '_' + srs_time
                srs[s] = {}
                srs[s]['imorient']  = ornt
                srs[s]['imsize']    = imsz
                srs[s]['voxsize']   = vxsz
                srs[s]['tseries']   = srs_time
            # append the file name
            if 'files' not in srs[s]: srs[s]['files'] = []
            if copy_series:
                srsdir = os.path.join(folder, s)
                create_dir( srsdir )
                shutil.copy(os.path.join(folder, f), srsdir)
                srs[s]['files'].append( os.path.join(srsdir, f) )
            else:
                srs[s]['files'].append( os.path.join(folder, f) )

    return srs
652266
def make_directory(self, directory_name, *args, **kwargs):
		
		self.dav_client().mkdir(self.join_path(self.session_path(), directory_name))
150885
def image_directory
      @image_directory ||= begin
        date_dir = Time.zone.now.strftime('%Y/%m')
        File.join(IMAGE_DIRECTORY, date_dir)
      end
    end
659445
def unpack(src_dir, dst_dir):
    ''''''
    for dirpath, dirnames, filenames in os.walk(src_dir):
        subdir = os.path.relpath(dirpath, src_dir)
        for f in filenames:
            src = os.path.join(dirpath, f)
            dst = os.path.join(dst_dir, subdir, f)
            os.renames(src, dst)
        for n, d in reversed(list(enumerate(dirnames))):
            src = os.path.join(dirpath, d)
            dst = os.path.join(dst_dir, subdir, d)
            if not os.path.exists(dst):
                # Directory does not exist in destination,
                # rename it and prune it from os.walk list.
                os.renames(src, dst)
                del dirnames[n]
    # Cleanup.
    for dirpath, dirnames, filenames in os.walk(src_dir, topdown=True):
        assert not filenames
        os.rmdir(dirpath)