Resample the floating image <fflo> into the geometry of <fref>,
        using the Vinci transformation output <faff> (an *.xml file).
        Output the NIfTI file path of the resampled/resliced image.
325691
def resample_vinci(
        fref,
        fflo,
        faff,
        intrp = 0,
        fimout = '',
        fcomment = '',
        outpath = '',
        pickname = 'ref',
        vc = '',
        con = '',
        vincipy_path = '',
        atlas_resample = False,
        atlas_ref_make = False,
        atlas_ref_del = False,
        close_vinci = False,
        close_buff = True,
        ):
    ''' 
    '''

    #---------------------------------------------------------------------------
    #> output path
    if outpath=='' and fimout!='' and '/' in fimout:
        opth = os.path.dirname(fimout)
        if opth=='':
            opth = os.path.dirname(fflo)
        fimout = os.path.basename(fimout)

    elif outpath=='':
        opth = os.path.dirname(fflo)
    else:
        opth = outpath
    imio.create_dir(opth)

    #> output floating and affine file names
    if fimout=='':
        if pickname=='ref':
            fout = os.path.join(
                    opth,
                    'affine-ref-' \
                    +os.path.basename(fref).split('.nii')[0]+fcomment+'.nii.gz')
        else:
            fout = os.path.join(
                    opth,
                    'affine-flo-' \
                    +os.path.basename(fflo).split('.nii')[0]+fcomment+'.nii.gz')
    else:
        fout = os.path.join(
                opth,
                fimout.split('.')[0]+'.nii.gz')
    #---------------------------------------------------------------------------


    if vincipy_path=='':
        try:
            import resources
            vincipy_path = resources.VINCIPATH
        except:
            raise NameError('e> could not import resources \
                    or find variable VINCIPATH in resources.py')

    sys.path.append(vincipy_path)

    try:
        from VinciPy import Vinci_Bin, Vinci_Connect, Vinci_Core, Vinci_XML, Vinci_ImageT
    except ImportError:
        raise ImportError('e> could not import Vinci:\n \
                check the variable VINCIPATH (path to Vinci) in resources.py')


    #---------------------------------------------------------------------------
    #> start Vinci core engine if it is not running/given
    if vc=='' or con=='':
        #> adopted from the Vinci's example RunMMMJob.py
        bin = Vinci_Bin.Vinci_Bin()
        con = Vinci_Connect.Vinci_Connect(bin)
        vinci_binpath = con.StartMyVinci()

        vc = Vinci_Core.Vinci_CoreCalc(con)
        vc.StdProject()
    #---------------------------------------------------------------------------

    if int(intrp)==0:
        interp_nn = True
    else:
        interp_nn = False

    #---------------------------------------------------------------------------
    #> change the reference image to be loaded as atlas
    if atlas_resample and atlas_ref_make:

        #> output file name for the extra reference image
        fextref = os.path.join(opth, 'reference-as-atlas.nii.gz')

        prc.nii_modify(fref, fimout=fextref, voxel_range=[0., 255.])
        
        ref = Vinci_ImageT.newTemporary(
                vc,
                szFileName = fextref,
                bLoadAsAtlas = atlas_resample)

        if atlas_ref_del:
            os.remove(fextref)

    else:
        ref = Vinci_ImageT.newTemporary(
                vc,
                szFileName = fref,
                bLoadAsAtlas = atlas_resample)
    #---------------------------------------------------------------------------

    #---------------------------------------------------------------------------
    #> reapply rigid transformation to new image


    flo = Vinci_ImageT.newTemporary(
            vc,
            szFileName = fflo,
            bLoadAsAtlas = atlas_resample)

    rsl = flo.reapplyMMMTransform(
            faff,
            refImage = ref,
            IsComputed=True)

    rsl.saveYourselfAs(
            bUseOffsetRotation = True,
            bUseNextNeighbourInterp = interp_nn,
            szFullFileName = fout)
    #---------------------------------------------------------------------------    


    #> close image buffers for reference and floating
    if close_buff:
        ref.killYourself()
        flo.killYourself()
        rsl.killYourself()
        


    if close_vinci: con.CloseVinci(True)

    return fout
