Convert ``filename`` to a NIFTI file using ``mri_convert``
185545
def mgz_to_nifti(filename,prefix=None,gzip=True):
    ''''''
    setup_freesurfer()
    if prefix==None:
        prefix = nl.prefix(filename) + '.nii'
    if gzip and not prefix.endswith('.gz'):
        prefix += '.gz'
    nl.run([os.path.join(freesurfer_home,'bin','mri_convert'),filename,prefix],products=prefix)
1147290
def file_to_str(fname):
    
    data = None
    # rU = read with Universal line terminator
    with open(fname, 'rU') as fd:
        data = fd.read()
    return data
1028959
def from_nibabel(nib_image):
    
    tmpfile = mktemp(suffix='.nii.gz')
    nib_image.to_filename(tmpfile)
    new_img = iio2.image_read(tmpfile)
    os.remove(tmpfile)
    return new_img
869990
def to_iris_syscal(self, filename):
        
        with open(filename, 'w') as fid:
            # fprintf(fod, '#\t X\t Y\t Z\n');
            fid.write('#\t X\t Y\t Z\n')
            # fprintf(fod, '%d\t %.1f\t %d\t %d\n', D');
            # loop over electrodes and assign increasing x-positions
            # TODO: use proper electrode positions, if available
            for nr in range(0, self.configs.max()):
                fid.write('{}   {}  0   0\n'.format(nr + 1, nr))

            # fprintf(fod, '#\t A\t B\t M\t N\n');
            fid.write('#\t A\t B\t M\t N\n')

            # fprintf(fod, '%d\t %d\t %d\t %d\t %d\n', C');
            for nr, config in enumerate(self.configs):
                fid.write('{}  {}  {}  {}  {}\n'.format(nr + 1, *config))
1339983
def rec2csv(r, filename):
    """"""
    names = r.dtype.names
    def translate(x):
        if x is None or str(x).lower == "none":
            x = ""
        return str(x)
    with open(filename, "w") as csv:
        csv.write(",".join([str(x) for x in names])+"\n")
        for data in r:
            csv.write(",".join([translate(x) for x in data])+"\n")
    #print "Wrote CSV table %r" % filename
    return filename
599131
def generate_tensor_filename(self, field_name, file_num, compressed=True):
        
        file_ext = TENSOR_EXT
        if compressed:
            file_ext = COMPRESSED_TENSOR_EXT
        filename = os.path.join(self.filename, 'tensors', '%s_%05d%s' %(field_name, file_num, file_ext))
        return filename
849285
def tohdf5(input_files, output_file, n_events, conv_times_to_jte, **kwargs):
    """"""
    if len(input_files) > 1:
        cprint(
            "Preparing to convert {} files to HDF5.".format(len(input_files))
        )

    from km3pipe import Pipeline    # noqa
    from km3pipe.io import GenericPump, HDF5Sink, HDF5MetaData    # noqa

    for input_file in input_files:
        cprint("Converting '{}'...".format(input_file))
        if len(input_files) > 1:
            output_file = input_file + '.h5'

        meta_data = kwargs.copy()
        meta_data['origin'] = input_file

        pipe = Pipeline()
        pipe.attach(HDF5MetaData, data=meta_data)
        pipe.attach(GenericPump, filenames=input_file, **kwargs)
        pipe.attach(StatusBar, every=250)
        if conv_times_to_jte:
            from km3modules.mc import MCTimeCorrector
            pipe.attach(MCTimeCorrector)
        pipe.attach(HDF5Sink, filename=output_file, **kwargs)
        pipe.drain(n_events)
        cprint("File '{}' was converted.".format(input_file))
469813
def load(input_filename):

    ''''''

    try:
        pil_img = Image.open(input_filename)
    except IOError:
        sys.stderr.write('warning: error opening {}\n'.format(
            input_filename))
        return None, None

    if pil_img.mode != 'RGB':
        pil_img = pil_img.convert('RGB')

    if 'dpi' in pil_img.info:
        dpi = pil_img.info['dpi']
    else:
        dpi = (300, 300)

    img = np.array(pil_img)

    return img, dpi
513385
function(filename, template, outputInInput) {
    var basename;
    var glob;

    template = Array.isArray(template) ? filename : template;
    glob = isGlob(template);
    if (outputInInput) {
      basename = _toArray(filename.split('.').pop()) ;
    } else if (glob) {
      basename = filename.slice(glob.length, filename.length).split('.');
      basename.pop();
    } else {
      basename = filename.split('/').pop().split('.');
      basename.pop();
    }
    return basename.join('.');
  }
1330947
function (mu, uriString, filename) {
        console.info('#green{[convert file]} ' + filename + ' #green{to data uri]}\n');
        return mu.replace(uriString, [
            'data:',
            mime.getType(filename),
            ';base64,',
            fs.readFileSync(filename).toString('base64')
        ].join(''));
    }
184098
def convert_pnm(self, infile, outfile):
        

        if self.interlace:
            pixels = array('B')
            pixels.fromfile(infile,
                            (self.bitdepth/8) * self.color_planes *
                            self.width * self.height)
            self.write_passes(outfile, self.array_scanlines_interlace(pixels))
        else:
            self.write_passes(outfile, self.file_scanlines(infile))
1266230
def to_file(self, filename):
		
		with open(filename, 'wb') as f:
			f.write(self.to_bytes())
1242714
def convert_all(folder, dest_path='.', force_all=False):
    ""
    path = Path(folder)

    changed_cnt = 0
    for fname in path.glob("*.ipynb"):
        # only rebuild modified files
        fname_out = Path(dest_path)/fname.with_suffix('.html').name
        if not force_all and fname_out.exists():
            in_mod  = os.path.getmtime(fname)
            out_mod = os.path.getmtime(fname_out)
            if in_mod < out_mod: continue

        print(f"converting: {fname} => {fname_out}")
        changed_cnt += 1
        convert_nb(fname, dest_path=dest_path)
    if not changed_cnt: print("No notebooks were modified")
