Beispiel #1
0
    def Export(self,
               data,
               outFile,
               xslice,
               yslice,
               zslice,
               metadata=None,
               events=None,
               origName=None,
               progressCallback=None):
        numpy.save(outFile, data[xslice, yslice, zslice])

        if not metadata is None:
            xmd = MetaDataHandler.XMLMDHandler(mdToCopy=metadata)
            if not origName is None:
                xmd.setEntry('cropping.originalFile', origName)

            xmd.setEntry('cropping.xslice', xslice.indices(data.shape[0]))
            xmd.setEntry('cropping.yslice', yslice.indices(data.shape[1]))
            xmd.setEntry('cropping.zslice', zslice.indices(data.shape[2]))

            xmlFile = os.path.splitext(outFile)[0] + '.xml'
            xmd.writeXML(xmlFile)
            #xmd.WriteSimple(xmlFile)

        if progressCallback:
            try:
                progressCallback(100, 100)
            except:
                pass
Beispiel #2
0
    def Export(self,
               data,
               outFile,
               xslice,
               yslice,
               zslice,
               metadata=None,
               events=None,
               origName=None,
               progressCallback=None):
        #nframes = (zslice.stop - zslice.start)/zslice.step

        outDir = os.path.splitext(outFile)[0]
        os.mkdir(outDir)

        i = 0
        for frameN in range(zslice.start, zslice.stop, zslice.step):
            im = data[xslice, yslice, frameN].squeeze()[None, :, :]
            for fN in range(frameN + 1, frameN + zslice.step):
                im += data[xslice, yslice, fN].squeeze()[None, :, :]

            Image.fromarray(im.squeeze().astype('uint16'), 'I;16').save(
                os.path.join(outDir, 'frame_%03d.tif' % i))
            i += 1

        if not metadata is None:
            xmd = MetaDataHandler.XMLMDHandler(mdToCopy=metadata)
            if not origName is None:
                xmd.setEntry('cropping.originalFile', origName)

            xmd.setEntry('cropping.xslice', xslice.indices(data.shape[0]))
            xmd.setEntry('cropping.yslice', yslice.indices(data.shape[1]))
            xmd.setEntry('cropping.zslice', zslice.indices(data.shape[2]))

            xmlFile = os.path.splitext(outFile)[0] + '.xml'
            xmd.writeXML(xmlFile)
            # xmd.WriteSimple(xmlFile)

        if progressCallback:
            try:
                progressCallback(100, 100)
            except:
                pass