410160
def svg_to_path(file_obj, file_type=None):
    

    def element_transform(e, max_depth=100):
        """
        Find a transformation matrix for an XML element.
        """
        matrices = []
        current = e
        for i in range(max_depth):
            if 'transform' in current.attrib:
                mat = transform_to_matrices(current.attrib['transform'])
                matrices.extend(mat)
                # cached[current] = mat
            current = current.getparent()
            if current is None:
                break

        if len(matrices) == 0:
            return np.eye(3)
        elif len(matrices) == 1:
            return matrices[0]
        else:
            return util.multi_dot(matrices[::-1])

    # first parse the XML
    xml = etree.fromstring(file_obj.read())

    # store paths and transforms as
    # (path string, 3x3 matrix)
    paths = []

    # store every path element
    for element in xml.iter('{*}path'):
        paths.append((element.attrib['d'],
                      element_transform(element)))

    return _svg_path_convert(paths)
1144545
def convert(filepath, outfilepath):
    """"""

    logger = logging.getLogger("example1")
    logger.setLevel(logging.INFO)
    fmt = logging.Formatter(STD_FORMAT)
    stderrHdlr = logging.StreamHandler()
    stderrHdlr.setFormatter(fmt)
    logger.addHandler(stderrHdlr)

    fi = ImageViewCairo(logger)
    fi.configure(500, 1000)

    # Load fits file
    image = load_data(filepath, logger=logger)

    # Make any adjustments to the image that we want
    fi.set_bg(1.0, 1.0, 1.0)
    fi.set_image(image)
    fi.auto_levels()
    fi.zoom_fit()
    fi.center_image()

    ht_pts = 11.0 / point_in
    wd_pts = 8.5 / point_in
    off_x, off_y = 0, 0

    out_f = open(outfilepath, 'w')
    surface = cairo.PDFSurface(out_f, wd_pts, ht_pts)
    # set pixels per inch
    surface.set_fallback_resolution(300, 300)
    surface.set_device_offset(off_x, off_y)
    try:
        fi.save_image_as_surface(surface)
        surface.show_page()
        surface.flush()
        surface.finish()
    finally:
        out_f.close()
500793
function resample(image, width, height) {
    let factor

    if (!width && !height) {
        width = image.width
        height = image.height
    }

    if (!width) {
        factor = height / image.height
        width = Math.round(image.width * factor)
    }

    if(!height) {
        factor = width / image.width
        height = Math.round(image.height * factor)
    }

    let canvas = image
    while(canvas.width > width && canvas.width * 0.5 > width) {
        canvas = scalingHelper(canvas, 0.5)
    }

    let finalCanvas = document.createElement('canvas')
    finalCanvas.width = width // 原始宽
    finalCanvas.height = height
    let ctx = finalCanvas.getContext('2d')
    ctx.drawImage(canvas, 0, 0, width, height)

    return finalCanvas
}
1273891
function _imageCopyResampledWorkaround2(&$dst_img, &$src_img, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h)
    {
        ImagePaletteCopy($dst_img, $src_img);
        $rX = $src_w / $dst_w;
        $rY = $src_h / $dst_h;
        $w = 0;
        for ($y = $dst_y; $y < $dst_h; $y++)
        {
            $ow = $w;
            $w = round(($y + 1) * $rY);
            $t = 0;
            for ($x = $dst_x; $x < $dst_w; $x++)
            {
                $r = $g = $b = 0;
                $a = 0;
                $ot = $t;
                $t = round(($x + 1) * $rX);
                for ($u = 0; $u < ($w - $ow); $u++)
                {
                    for ($p = 0; $p < ($t - $ot); $p++)
                    {
                        $c = ImageColorsForIndex($src_img, ImageColorAt($src_img, $ot + $p, $ow + $u));
                        $r += $c['red'];
                        $g += $c['green'];
                        $b += $c['blue'];
                        $a++;
                    }
                }
                ImageSetPixel($dst_img, $x, $y, ImageColorClosest($dst_img, $r / $a, $g / $a, $b / $a));
            }
        }
    }
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']}
269526
def image_shift(xshift=0, yshift=0, axes="gca"):
    

    if axes=="gca": axes = _pylab.gca()

    e = axes.images[0].get_extent()

    e[0] = e[0] + xshift
    e[1] = e[1] + xshift
    e[2] = e[2] + yshift
    e[3] = e[3] + yshift

    axes.images[0].set_extent(e)

    _pylab.draw()