1134200
def conv(arg, source, target, filename, section):
    
    logging.info(_('This is Binary Conversion mode.'))
    section = section.encode('utf-8')
    if source == 'sec':
        arg = open(arg, 'rb')
    if source == 'sec':
        kwargs = dict(section_name=section)
    else:
        kwargs = dict()
    result = Converter.uni_from(source, arg, **kwargs).uni_to(target)
    if result:
        if filename:
            logging.info(
                _('Writing shellcode to the file: %s'), filename)
            mode = 'wb' if target == 'bin' else 'w'
            with open(filename, mode) as output:
                output.write(result)
        else:
            print(result)
    else:
        logging.error(_('Failed.'))
    if source == 'sec':
        arg.close()
    return 0
965700
def _classic_4d_to_nifti(grouped_dicoms, output_file):
    
    # Get the sorted mosaics
    all_dicoms = [i for sl in grouped_dicoms for i in sl]  # combine into 1 list for validating
    common.validate_orientation(all_dicoms)

    # Create mosaic block
    logger.info('Creating data block')
    full_block = _classic_get_full_block(grouped_dicoms)

    logger.info('Creating affine')
    # Create the nifti header info
    affine, slice_increment = common.create_affine(grouped_dicoms[0])

    logger.info('Creating nifti')
    # Convert to nifti
    nii_image = nibabel.Nifti1Image(full_block, affine)
    common.set_tr_te(nii_image, float(grouped_dicoms[0][0].RepetitionTime), float(grouped_dicoms[0][0].EchoTime))
    logger.info('Saving nifti to disk')
    # Save to disk
    if output_file is not None:
        nii_image.to_filename(output_file)

    if _is_diffusion_imaging(grouped_dicoms[0][0]):
        logger.info('Creating bval en bvec')
        bval_file = None
        bvec_file = None
        if output_file is not None:
            base_path = os.path.dirname(output_file)
            base_name = os.path.splitext(os.path.splitext(os.path.basename(output_file))[0])[0]
            logger.info('Creating bval en bvec files')
            bval_file = '%s/%s.bval' % (base_path, base_name)
            bvec_file = '%s/%s.bvec' % (base_path, base_name)

        bval = _create_bvals(grouped_dicoms, bval_file)
        bvec = _create_bvecs(grouped_dicoms, bvec_file)

        return {'NII_FILE': output_file,
                'BVAL_FILE': bval_file,
                'BVEC_FILE': bvec_file,
                'NII': nii_image,
                'BVAL': bval,
                'BVEC': bvec,
                'MAX_SLICE_INCREMENT': slice_increment}

    return {'NII_FILE': output_file,
            'NII': nii_image,
            'MAX_SLICE_INCREMENT': slice_increment}
819159
def nii_modify(
        nii,
        fimout = '',
        outpath = '',
        fcomment = '',
        voxel_range=[]):

    ''' 
    '''

    if isinstance(nii, basestring) and os.path.isfile(nii):
        dctnii = imio.getnii(nii, output='all')
        fnii = nii
    if isinstance(nii, dict) and 'im' in nii:
        dctnii = nii
        if 'fim' in dctnii:
            fnii = dctnii['fim']

    #---------------------------------------------------------------------------
    #> output path
    if outpath=='' and fimout!='' and '/' in fimout:
        opth = os.path.dirname(fimout)
        if opth=='' and isinstance(fnii, basestring) and os.path.isfile(fnii):
            opth = os.path.dirname(nii)
        fimout = os.path.basename(fimout)

    elif outpath=='' and isinstance(fnii, basestring) and os.path.isfile(fnii):
        opth = os.path.dirname(fnii)
    else:
        opth = outpath
    imio.create_dir(opth)

    #> output floating and affine file names
    if fimout=='':

        if fcomment=='':
            fcomment += '_nimpa-modified'

        fout = os.path.join(
                opth,
                os.path.basename(fnii).split('.nii')[0]+fcomment+'.nii.gz')
    else:
        fout = os.path.join(
                opth,
                fimout.split('.')[0]+'.nii.gz')
    #---------------------------------------------------------------------------


    #> reduce the max value to 255
    if voxel_range and len(voxel_range)==1:
        im = voxel_range[0] * dctnii['im']/np.max(dctnii['im'])
    elif voxel_range and len(voxel_range)==2:
        #> normalise into range 0-1
        im = (dctnii['im'] - np.min(dctnii['im'])) / np.ptp(dctnii['im'])
        #> convert to voxel_range 
        im = voxel_range[0] + im*(voxel_range[1] - voxel_range[0])
    else:
        return None

    #> output file name for the extra reference image
    imio.array2nii(
        im,
        dctnii['affine'],
        fout,
        trnsp = (dctnii['transpose'].index(0),
                 dctnii['transpose'].index(1),
                 dctnii['transpose'].index(2)),
        flip = dctnii['flip'])

    return {'fim':fout, 'im':im, 'affine':dctnii['affine']}
700825
def convert_to_file(cgi_input, output_file, twobit_ref, twobit_name, var_only=False):
    """"""

    if isinstance(output_file, str):
        output_file = auto_zip_open(output_file, 'w')

    conversion = convert(cgi_input=cgi_input, twobit_ref=twobit_ref, twobit_name=twobit_name, var_only=var_only)
    for line in conversion:
        output_file.write(line + "\n")
    output_file.close()