Beispiel #3
0
    def _findAndParseMetadata(self, filename):
        """Try and find and load a .xml or .md metadata file that might be ascociated
        with a given image filename. See the relevant metadatahandler classes
        for details."""
        import xml.parsers.expat
        from PYME.IO import unifiedIO

        if not self.mdh is None:
            return  #we already have metadata (probably passed in on command line)

        mdf = None
        xmlfn = os.path.splitext(filename)[0] + '.xml'
        xmlfnmc = os.path.splitext(filename)[0].split('__')[0] + '.xml'
        if os.path.exists(xmlfn):
            try:
                self.mdh = MetaDataHandler.NestedClassMDHandler(
                    MetaData.TIRFDefault)
                self.mdh.copyEntriesFrom(MetaDataHandler.XMLMDHandler(xmlfn))
                mdf = xmlfn
            except xml.parsers.expat.ExpatError:
                #fix for bug in which PYME .md was written with a .xml extension
                self.mdh = MetaDataHandler.NestedClassMDHandler(
                    MetaData.BareBones)
                self.mdh.copyEntriesFrom(
                    MetaDataHandler.SimpleMDHandler(xmlfn))
                mdf = xmlfn

        elif os.path.exists(
                xmlfnmc):  #this is a single colour channel of a pair
            self.mdh = MetaDataHandler.NestedClassMDHandler(
                MetaData.TIRFDefault)
            self.mdh.copyEntriesFrom(MetaDataHandler.XMLMDHandler(xmlfnmc))
            mdf = xmlfnmc
        else:
            self.mdh = MetaDataHandler.NestedClassMDHandler(MetaData.BareBones)

            #check for simple metadata (python code with an .md extension which
            #fills a dictionary called md)
            mdfn = os.path.splitext(filename)[0] + '.md'
            jsonfn = os.path.splitext(filename)[0] + '.json'
            if os.path.exists(mdfn):
                self.mdh.copyEntriesFrom(MetaDataHandler.SimpleMDHandler(mdfn))
                mdf = mdfn
            elif os.path.exists(jsonfn):
                import json
                with open(jsonfn, 'r') as f:
                    mdd = json.load(f)
                    self.mdh.update(mdd)
            elif filename.endswith('.lsm'):
                #read lsm metadata
                from PYME.contrib.gohlke.tifffile import TIFFfile
                tf = TIFFfile(filename)
                lsm_info = tf[0].cz_lsm_scan_information
                self.mdh['voxelsize.x'] = lsm_info['line_spacing']
                self.mdh['voxelsize.y'] = lsm_info['line_spacing']
                self.mdh['voxelsize.z'] = lsm_info['plane_spacing']

                def lsm_pop(basename, dic):
                    for k, v in dic.items():
                        if isinstance(v, list):
                            #print k, v
                            for i, l_i in enumerate(v):
                                #print i, l_i, basename
                                lsm_pop(
                                    basename + k + '.' + k[:-1] + '%i.' % i,
                                    l_i)

                        else:
                            self.mdh[basename + k] = v

                lsm_pop('LSM.', lsm_info)

            elif filename.endswith('.tif'):
                #look for OME data...
                from PYME.contrib.gohlke.tifffile import TIFFfile
                tf = TIFFfile(filename)

                if tf.is_ome:
                    try:
                        omemdh = MetaDataHandler.OMEXMLMDHandler(
                            tf.pages[0].tags['image_description'].value)

                        self.mdh.copyEntriesFrom(omemdh)
                    except IndexError:
                        pass

            elif filename.endswith('.dcimg'):  #Bewersdorf lab Biplane
                # FIXME load seriesXX.json for seriesXX_chunkXX.dcimg files more elegantly
                jsonfn = filename[:-22] + '.json'

                import json
                try:
                    mdd = json.loads(unifiedIO.read(jsonfn))
                    self.mdh.update(mdd)

                except IOError:
                    pass

            elif filename.endswith('.dbl'):  #Bewersdorf lab STED
                mdfn = filename[:-4] + '.txt'
                entrydict = {}

                try:  #try to read in extra metadata if possible
                    with unifiedIO.openFile(mdfn, 'r') as mf:
                        for line in mf:
                            s = line.split(':')
                            if len(s) == 2:
                                entrydict[s[0]] = s[1]

                except IOError:
                    pass


#                vx, vy = entrydict['Pixel size (um)'].split('x')
#                self.mdh['voxelsize.x'] = float(vx)
#                self.mdh['voxelsize.y'] = float(vy)
#                self.mdh['voxelsize.z'] = 0.2 #FIXME for stacks ...
#
#                sx, sy = entrydict['Image format'].split('x')
#                self.mdh['Camera.ROIWidth'] = int(sx)
#                self.mdh['Camera.ROIHeight'] = int(sy)
#
#                self.mdh['NumImages'] = int(entrydict['# Images'])

                with unifiedIO.openFile(filename) as df:
                    s = df.read(8)
                    Z, X, Y, T = numpy.fromstring(s, '>u2')
                    s = df.read(16)
                    depth, width, height, elapsed = numpy.fromstring(s, '<f4')

                    self.mdh['voxelsize.x'] = width / X
                    self.mdh['voxelsize.y'] = height / Y
                    self.mdh['voxelsize.z'] = depth

                    self.mdh['Camera.ROIWidth'] = X
                    self.mdh['Camera.ROIHeight'] = Y
                    self.mdh['NumImages'] = Z * T

                def _sanitise_key(key):
                    k = key.replace('#', 'Num')
                    k = k.replace('(%)', '')
                    k = k.replace('(', '')
                    k = k.replace(')', '')
                    k = k.replace('.', '')
                    k = k.replace('/', '')
                    k = k.replace('?', '')
                    k = k.replace(' ', '')
                    if not k[0].isalpha():
                        k = 's' + k
                    return k

                for k, v in entrydict.items():
                    self.mdh['STED.%s' % _sanitise_key(k)] = v

            #else: #try bioformats
            #    OMEXML = bioformats.get_omexml_metadata(filename).encode('utf8')
            #    OMEmd = MetaDataHandler.OMEXMLMDHandler(OMEXML)
            #    self.mdh.copyEntriesFrom(OMEmd)

        if self.haveGUI and not ('voxelsize.x' in self.mdh.keys()
                                 and 'voxelsize.y' in self.mdh.keys()):
            from PYME.DSView.voxSizeDialog import VoxSizeDialog

            dlg = VoxSizeDialog(None)
            dlg.ShowModal()

            self.mdh.setEntry('voxelsize.x', dlg.GetVoxX())
            self.mdh.setEntry('voxelsize.y', dlg.GetVoxY())
            self.mdh.setEntry('voxelsize.z', dlg.GetVoxZ())

        return mdf
