Beispiel #1
0
def makeHdrFromRdr(rdr):
    """
    rdr: reader object
    return header
    """
    if hasattr(rdr, 'hdr'):
        hdr = rdr.hdr
    else:
        hdr = Mrc.makeHdrArray()
        Mrc.init_simple(hdr, Mrc.dtype2MrcMode(rdr.dtype), rdr.shape)
        hdr.ImgSequence = rdr.imgSequence
        hdr.NumTimes = rdr.nt
        hdr.NumWaves = rdr.nw
        hdr.Num[-1] = rdr.nt * rdr.nw * rdr.nz
        if len(rdr.wave):
            if [
                    1 for wave in rdr.wave[:rdr.nw]
                    if isinstance(wave, basestring)
            ]:
                hdr.wave[:rdr.nw] = 0
            else:
                hdr.wave[:rdr.nw] = rdr.wave[:rdr.nw]
        hdr.d = rdr.pxlsiz[::-1]
        if rdr.metadata.has_key('Instrument'):
            hdr.LensNum = eval(
                rdr.metadata['Instrument']['Objective']['ID'].split(':')[1])

    return hdr
Beispiel #2
0
def saveNewMrc(mrc_path, arr, n_tzcyx, cal_xyz, wavelengths=None):
    """
    Write a new Mrc file using numpy ndarray 'arr' and tuples of
    - dimension sizes (nt, nz, nc, ny, nx) and
    - float pixel calibrations in microns (cal_x, cal_y, cal_z)
    """
    nt, nz, nc, ny, nx = n_tzcyx
    if not wavelengths:
        wavelengths = tuple(900 + n for n in range(5))

    arr = numpy.reshape(arr, n_tzcyx)  # introduce length 1 dimensions
    arr = arr.transpose([0, 2, 1, 3, 4])  # Mrc output shape "ZWT"

    hdr = Mrc.makeHdrArray()
    mrc_mode = Mrc.dtype2MrcMode(arr.dtype)
    nslices = nt * nz * nc
    Mrc.init_simple(hdr, mrc_mode, (nslices, ny, nx))  # set default hdr values
    hdr.NumTimes = nt
    hdr.NumWaves = nc
    hdr.ImgSequence = 2  # write in order "ZWT"
    hdr.d = cal_xyz
    hdr.wave = wavelengths

    # write header & slices
    f_out = file(mrc_path, 'wb')
    f_out.write(hdr._array.tostring())
    for t in range(nt):
        for c in range(nc):
            for z in range(nz):
                arr_yx_yinverted = arr[t, c, z, ::-1, :]
                f_out.write(arr_yx_yinverted.copy(order='C'))

    f_out.close()
    
    return DataDoc(mrc_path)
Beispiel #3
0
    def doOnSetDim(self):
        pixelType = Mrc.dtype2MrcMode(self.dtype)
        num = self.nx, self.ny, self.nz * self.nw * self.nt
        if not self.hdr:
            self.hdr = Mrc.makeHdrArray()
            init_simple(self.hdr, pixelType, num)
        self.hdr.Num = num
        self.hdr.NumTimes = self.nt
        self.hdr.NumWaves = self.nw
        self.hdr.PixelType = pixelType
        self.hdr.ImgSequence = self.imgSequence
        self.hdr.wave[:self.nw] = self.wave[:self.nw]
        self.hdr.d[:] = self.pxlsiz[::-1]

        self.writeHeader(self.hdr)
Beispiel #4
0
    def doOnSetDim(self):
        pixelType = Mrc.dtype2MrcMode(self.dtype)
        num = self.nx, self.ny, self.nz * self.nw * self.nt
        if not self.hdr:
            self.hdr = Mrc.makeHdrArray()
            init_simple(self.hdr, pixelType, num)
        self.hdr.Num = num
        self.hdr.NumTimes = self.nt
        self.hdr.NumWaves = self.nw
        self.hdr.PixelType = pixelType
        self.hdr.ImgSequence = self.imgSequence
        self.hdr.wave[:self.nw] = self.wave[:self.nw]
        self.hdr.d[:] = self.pxlsiz[::-1]

        #self.makeHdr()
        #self.setDimFromMrcHdr(hdr)
        self.writeHeader(self.hdr, extInts=self.extInts, extFloats=self.extFloats)
Beispiel #5
0
    def makeHdr(self):
        """
        make a Mrc header using the available dimension information to export
        """
        if not self.hdr:
            hdr = Mrc.makeHdrArray()
            Mrc.init_simple(hdr, Mrc.dtype2MrcMode(self.dtype), self.shape)
            hdr.ImgSequence = self.imgSequence
            hdr.NumTimes = self.nt
            hdr.NumWaves = self.nw
            hdr.Num[-1] = self.nt * self.nw * self.nz
            if len(self.wave):
                hdr.wave[:self.nw] = self.wave[:self.nw]
            hdr.d = self.pxlsiz[::-1]
            if 'Instrument' in self.metadata:
                hdr.hdr.LensNum = eval(self.metadata['Instrument']['Objective']['ID'].split(':')[1])

            self.hdr = hdr