588520
function resample(coordinates) {
    var i = 0,
        n = coordinates.length,
        j,
        m,
        resampled = n ? [coordinates[0]] : coordinates,
        resamples,
        origin = arc.source();

    while (++i < n) {
      resamples = arc.source(coordinates[i - 1])(coordinates[i]).coordinates;
      for (j = 0, m = resamples.length; ++j < m;) resampled.push(resamples[j]);
    }

    arc.source(origin);
    return resampled;
  }
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}
1373321
def post_process(intermediate_file, reduction_factor)
      # Calculate a new set of transforms with respect to reduction_factor
      transformation = if reduction_factor
                         reduce(without_crop, reduction_factor)
                       else
                         without_crop
                       end
      Riiif::File.new(intermediate_file).extract(transformation, image_info)
    end
90735
def new_for_fk10_fig9(cls, shlib_path):
        
        inst = (cls(shlib_path)
            .set_thermal_background(2.1e7, 3e9)
            .set_bfield(48)
            .set_edist_powerlaw(0.016, 4.0, 3.7, 5e9/3)
            .set_freqs(100, 0.5, 50)
            .set_hybrid_parameters(12, 12)
            .set_ignore_q_terms(False)
            .set_obs_angle(50 * np.pi / 180)
            .set_padist_gaussian_loss_cone(0.5 * np.pi, 0.4)
            .set_trapezoidal_integration(15))

        # haven't yet figure out how to deal with this part:
        inst.in_vals[0] = 1.33e18
        inst.in_vals[1] = 6e8
        return inst
858158
def to_sdf(self):
        
        # compute medial axis transform
        skel, sdf_in = morph.medial_axis(self.data, return_distance=True)
        useless_skel, sdf_out = morph.medial_axis(
            np.iinfo(np.uint8).max - self.data, return_distance=True)

        # convert to true sdf
        sdf = sdf_out - sdf_in
        return sdf
339846
def fromfile(fname):
    
    fig = SVGFigure()
    with open(fname) as fid:
        svg_file = etree.parse(fid)

    fig.root = svg_file.getroot()
    return fig
787292
protected void squareToImageSample(float x, float y, RectangleRotate_F32 region) {
		// -1 because it starts counting at 0.  otherwise width+1 samples are made
		x *= region.width-1;
		y *= region.height-1;

		imageX = x*c - y*s + region.cx;
		imageY = x*s + y*c + region.cy;
	}
1041419
def save_figure_tofile(fig, fmt, fname):
    """"""
    root, ext = osp.splitext(fname)
    if ext == '.png' and fmt == 'image/svg+xml':
        qimg = svg_to_image(fig)
        qimg.save(fname)
    else:
        if fmt == 'image/svg+xml' and is_unicode(fig):
            fig = fig.encode('utf-8')

        with open(fname, 'wb') as f:
            f.write(fig)
916564
def reconstructImage(self):
        '''
        
        '''
        f_ishift = np.fft.ifftshift(self.fshift)
        return np.real(np.fft.ifft2(f_ishift))
394057
def _multiframe_to_nifti(dicom_input, output_file):
    

    # Read the multiframe dicom file
    logger.info('Read dicom file')
    multiframe_dicom = dicom_input[0]

    # Create mosaic block
    logger.info('Creating data block')
    full_block = _multiframe_to_block(multiframe_dicom)

    logger.info('Creating affine')

    # Create the nifti header info
    affine = _create_affine_multiframe(multiframe_dicom)
    logger.info('Creating nifti')

    # Convert to nifti
    nii_image = nibabel.Nifti1Image(full_block, affine)
    timing_parameters = multiframe_dicom.SharedFunctionalGroupsSequence[0].MRTimingAndRelatedParametersSequence[0]
    first_frame = multiframe_dicom[Tag(0x5200, 0x9230)][0]
    common.set_tr_te(nii_image, float(timing_parameters.RepetitionTime),
                     float(first_frame[0x2005, 0x140f][0].EchoTime))

    # Save to disk
    if output_file is not None:
        logger.info('Saving nifti to disk %s' % output_file)
        nii_image.to_filename(output_file)

    if _is_multiframe_diffusion_imaging(dicom_input):
        bval_file = None
        bvec_file = None
        if output_file is not None:
            # Create the bval en bvec files
            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, bvec, bval_file, bvec_file = _create_bvals_bvecs(multiframe_dicom, bval_file, bvec_file, nii_image,
                                                               output_file)

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

    return {'NII_FILE': output_file,
            'NII': nii_image}