Beispiel #4
0
    def Export(self,
               data,
               outFile,
               xslice,
               yslice,
               zslice,
               metadata=None,
               events=None,
               origName=None,
               progressCallback=None):
        #numpy.save(outFile, data[xslice, yslice, zslice])
        #import cPickle

        try:
            chanNames = metadata.getEntry('ChannelNames')
        except:
            chanNames = ['Chan %d' % d for d in range(data.shape[4])]

        dat = [
            data[xslice, yslice, zslice, :, chan].squeeze()
            for chan in range(data.shape[4])
        ]

        #print chanNames

        if metadata and 'Profile.XValues' in metadata.getEntryNames():
            dat = [metadata.getEntry('Profile.XValues')] + dat
            chanNames = [metadata.getEntry('Profile.XLabel')] + chanNames

        if metadata and 'Spectrum.Wavelengths' in metadata.getEntryNames():
            dat = [metadata.getEntry('Spectrum.Wavelengths')] + dat
            chanNames = ['Wavelength [nm]'] + chanNames

        fid = open(outFile, 'wb')

        #write header
        fid.write(('#' + '\t'.join(chanNames)).encode('utf-8'))

        for i in range(len(dat[0])):
            fid.write(
                ('\n' + '\t'.join(['%f' % d[i] for d in dat])).encode('utf-8'))

        fid.close()

        # write metadata in xml file
        if not metadata is None:
            xmd = MetaDataHandler.XMLMDHandler(mdToCopy=metadata)
            if not origName is None:
                xmd.setEntry('cropping.originalFile', origName)

            xmd.setEntry('cropping.xslice', xslice.indices(data.shape[0]))
            xmd.setEntry('cropping.yslice', yslice.indices(data.shape[1]))
            xmd.setEntry('cropping.zslice', zslice.indices(data.shape[2]))

            xmlFile = os.path.splitext(outFile)[0] + '.xml'
            xmd.writeXML(xmlFile)

        if progressCallback:
            try:
                progressCallback(100, 100)
            except:
                pass
Beispiel #5
0
    def Export(self,
               data,
               outFile,
               xslice,
               yslice,
               zslice,
               metadata=None,
               events=None,
               origName=None,
               progressCallback=None):
        warnings.warn(
            'export of old style tiffs should only be used in exceptional circumstances'
        )
        #xmd = None
        if not metadata is None:
            xmd = MetaDataHandler.XMLMDHandler(mdToCopy=metadata)

        if data.shape[3] > 1:  #have multiple colour channels
            if data.shape[2] == 1:  #2d image -> stack with chans
                #d = numpy.concatenate([numpy.atleast_3d(data[xslice, yslice, 0, i].squeeze()) for i in range(data.shape[3])],2)
                #saveTiffStack.saveTiffMultipage(d, outFile)
                mpt = saveTiffStack.TiffMP(outFile)
                for i in range(data.shape[3]):
                    mpt.AddSlice(data[xslice, yslice, 0, i].squeeze())
                mpt.close()
            else:  #save each channel as it's own stack
                if not metadata is None and 'ChannelNames' in metadata.getEntryNames(
                ):
                    chanNames = metadata['ChannelNames']

                else:
                    chanNames = range(data.shape[3])

                chanFiles = [
                    os.path.splitext(os.path.split(outFile)[1])[0] +
                    '__%s.tif' % chanNames[i] for i in range(data.shape[3])
                ]
                if not metadata is None:
                    xmd['ChannelFiles'] = chanFiles

                for i in range(data.shape[3]):
                    saveTiffStack.saveTiffMultipage(
                        data[xslice, yslice, zslice, i].squeeze(),
                        os.path.splitext(outFile)[0] +
                        '__%s.tif' % chanNames[i])
        else:
            saveTiffStack.saveTiffMultipage(data[xslice, yslice, zslice],
                                            outFile)

        if not metadata is None:
            #xmd = MetaDataHandler.XMLMDHandler(mdToCopy=metadata)
            if not origName is None:
                xmd.setEntry('cropping.originalFile', origName)

            xmd.setEntry('cropping.xslice', xslice.indices(data.shape[0]))
            xmd.setEntry('cropping.yslice', yslice.indices(data.shape[1]))
            xmd.setEntry('cropping.zslice', zslice.indices(data.shape[2]))

            print((xslice.indices(data.shape[0])))

            xmlFile = os.path.splitext(outFile)[0] + '.xml'
            xmd.writeXML(xmlFile)
            # xmd.WriteSimple(xmlFile)

        if progressCallback:
            try:
                progressCallback(100, 100)
            except:
                pass