Beispiel #6
0
    def makeHdr(self):
        """
        make a Mrc header using the available dimension information to export
        """
        if not self.hdr:
            hdr = Mrc.makeHdrArray()
            Mrc.init_simple(hdr, Mrc.dtype2MrcMode(self.dtype), self.shape)
            hdr.ImgSequence = self.imgSequence
            hdr.NumTimes = self.nt
            hdr.NumWaves = self.nw
            hdr.Num[-1] = self.nt * self.nw * self.nz
            if len(self.wave):
                hdr.wave[:self.nw] = self.wave[:self.nw]
            hdr.d = self.pxlsiz[::-1]
            if 'Instrument' in self.metadata:
                hdr.hdr.LensNum = eval(self.metadata['Instrument']['Objective']['ID'].split(':')[1])

            self.hdr = hdr
def makeFlatConv(fn, out=None, suffix=''):  #, dark=None):
    """
    save a calibration file
    
    return output file name
    """
    if not out:
        out = os.path.extsep.join((os.path.splitext(fn)[0] + suffix, EXT))
        #out = fn + EXT
    h = imgfileIO.load(fn)  #mrcIO.MrcReader(fn)
    h.makeHdr()
    ntz = h.nz * h.nt
    hdr = mrcIO.makeHdr_like(h.hdr)
    hdr.NumTimes = 1
    hdr.Num[-1] = h.nw  # * 2
    hdr.PixelType = Mrc.dtype2MrcMode(N.float32)
    hdr.type = IDTYPE
    for w in range(h.nw):
        if w == 0:
            hdr.mmm1[0] = 0
            hdr.mmm1[1] = 2
        else:
            exec('hdr.mm%i[0] = 0' % (w + 1))
            exec('hdr.mm%i[1] = 2' % (w + 1))

    #o = imgfileIO.getWriter(out, hdr)
    o = mrcIO.MrcWriter(out, hdr)
    for w in range(h.nw):
        canvas = N.zeros((h.nt, h.nz, h.ny, h.nx), N.float32)
        #o.writeArr(canvas[0,0], w=w, z=0)
        # o.writeArr(canvas[0,0], w=w, z=2)
        #o.writeArr(canvas[0,0], w=w, z=3)
        for t in range(h.nt):
            for z in range(h.nz):
                canvas[t, z] = h.getArr(w=w, t=t, z=z)
        arr = canvas.reshape(ntz, h.ny, h.nx).mean(axis=0)
        arr = arr.mean() / arr
        o.writeArr(arr.astype(N.float32), w=w, z=0)  #1)
    o.close()
    h.close()

    return out
Beispiel #8
0
def makeHdrFromRdr(rdr):
    """
    rdr: reader object
    return header
    """
    if hasattr(rdr, 'hdr'):
        hdr = makeHdr_like(rdr.hdr)
    else:
        hdr = Mrc.makeHdrArray()
        Mrc.init_simple(hdr, Mrc.dtype2MrcMode(rdr.dtype), rdr.shape)
        hdr.ImgSequence = rdr.imgSequence
        hdr.NumTimes = rdr.nt
        hdr.NumWaves = rdr.nw
        hdr.Num[-1] = rdr.nt * rdr.nw * rdr.nz
        if len(rdr.wave):
            if [1 for wave in rdr.wave[:rdr.nw] if isinstance(wave, six.string_types)]:
                hdr.wave[:rdr.nw] = 0
            else:
                hdr.wave[:rdr.nw] = rdr.wave[:rdr.nw]
        hdr.d = rdr.pxlsiz[::-1]
        if 'Instrument' in rdr.metadata:
            hdr.LensNum = eval(rdr.metadata['Instrument']['Objective']['ID'].split(':')[1])

    return hdr
