Exemple #1
0
def GlobalApply(vfn,
                kfn,
                vstop=0.02,
                kstop=0.05,
                rlambda=1E-4,
                niters=100,
                nvar=0.1,
                gain=0.5,
                prefilter=None,
                out=None,
                omf=False,
                fast=True,
                vext=True,
                savedf=False,
                verbose=0,
                p2fft=False):
    wtype = np.float32 if fast else np.float64
    volume = MIV(vfn, dtype=wtype)
    kernel = MIV(kfn, dtype=wtype)

    v = None
    if vext is 'fft':
        v = volume.GetFFTVolume(p2=True)
    elif vext is True:
        v = volume.Mirror(volume.vdim // 8).GetFFTVolume()
    elif vext is 0:
        v = volume.Pad(volume.vdim // 8).GetFFTVolume()
    else:
        pdim = MIV.FFTSize(volume.vdim, p2=p2fft) - volume.vdim
        v = volume.Mirror(pdim)
        #v = volume.GetFFTVolume()
    s = v.vdim.clip(kernel.vdim)
    print 'PadTo: ', s
    k = kernel.PadTo(s)
    v = v.PadTo(s)
    if isinstance(prefilter, str):
        try:
            v = v.ApplyMask(prefilter)
            k = k.ApplyMask(prefilter)
        except:
            print 'Masking method %s not found' % prefilter
            return
    r = v.Clone(data=[])
    dm = vstop / 10
    cm = int((5 + np.log10(vstop)) * 200)

    dcv = BDKF()
    dcv.SetWorkingSize(k.cdim)
    dcv.SetParameters(vstop, kstop, rlambda, dm, cm, niters, verbose)
    dcv.SetFilterParameters(nvar, gain)
    dcv.Invoke(v, k, r)
    dcv.Release()
    r = r.Rip(volume.vdim)
    if out is None:
        return r
    r.Save(filename=out)
    if isinstance(omf, int) and omf > 2:
        r.Filter.Median(omf).Save(XFile.NewExt(out, 'mf%d.miv' % omf))
    if savedf is True:
        k.Rip(kernel.vdim).Save(XFile.NewExt(out, 'kdf.miv'))
Exemple #2
0
 def GetFullPath(dll):
     if XFile.Exists(dll):
         return os.path.abspath(dll)
     dpath = ExternalLib.DEFAULT_SHARED_LIB_PATH
     if dpath is None:
         dpath = os.path.abspath('./lib')
         if not XFile.PathExists(dpath):
             return dll
     return dpath + os.sep + dll
Exemple #3
0
def Tiff2MIV(sdir, odir, pattern='*.tif'):
    if not XFile.PathExists(odir):
        XFile.MkDir(odir)

    for f in XFile.GetList(sdir, pattern):
        print 'Loading', f, '...',
        v = TIV(sdir + '/' + f)
        print 'done.'
        v = MIV(v.data[:, :, :, 0].copy())
        v.Save(odir + '/' + XFile.NewExt(f, 'miv'))
Exemple #4
0
 def Save(self, filename=None):
     if isinstance(filename, str):
         self.filename = filename
     while self.filename == None or self.filename == '':
         self.filename = raw_input('Enter new filename: ').strip()
         if self.filename != '' and XFile.GetExt(
                 self.filename) != MIV.DEFAULT_EXTENSION:
             self.filename = XFile.NewExt(self.filename,
                                          MIV.DEFAULT_EXTENSION)
     print 'Saving data to %s ... ' % (self.filename),
     MIV.Write(self.filename, self.data, self.vsize, self.vunit, self.clist)
     print 'done.'
Exemple #5
0
 def SaveHDF5(self, filename=None, compression=None, level=6):
     try:
         import h5py
         if isinstance(filename,str):
             self.filename = filename
         if not isinstance(self.filename,str):
             self.filename = raw_input('Enter new filename: ').strip()
         hdf = h5py.File(XFile.NewExt(self.filename, 'h5v'), 'w')
         vds = None
         if compression == 'gzip' and isinstance(level,int):
             vds = hdf.create_dataset('volume', data=self.data,
                                     compression=compression,
                                     compression_opts=level)
         elif compression == 'lzf':
             vds = hdf.create_dataset('volume', data=self.data,
                                     compression=compression)
         else:
             vds = hdf.create_dataset('volume', data=self.data)
         vds.attrs['voxel_size'] = self.vsize
         vds.attrs['voxel_unit'] = self.vunit
         vds.attrs['n_channels'] = self.nchan
         vds.attrs['vcolorlist'] = self.clist
         hdf.attrs['vclzid'] = self.__class__.__name__
         hdf.close()
     except ImportError:
         print 'Error: h5py module is required to save to HDF5 format'
     except:
         print 'Unexpected error:', sys.exc_info()[0]
Exemple #6
0
 def Release(self):
     try:
         while self.DFree(self.hid) == 1:
             pass
         cdll.__delattr__(XFile.CutExt(self.dll))
     except Exception:
         pass
Exemple #7
0
def SegBulk(sdir, odir, mk=None, sk=None, ft='mf', pattern='*.miv'):
    if not XFile.PathExists(odir):
        os.mkdir(odir)

    if mk is None:
        mk = [3] * 3
    if sk is None:
        sk = [0.5] * 3

    t0 = time.time()
    files = XFile.GetList(sdir, pattern)
    for f in files:
        fn = sdir + '/' + f
        fo = odir + '/' + XFile.NewExt(f, 'bin.miv')
        MIV_Seg(fn, mk=mk, sk=sk, pfk=[.5] * 3, fltmode=ft, out=fo)
    print 'Total time: %.1fs' % (time.time() - t0)
Exemple #8
0
 def Load(self, filename):
     try:
         if XFile.GetExt(filename) != RIV.DEFAULT_EXTENSION:
             raise RIVError(-1)
         fn = XFile.CutExt(filename)  # filename without ext
         mi = XFile.GetExt(fn)  # extract metainfo
         if mi == '':
             raise RIVError(-1)
         dt = mi[-1]  # last char in metainfo is datatype
         vt = RIV_DTYPES['b']  # assume 'byte' type if no datatype
         if RIV_DTYPES.has_key(dt):
             vt = RIV_DTYPES[dt]
             mi = mi[:-1]
         mi = mi.split('x')
         if len(mi) != 3:
             raise RIVError(-2, mi)
         xdim, ydim, zdim = vdim = [int(v) for v in mi]
         if xdim <= 0 or ydim <= 0 or zdim <= 0:
             raise RIVError(-2, vdim)
         # Load data type ID (compatible with ImageJ data type)
         dm = (zdim, ydim, xdim) if dt != 'c' else (zdim, ydim, xdim, 3)
         # Voxel unit (See Volume.VOXEL_UNITS)
         vu = 0  # no voxel unit (default is pixel)
         # Voxel size
         vs = [1.0] * 3  # no voxel size (default [1,1,1])
         # Number of channels
         nc = 1  # only support 1 channel
         # Color map id (support maximum 8 channels)
         cl = [0] * 8  # color table is gray
         with open(filename, 'rb') as fp:
             # Load data
             vb = np.fromfile(fp, np.dtype(vt)).reshape(dm)
     except RIVError as err:
         print err.message % filename, err.info
         raise
     except Exception:
         raise
     else:
         self.data = vb
         self.xdim = xdim
         self.ydim = ydim
         self.zdim = zdim
         self.vdim = vdim
         self.vunit = vu
         self.vsize = vs
         self.nchan = nc
         self.clist = cl
Exemple #9
0
 def Load(self, dirname):
     try:
         if not XFile.PathExists(dirname):
             raise DIVError(-1)
         files = XFile.GetList(dirname, '*.' + DIV.DEFAULT_EXTENSION)
         if files is None or len(files) == 0:
             raise DIVError(-2)
         vol = None
         vdim = None
         for dfile in sorted(files):
             dicom = gdcm.ImageReader()
             dicom.SetFileName(dirname + '/' + dfile)
             if not dicom.Read():
                 raise DIVError(-3)
             image = dicom.GetImage()
             if vdim is None:
                 vdim = image.GetDimensions()  # Image dimensions
                 fmt = image.GetPixelFormat()  # Pixel format
                 vs = image.GetSpacing()  # Voxel size
                 vdim.append(len(files))
                 dt = DIV_DTYPES[fmt.GetScalarType()]
             raw = np.frombuffer(image.GetBuffer(), dtype=dt)
             vol = raw if vol is None else np.append(vol, raw)
         xdim, ydim, zdim = vdim
         vol = vol.reshape((zdim, ydim, xdim))
         vu = Volume.VOXEL_UNITS['mm']
         cl = [0] * 8
         nc = 1
     except DIVError as err:
         print err.message % filename, err.info
         raise
     except Exception:
         raise
     else:
         self.data = vol
         self.xdim = xdim
         self.ydim = ydim
         self.zdim = zdim
         self.vdim = vdim
         self.vunit = vu
         self.vsize = vs
         self.nchan = nc
         self.clist = cl
Exemple #10
0
    def Init(self, dll):
        if XFile.GetExt(dll) == '':
            if platform.system() == 'Windows':
                dll += '.dll'
            else:
                dll += '.so'

        try:
            self.lib = cdll.__getattr__(XFile.CutExt(dll))
        except Exception:
            self.lib = cdll.LoadLibrary(self.GetFullPath(dll))

        self.dll = dll
        if platform.system() == 'Windows':
            self.DFree = cdll.kernel32.FreeLibrary
            self.hid = c_voidp(self.lib._handle)
        else:
            self.DFree = cdll.LoadLibrary('libdl.so').dlclose
            self.hid = self.lib._handle
        self.npt = cpu_count()
        self.args = []
Exemple #11
0
 def Promote(self, clz):
     if not issubclass(clz, Volume):
         raise TypeError('%s must be a subclass of %s' % (repr(clz), repr(Volume)))
     self.__class__ = clz
     if self.filename is not None:
         self.filename = XFile.NewExt(self.filename, clz.DEFAULT_EXTENSION)
Exemple #12
0
def MIV_Seg(fn=None,
            mk=[1.0] * 3,
            sk=[20.0] * 3,
            pfk=[1.5] * 3,
            fltmode='ln',
            pad=None,
            out=None,
            **kw_args):

    if not isinstance(fn, str):
        fn = raw_input('Input MIV file: ')
        if fn == '':
            return
    if isinstance(out, bool) and out == True:
        out = None
    elif out is MIV:
        pass
    elif not isinstance(out, str):
        out = XFile.NewExt(fn, 'bin.miv')

    t0 = time.time()

    print 'Starting QuickSeg("%s", mk=%s, sk=%s)' % (fn, str(mk), str(sk))
    print '- Loading...'
    v = MIV(fn)
    if isinstance(pad, np.ndarray) and len(pad.shape) == 1 and pad.size == 3:
        v = v.Pad(pad)

    if fltmode == 'ln':
        print '- Local Normalizing...'
        p = v.Filter.LocalNormalize(sigm=mk, sigv=sk)
        print '- GF Smoothing...'
        p = p.GetFFTVolume()
        if pfk != None:
            p = p.Filter.Gaussian(pfk)
    elif fltmode == 'mo':
        print '- Morphing...'
        p = v.Morph('Close', Volume.Gaussian(mk), gray=True)
        print '- GF Smoothing...'
        p = p.GetFFTVolume()
        p = p.Filter.Gaussian(sk)
    elif fltmode == 'gf':
        print '- GF Smoothing...'
        p = v.GetFFTVolume()
        p = p.Filter.Gaussian(sk)
    elif fltmode == 'mf':
        print '- MF Smoothing...'
        p = v.GetFFTVolume()
        k = Volume.Ones(tuple(mk))
        p = p.Filter.Median(k, cdf=True)
    elif fltmode == 'af':
        print '- AF Smoothing...'
        p = v.GetFFTVolume()
        p = p.Filter.Anisotropic(N=mk[0])
    else:
        print '- No Smoothing...'
        p = v.GetFFTVolume()

    print '- Local mean calculating...'
    s = p.Filter.Hanning().Rip(v.vdim)
    p = p.Rip(v.vdim).AsByte()
    print '- Binarizing...'
    v = DynaBinarize(p, s, mk, **kw_args)
    if isinstance(out, str) or out is None:
        v.Save(filename=out)

    print 'Elapse: %.1fs' % (time.time() - t0)
    if out is MIV:
        return v