Beispiel #9
0
    def alignAndCrop(self, wavelengths = [], timepoints = [], 
            savePath = None):
        """
        Align and Crop the chosen channels/timepoints according to 
        values already set in this DataDoc, and save the new MRC 
        file result.
        """
        if not wavelengths:
            wavelengths = range(self.size[0])
        if not timepoints:
            timepoints = range(self.cropMin[1], self.cropMax[1])

        # Generate the cropped shape of the file.
        croppedShape = [len(wavelengths)]
        for min, max in zip(self.cropMin[1:], self.cropMax[1:]):
            croppedShape.append(max - min)
        # Reorder to time/wavelength/z/y/x for saving.
        croppedShape[0], croppedShape[1] = croppedShape[1], croppedShape[0]
        croppedShape = tuple(croppedShape)

        newHeader = Mrc.makeHdrArray()
        Mrc.initHdrArrayFrom(newHeader, self.imageHeader)
        newHeader.Num = (croppedShape[4], croppedShape[3], 
                croppedShape[2] * len(timepoints) * len(wavelengths))
        newHeader.NumTimes = len(timepoints)
        newHeader.NumWaves = len(wavelengths)
        # Size of the extended header -- forced to zero for now.
        newHeader.next = 0
        # Ordering of data in the file; 2 means z/w/t
        newHeader.ImgSequence = 2
        newHeader.PixelType = Mrc.dtype2MrcMode(numpy.float32)

        if not savePath:
            outputArray = numpy.empty(croppedShape, numpy.float32)
        else:
            if self.filePath == savePath:
                # \todo Why do we do this?
                del self.image.Mrc

            # Write out the header.
            outputFile = file(savePath, 'wb')
            outputFile.write(newHeader._array.tostring())

        # Slices to use to crop out the 3D volume we want to use for each
        # wave-timepoint pair.
        volumeSlices = []
        for min, max in zip(self.cropMin[2:], self.cropMax[2:]):
            volumeSlices.append(slice(min, max))
        for timepoint in timepoints:
            for waveIndex, wavelength in enumerate(wavelengths):
                volume = self.imageArray[wavelength][timepoint]
                dx, dy, dz, angle, zoom = self.alignParams[wavelength]
                if dz and self.size[2] == 1:
                    dz = 0  # in 2D files Z translation blanks out the slice!
                if dx or dy or dz or angle or zoom != 1:
                    # Transform the volume.
                    volume2 = self.transformArray(
                            volume, dx, dy, dz, angle, zoom
                    )
                else:
                    volume2 = volume.copy()  # no transform
                # Crop to the desired shape.
                volume2 = volume2[volumeSlices].astype(numpy.float32)
                if not savePath:
                    outputArray[timepoint, waveIndex] = volume2
                else:
                    # Write to the file.
                    for i, zSlice in enumerate(volume2):
                        outputFile.write(zSlice)
        if not savePath:
            # Reorder to WTZYX since that's what the user expects.
            return outputArray.transpose([1, 0, 2, 3, 4])
        else:
            outputFile.close()
Beispiel #10
0
    def saveSelection(self, wavelengths = [], timepoints = [],                   
            savePath = None):
        """
        Save a wavelength=channel and/or timepoint=frame selection.
        Basically a duplicate of parts of the alignAndCrop method below,
        which should now be refactored to use this method instead.
        Note that a new MRC object is created in the process.
        """
        if not wavelengths:
            wavelengths = range(self.size[0])
        if not timepoints:
            timepoints = range(self.cropMin[1], self.cropMax[1])
        newShape = numpy.array([len(wavelengths), len(timepoints), self.size[2], 
                    self.size[3], self.size[4] ], dtype = numpy.int)

        # make a new header
        newHeader = Mrc.makeHdrArray()
        Mrc.initHdrArrayFrom(newHeader, self.imageHeader)
        newHeader.Num = (self.size[4], self.size[3], 
                self.size[2] * len(timepoints) * len(wavelengths))
        newHeader.NumTimes = len(timepoints)
        newHeader.NumWaves = len(wavelengths)
        # Size of the extended header -- forced to zero for now.
        newHeader.next = 0
        # Ordering of data in the file; 2 means z/w/t
        newHeader.ImgSequence = 2
        newHeader.PixelType = Mrc.dtype2MrcMode(numpy.float32)

        if not savePath:
            outputArray = numpy.empty(newShape, numpy.float32)
        else:
            if self.filePath == savePath:
                # \todo Why do we do this?
                del self.image.Mrc

            # update wavelength info to ensure it remains correct
            #  (we could be re-ordering here)
            for waveIndex, wavelength in enumerate(wavelengths):
                trueWavelength = self.imageHeader.wave[wavelength]
                newHeader.wave[waveIndex] = trueWavelength

            # Write out the header.
            outputFile = file(savePath, 'wb')
            outputFile.write(newHeader._array.tostring())

        for timepoint in timepoints:
            for waveIndex, wavelength in enumerate(wavelengths):
                volume = self.imageArray[wavelength][timepoint]
                
                if not savePath:
                    outputArray[timepoint, waveIndex] = volume
                else:
                    # Write to the file.
                    for i, zSlice in enumerate(volume):
                        outputFile.write(zSlice)

        if not savePath:
            # Reorder to WTZYX since that's what the user expects.
            return outputArray.transpose([1, 0, 2, 3, 4])
        else:
            outputFile.close()