Exemplo n.º 1
0
    def _showOneColorslice(self, param=None):
        """
        It shows a single colored slice of the 3DFSC
        """
        imageFile = self.protocol._getExtraPath(OUTPUT_3DFSC)
        img = ImageHandler().read(imageFile)
        imgData = img.getData()

        xplotter = XmippPlotter(x=1,
                                y=1,
                                mainTitle="3DFSC Slices "
                                "along %s-axis." % self._getAxis())
        sliceNumber = self.sliceNumber.get()
        if sliceNumber < 0:
            x, _, _, _ = ImageHandler().getDimensions(imageFile)
            sliceNumber = int(x / 2)
        else:
            sliceNumber -= 1
        # sliceNumber has no sense to start in zero
        a = xplotter.createSubPlot("Slice %s" % (sliceNumber + 1), '', '')
        matrix = self.getSliceImage(imgData, sliceNumber, self._getAxis())
        plot = xplotter.plotMatrix(a,
                                   matrix,
                                   0,
                                   1,
                                   cmap=self.getColorMap(),
                                   interpolation="nearest")
        xplotter.getColorBar(plot)

        return [plt.show(xplotter)]
Exemplo n.º 2
0
    def appendMicsFromTomogram(self, output, tomo):

        self.info("Creating micrographs for %s" % tomo.getFileName())
        # Load the tomogram
        ih = ImageHandler()
        img = ih.read(tomo.getFileName())
        data = img.getData()

        # For each slice
        for index in range(0, len(data), self.slicesGap.get()):
            self.debug("Creating micrograph for slice %s" % index)
            micName = tomoSliceToMicName(tomo, index)
            outputMicName = self._getExtraPath(micName)
            outputMicName = replaceExt(outputMicName, "mrc")
            slice = data[index]
            micImg = ImageHandler()
            micImg._img.setData(slice)
            micImg.write(micImg._img, outputMicName)

            # Create the micrograph metadata object
            newMic = Micrograph()
            newMic.setFileName(outputMicName)
            newMic.setMicName(micName)
            newMic.setSamplingRate(tomo.getSamplingRate())

            # Append it
            output.append(newMic)
Exemplo n.º 3
0
 def _beforePreview(self):
     imgLocation = self.protocolParent.inputImage.get().getLocation()
     self.dim = ImageHandler().getDimensions(imgLocation)[0]
     self.lastObj = None
     self.rightPreviewLabel = "Final mask"
     self.message = "Generating mask..."
     self.ih = ImageHandler()
     self.rightImage = self.ih.createImage()
Exemplo n.º 4
0
 def readImages(self, img_paths):
     if len(img_paths) == 1:
         # Numpy does not convert a list of size one to an array but to the actual object type of
         # element inside the list. We need to consider this case as it will raise an error in Python
         # when iterating over a non-array object type
         self.images = np.squeeze(ImageHandler().read(
             img_paths[0]).getData())
     else:
         self.images = [
             np.squeeze(ImageHandler().read(img_path).getData())
             for img_path in img_paths
         ]
Exemplo n.º 5
0
    def __init__(self, **kwargs):
        """
        Create a new instance with some configuration parameters.

        Keyword Args:
            rootDir: Specify a directory that will be used as "root"
                for setting the path values in the star file pointing
                to the binaries
            convertPolicy: By default, conversion of binary files will
                create symbolic links if no conversion is required.
                By passing convertPolicy=CONVERT_ALWAYS, it will force
                the conversion.
            useBaseName: (bool) By default the writer will use the id to
                generate shorter names. If this option is True, then
                the images base name will be used instead. This option
                might be useful in export protocols.

        """
        self._optics = kwargs.get('optics', None)
        # Not used now
        # self.convertPolicy = kwargs.get('convertPolicy', self.CONVERT_IF_NEEDED)
        self.rootDir = None
        self.outputDir = None
        self.outputStack = None
        self.useBaseName = False
        self.extensions = ['mrc']
        self.update(['rootDir', 'outputDir', 'userBaseName', 'extensions'],
                    **kwargs)
        self._ih = ImageHandler()  # used to convert images
        self._filesDict = {}  # used to map file names (converted or linked)
        self._dimensionality = 2
        self._imageSize = None
    def convertInputStep(self, inputParticles, inputVolume, targetResolution):
        """ Write the input images as a Xmipp metadata file. 
        particlesId: is only need to detect changes in
        input particles and cause restart from here.
        """
        imgSet = self._getInputParticles()
        convXmp.writeSetOfParticles(imgSet, self._getInputXmd())
        newXdim =self._getNewDim()

        ih = ImageHandler()
        inputVol = self.inputVolume.get()
        fn = ih.fixXmippVolumeFileName(inputVol)
        img = ih.read(fn)
        img.scale(newXdim, newXdim, newXdim)
        img.write(self._getExtraPath("volume.vol"))

        args = '-i %(parts)s -o %(scaledStk)s --save_metadata_stack '
        args += '%(scaledXmd)s --dim %(xDim)d'

        params = {"parts" : self._getInputXmd(),
                  "scaledStk": self._getExtraPath('scaled_particles.stk'),
                  "scaledXmd": self._getExtraPath('scaled_particles.xmd'),
                  "xDim": newXdim
                  }
        self.runJob("xmipp_image_resize", args % params)
Exemplo n.º 7
0
    def createOutputStep(self, volId):
        sym = self.symmetryGroup.get()

        inFn = self._getPath('input_volume.mrc')
        alignedFn = self._getPath('volume_aligned_sym%s.mrc' % sym)
        symFn = self._getPath('volume_sym%s.mrc' % sym)
        pixSize = self.inputVolume.get().getSamplingRate()

        ImageHandler().convert(self.inputVolume.get(), inFn)

        self.runJob(
            "relion_align_symmetry", "--i %s --o %s --sym %s --angpix %0.5f" %
            (inFn, alignedFn, sym, pixSize))

        self.runJob("relion_image_handler",
                    "--i %s --o %s --sym %s" % (alignedFn, symFn, sym))

        def _defineOutputVol(name, fn):
            vol = Volume()
            vol.copyInfo(self.inputVolume.get())
            vol.setLocation(fn)
            self._defineOutputs(**{name: vol})
            self._defineTransformRelation(self.inputVolume, vol)

        _defineOutputVol('outputVolumeAligned', alignedFn)
        _defineOutputVol('outputVolumeSymmetrized', symFn)
    def convertInputStep(self):
        # blocres works with .map
        vol1Fn = self.inputVolume.get().getFileName()
        vol2Fn = self.inputVolume2.get().getFileName()
        if self.mask.get().getFileName() != '':
            maskFn = self.mask.get().getFileName()

        self.fnvol1 = self._getFileName("half1")
        self.fnvol2 = self._getFileName("half2")
        ImageHandler().convert(vol1Fn, self.fnvol1)
        ImageHandler().convert(vol2Fn, self.fnvol2)
        if self.mask.get().getFileName() != '':
            self.fnmask = self._getFileName("maskvol")
            ImageHandler().convert(maskFn, self.fnmask)
        else:
            self.fnmask = self.maks.get().getFileName()
 def _invertScaleVol(self, fn):
     xdim = self._getInputParticles().getXDim()
     outputFn = self._getOutputVolFn(fn)
     ih = ImageHandler()
     img = ih.read(fn)
     img.scale(xdim, xdim, xdim)
     img.write(outputFn)
Exemplo n.º 10
0
 def convertMaskStep(self, maskType):
     """ Convert the input mask if needed."""
     # Copy mask if selected
     if maskType > 0:  # mask from file
         maskFn = self._getFileName('mask')
         ImageHandler().convert(self.maskImage.get().getLocation(),
                                (1, maskFn))
Exemplo n.º 11
0
 def createMaskFromVolumeStep(self):
     volume = self.inputVolume.get()
     fnVol = getImageLocation(volume)
     Ts = volume.getSamplingRate()
     
     if self.volumeOperation == OPERATION_THRESHOLD:
         self.runJob("xmipp_transform_threshold",
                     "-i %s -o %s --select below %f --substitute binarize"
                     % (fnVol, self.maskFile, self.threshold.get()))
     elif self.volumeOperation == OPERATION_SEGMENT:
         args="-i %s -o %s --method " % (fnVol, self.maskFile)
         if self.segmentationType == SEGMENTATION_VOXELS:
             args += "voxel_mass %d" % (self.nvoxels.get())
         elif self.segmentationType == SEGMENTATION_AMINOACIDS:
             args += "aa_mass %d %f" % (self.naminoacids.get(), Ts)
         elif self.segmentationType == SEGMENTATION_DALTON:
             args += "dalton_mass %d %f" % (self.dalton.get(), Ts)
         else:
             args += "otsu"
         self.runJob("xmipp_volume_segment", args)
     
     elif self.volumeOperation == OPERATION_POSTPROCESS:
         ImageHandler().convert(fnVol,self.maskFile)
         
     return [self.maskFile]
    def _pickMicrograph(self, mic, args):
        # Prepare mic folder and convert if needed
        micName = mic.getFileName()
        micDir = self._getTmpPath(pwutils.removeBaseExt(micName))
        pwutils.makePath(micDir)

        ih = ImageHandler()
        # If needed convert micrograph to mrc format, otherwise link it
        if pwutils.getExt(micName) != ".mrc":
            fnMicBase = pwutils.replaceBaseExt(micName, 'mrc')
            inputMic = os.path.join(micDir, fnMicBase)
            ih.convert(mic.getLocation(), inputMic)
        else:
            inputMic = os.path.join(micDir, os.path.basename(micName))
            pwutils.createLink(micName, inputMic)

        # Prepare environment
        from appion import Plugin
        Plugin.getEnviron()

        # Program to execute and it arguments
        program = "python2"
        outputFile = self._getExtraPath(pwutils.replaceBaseExt(
            inputMic, "txt"))

        args += " --image=%s --outfile=%s" % (inputMic, outputFile)

        dogpicker = Plugin.getHome("ApDogPicker.py")
        args = dogpicker + " " + args

        self.runJob(program, args)
Exemplo n.º 13
0
    def importTomogramsStep(self, pattern, samplingRate):
        """ Copy images matching the filename pattern
        Register other parameters.
        """
        self.info("Using pattern: '%s'" % pattern)

        # Create a Volume template object
        tomo = Tomogram()
        tomo.setSamplingRate(samplingRate)

        imgh = ImageHandler()

        tomoSet = self._createSetOfTomograms()
        tomoSet.setSamplingRate(samplingRate)

        self._parseAcquisitionData()
        for fileName, fileId in self.iterFiles():
            x, y, z, n = imgh.getDimensions(fileName)
            if fileName.endswith('.mrc') or fileName.endswith('.map'):
                fileName += ':mrc'
                if z == 1 and n != 1:
                    zDim = n
                    n = 1
                else:
                    zDim = z
            else:
                zDim = z

            origin = Transform()

            if self.setOrigCoord.get():
                origin.setShiftsTuple(self._getOrigCoord())
            else:
                origin.setShifts(x / -2. * samplingRate,
                                 y / -2. * samplingRate,
                                 zDim / -2. * samplingRate)

            tomo.setOrigin(origin)  # read origin from form

            newFileName = _getUniqueFileName(self.getPattern(),
                                             fileName.split(':')[0])
            tsId = removeExt(newFileName)
            tomo.setTsId(tsId)

            if fileName.endswith(':mrc'):
                fileName = fileName[:-4]
            createAbsLink(fileName, abspath(self._getExtraPath(newFileName)))
            tomo.setAcquisition(self._extractAcquisitionParameters(fileName))

            if n == 1:  # One volume per file
                tomo.cleanObjId()
                tomo.setFileName(self._getExtraPath(newFileName))
                tomoSet.append(tomo)
            else:  # A stack of volumes per file (not common)
                for index in range(1, n + 1):
                    tomo.cleanObjId()
                    tomo.setLocation(index, self._getExtraPath(newFileName))
                    tomoSet.append(tomo)

        self._defineOutputs(outputTomograms=tomoSet)
Exemplo n.º 14
0
    def applyAlignmentStep(self, tsObjId):
        ts = self.inputSetOfTiltSeries.get()[tsObjId]
        tsId = ts.getTsId()
        extraPrefix = self._getExtraPath(tsId)
        path.makePath(extraPrefix)
        outputTsFileName = os.path.join(extraPrefix, "%s.mrc" % tsId)

        ts.applyTransform(outputTsFileName)

        outputInterpolatedSetOfTiltSeries = self.getOutputInterpolatedSetOfTiltSeries()

        newTs = tomoObj.TiltSeries(tsId=tsId)
        newTs.copyInfo(ts)
        outputInterpolatedSetOfTiltSeries.append(newTs)

        for index, tiltImage in enumerate(ts):
            newTi = tomoObj.TiltImage()
            newTi.copyInfo(tiltImage, copyId=True)
            newTi.setLocation(index + 1, outputTsFileName)
            newTs.append(newTi)

        ih = ImageHandler()
        x, y, z, _ = ih.getDimensions(newTs.getFirstItem().getFileName())
        newTs.setDim((x, y, z))
        newTs.write()

        outputInterpolatedSetOfTiltSeries.update(newTs)
        outputInterpolatedSetOfTiltSeries.updateDim()
        outputInterpolatedSetOfTiltSeries.write()
        self._store()
Exemplo n.º 15
0
 def _resizeVolume(self, volFn):
     """ Resize input volume if not of the same size of referenceVol """
     refDim = self.referenceVolume.get().getXDim()
     volDim = ImageHandler().getDimensions(volFn)
     if refDim != volDim:
         self.runJob('xmipp_image_resize',
                     "-i %s --dim %d" % (volFn, refDim))
Exemplo n.º 16
0
    def importMaskStep(self, path, samplingRate):
        """ Copy mask from maskPath.
        """
        self.info("Using mask path: '%s'" % path)

        # Copy the image file into the project
        dst = self._getExtraPath(basename(path))
        dst, cleaned = cleanFileName(dst)
        pwutils.copyFile(path, dst)

        # Retrieve image dimensions
        imgh = ImageHandler()
        _, _, z, n = imgh.getDimensions(dst)

        # Create a 2D or 3D Mask, consider the case of n>1
        # as the case of some volume maps in mrc format
        if z > 1 or n > 1:
            mask = VolumeMask()
        else:
            mask = Mask()

        mask.setFileName(dst)
        mask.setSamplingRate(samplingRate)

        self._defineOutputs(**{self._possibleOutputs.outputMask.name: mask})
Exemplo n.º 17
0
def getTomoSetFromStar(prot, starFile):
    samplingRate = prot.pixelSize.get()
    imgh = ImageHandler()
    tomoTable = Table()
    tomoTable.read(starFile)
    tomoList = [row.get(TOMO_NAME, FILE_NOT_FOUND) for row in tomoTable]
    prot.tomoList = List(tomoList)
    tomoNamesUnique = list(set(tomoList))

    # Create a Volume template object
    tomo = Tomogram()
    tomo.setSamplingRate(samplingRate)
    for fileName in tomoNamesUnique:
        x, y, z, n = imgh.getDimensions(fileName)
        if fileName.endswith('.mrc') or fileName.endswith('.map'):
            if z == 1 and n != 1:
                zDim = n
                n = 1
            else:
                zDim = z
        else:
            zDim = z
        origin = Transform()
        origin.setShifts(x / -2. * samplingRate,
                         y / -2. * samplingRate,
                         zDim / -2. * samplingRate)

        tomo.setOrigin(origin)  # read origin from form

        for index in range(1, n + 1):
            tomo.cleanObjId()
            tomo.setLocation(index, fileName)
            tomo.setAcquisition(TomoAcquisition(**prot.acquisitionParams))
            prot.tomoSet.append(tomo)
    def maskVolume(self, volFn, maskFn, index, halfString):
        ih = ImageHandler()

        # Check if there is a mask if not then use a spherical mask
        if maskFn is None:
            # Compute sphere radius and make a spherical mask
            maskFn = self._getFileName('mask', index + 1)
            volSize = ih.getDimensions(volFn)[0]
            radius = volSize / 2 - 1
            emlib.createEmptyFile(maskFn, volSize, volSize, volSize)
            program = "xmipp_transform_mask"
            args = "-i %s --mask circular %d --create_mask %s " % (
                maskFn, -1 * radius, maskFn)
            self.runJob(program, args)
        else:
            putils.copyFile(maskFn, self._getFileName('mask', index + 1))
            maskFn = self._getFileName('mask', index + 1)

        # Read the volume if it is provided
        if volFn.endswith(".mrc"):
            volFn = volFn + ":mrc"
        # Apply mask to the volume
        volMasked = self._getFileName('volume', 'masked', index + 1,
                                      halfString)
        program = 'xmipp_image_operate'
        args = '-i %s --mult %s -o %s' % (volFn, maskFn, volMasked)
        self.runJob(program, args)
Exemplo n.º 19
0
def main():
    # Get arguments.
    args = get_parser().parse_args()

    setObj = EMSet(filename=args.setFile)
    firstItem = setObj.getFirstItem()
    root = pwutils.findRootFrom(args.setFile, firstItem.getFileName())
    print("ROOT: ", root)

    if args.output_text:
        with open(args.output, 'w') as f:
            for movie in setObj:
                f.write('%s\n' % movie.getFileName())
    elif args.print:
        for item in setObj:
            print(item.getFileName())
    elif args.copy:
        for item in setObj:
            fn = os.path.join(root, item.getFileName())
            print('Copying %s to %s' % (fn, args.output))
            pwutils.copyFile(fn, args.output)

    elif args.check_dims:
        from pwem.emlib.image import ImageHandler
        ih = ImageHandler()

        counter = {}

        for item in setObj:
            fn = os.path.join(root, item.getFileName())
            dims = ih.getDimensions(fn)
            counter[dims] = 1 if dims not in counter else counter[dims] + 1
            print('%s: %s' % (os.path.basename(fn), dims))

        pwutils.prettyDict(counter)
    def createOutputStep(self):
        particles = self.inputParticles.get()

        # Generate the SetOfAlignmet
        alignedSet = self._createSetOfParticles()
        alignedSet.copyInfo(particles)

        inputMd = self._getPath('aligned_particles.xmd')
        alignedSet.copyItems(particles,
                             updateItemCallback=self._updateItem,
                             itemDataIterator=md.iterRows(inputMd, sortByLabel=md.MDL_ITEM_ID))
        # Remove alignment 2D
        alignedSet.setAlignment(ALIGN_NONE)

        # Define the output average

        avgFile = self._getExtraPath("average.xmp")

        imgh = ImageHandler()
        avgImage = imgh.computeAverage(alignedSet)

        avgImage.write(avgFile)

        avg = Particle()
        avg.setLocation(1, avgFile)
        avg.copyInfo(alignedSet)

        self._defineOutputs(outputAverage=avg)
        self._defineSourceRelation(self.inputParticles, avg)

        self._defineOutputs(outputParticles=alignedSet)
        self._defineSourceRelation(self.inputParticles, alignedSet)
Exemplo n.º 21
0
    def _prepareParams(self):
        args = " --noguiSplit %(half1)s %(half2)s"
        args += " --vxSize=%0.3f" % self.volumeHalf1.get().getSamplingRate()
        args += " --pVal=%(pVal)f --maxRes=%(maxRes)f --minRes=%(minRes)f"
        args += " --stepRes=%(stepRes)f"

        if self.show2D:
            args += " --vis2D"

        if self.applyMask:
            # convert mask to map/ccp4
            ih = ImageHandler()
            ih.convert(self.maskVolume.get().getLocation(),
                       self._getFileName('mask'))

            args += " --maskVol=%s" % os.path.basename(
                self._getFileName('mask'))

        params = {
            'half1': os.path.basename(self._getFileName('half1')),
            'half2': os.path.basename(self._getFileName('half2')),
            'pVal': self.pVal.get(),
            'maxRes': self.maxRes.get(),
            'minRes': self.minRes.get(),
            'stepRes': self.stepRes.get()
        }

        if self.useGpu:
            args += " --use_gpu=yes --set_gpu=%s" % self.gpuList.get()
            args += ' --lib_krnl_gpu="%s"' % resmap.Plugin.getGpuLib()

        if self.doBenchmarking:
            args += ' --doBenchMarking'

        return args % params
    def test_tomoProjectionOutputTiltSeriesDimension(self):
        ih = ImageHandler()
        outputDimensions = ih.getDimensions(
            self.protTomoProjection.outputProjectedSetOfTiltSeries.
            getFirstItem().getFirstItem().getFileName())

        self.assertTrue(outputDimensions == (256, 256, 61, 1))
    def createOutputStep(self, tsObjId):
        ts = self.inputSetOfTiltSeries.get()[tsObjId]
        tsId = ts.getTsId()
        extraPrefix = self._getExtraPath(tsId)

        outputSetOfTomograms = self.getOutputSetOfTomograms()

        newTomogram = Tomogram()
        newTomogram.setLocation(os.path.join(extraPrefix, ts.getFirstItem().parseFileName(extension=".mrc")))

        # Set tomogram origin
        ih = ImageHandler()
        xDim, yDim, zDim, _ = \
            ih.getDimensions(os.path.join(extraPrefix, ts.getFirstItem().parseFileName(extension=".mrc")))

        origin = Transform()
        sr = self.inputSetOfTiltSeries.get().getSamplingRate()
        origin.setShifts(xDim / -2. * sr,
                         yDim / -2. * sr,
                         zDim / -2 * sr)
        newTomogram.setOrigin(origin)

        # Set tomogram acquisition
        acquisition = TomoAcquisition()
        acquisition.setAngleMin(ts.getFirstItem().getTiltAngle())
        acquisition.setAngleMax(ts[ts.getSize()].getTiltAngle())
        acquisition.setStep(self.getAngleStepFromSeries(ts))
        newTomogram.setAcquisition(acquisition)

        outputSetOfTomograms.append(newTomogram)
        outputSetOfTomograms.update(newTomogram)
        outputSetOfTomograms.write()
        self._store()
Exemplo n.º 24
0
    def convertStep(self, volFn, volDim, volSr, minDim, maxSr, nVoli):
        Xdim = volDim
        Ts = volSr
        newTs = self.targetResolution.get() * 1.0 / 3.0
        newTs = max(maxSr, newTs)
        newXdim = Xdim * Ts / newTs
        newRmax = self.Rmax.get() * Ts / newTs
        self.newRmax = min(newRmax, self.Rmax.get())
        fnOut = os.path.splitext(volFn)[0]
        fnOut = self._getExtraPath(
            os.path.basename(fnOut + self.OUTPUT_SUFFIX % nVoli))

        ih = ImageHandler()
        volFn = volFn if getExt(volFn) == '.vol' else volFn + ':mrc'
        if Xdim != newXdim:
            self.runJob("xmipp_image_resize",
                        "-i %s -o %s --dim %d" % (volFn, fnOut, newXdim))

        else:
            ih.convert(volFn, fnOut)

        if newXdim > minDim:
            self.runJob(
                "xmipp_transform_window",
                " -i %s -o %s --crop %d" % (fnOut, fnOut, (newXdim - minDim)))
Exemplo n.º 25
0
    def lafterStep(self):
        halfmaps = self.inputVol.get().getHalfMaps().split(',')
        fn1 = halfmaps[0]
        fn2 = halfmaps[1]
        fn1mrc = self._getTmpPath('vol1.mrc')
        fn2mrc = self._getTmpPath('vol2.mrc')
        ih = ImageHandler()
        ih.convert(fn1, fn1mrc)
        ih.convert(fn2, fn2mrc)

        args = '--v1 tmp/vol1.mrc --v2 tmp/vol2.mrc'
        if self.maskType.get() == 0:
            fnMmrc = self._getTmpPath('mask.mrc')
            ih.convert(self.volumeMask.get().getFileName(), fnMmrc)
            args += " --mask tmp/mask.mrc"
        else:
            if self.volumeRadius.get() > 0:
                args += " --particle_diameter %d" % (2 *
                                                     self.volumeRadius.get())
            else:
                args += " --particle_diameter %d" % (
                    self.inputVol.get().getDim()[0])
        if self.sharp.get():
            args += " --sharp"
        args += " --fsc %f" % self.fscCutoff.get()
        if self.downsample.get():
            args += " --downsample"
        if self.overfitting.get():
            args += " --overfitting"
        self.runJob('lafter', args, cwd=self._getPath())
    def _runNormalize(self, stack, frames):
        import math
        program = "xmipp_transform_normalize"
        args = "-i %(stack)s "
        normType = self.normType.get()
        bgRadius = self.backRadius.get()

        size, _, _, _ = ImageHandler().getDimensions(stack)
        if bgRadius <= 0:
            bgRadius = int(size / 2)

        if normType == "OldXmipp":
            args += "--method OldXmipp"
        elif normType == "NewXmipp":
            args += "--method NewXmipp --background circle %(bgRadius)d"
        else:
            args += "--method Ramp --background circle %(bgRadius)d"
        self.runJob(program, args % locals())

        # The background's stddev of the movie
        # particles must be equal to sqrt(NoOfFrames)
        # for the background's stddev of the
        # average particle be equal to 1.
        val = math.sqrt(frames)
        opArgs = "-i %s --mult %f" % (stack, val)
        self.runJob("xmipp_image_operate", opArgs)
Exemplo n.º 27
0
    def _validateImages(self):
        errors = []
        ih = ImageHandler()

        for imgFn, _ in self.iterFiles():

            if isdir(imgFn):
                errors.append("Folders can not be selected.")
                errors.append('  %s' % imgFn)
            else:
                # Check if images are correct by reading the header of the
                # imported files:
                # Exceptions:
                #  - Compressed movies (bz2 or tbz extensions)
                #  - Importing in streaming, since files may be incomplete
                #  - Bad characters in path [':' ,'%', '#']
                if (not self.dataStreaming and
                        not (imgFn.endswith('bz2') or imgFn.endswith('tbz') or
                             imgFn.endswith('eer') or ih.isImageFile(imgFn))):
                    if not errors:  # if empty add the first line
                        errors.append("Error reading the following images:")
                    errors.append('  %s' % imgFn)
                    errors += ProtImportImages.validatePath(imgFn)

            break  # validate just first image

        return errors
Exemplo n.º 28
0
 def _beforePreview(self):
     ImagePreviewDialog._beforePreview(self)
     self.lastObj = None
     self.rightPreviewLabel = "Filtered particle"
     self.message = "Filtering particle..."
     self.previewLabel = "Particle"
     self.rightImage = ImageHandler()._img
Exemplo n.º 29
0
    def convertInputStep(self):
        fnInputVol = self._getFileName('fnInputVol')
        fnRefVol = self._getFileName('fnRefVol')

        XdimI = self.inputVolume.get().getDim()[0]
        TsI = self.inputVolume.get().getSamplingRate()
        XdimR = self.refVolume.get().getDim()[0]
        TsR = self.refVolume.get().getSamplingRate()
        self.newTs = self.targetResolution.get() * 1.0 / 3.0
        self.newTs = max(TsI, TsR, self.newTs)
        newXdimI = XdimI * TsI / self.newTs
        newXdimR = XdimR * TsR / self.newTs
        newRmax = self.Rmax.get() * TsI / self.newTs
        self.newXdim = min(newXdimI, newXdimR)
        self.newRmax = min(newRmax, self.Rmax.get())

        ih = ImageHandler()
        ih.convert(self.inputVolume.get(), fnInputVol)
        if XdimI != newXdimI:
            self.runJob("xmipp_image_resize",
                        "-i %s --dim %d" % (fnInputVol, newXdimI))
        if newXdimI > self.newXdim:
            self.runJob(
                "xmipp_transform_window",
                " -i %s --crop %d" % (fnInputVol, (newXdimI - self.newXdim)))

        ih.convert(self.refVolume.get(), fnRefVol)

        if XdimR != newXdimR:
            self.runJob("xmipp_image_resize",
                        "-i %s --dim %d" % (fnRefVol, newXdimR))
        if newXdimR > self.newXdim:
            self.runJob(
                "xmipp_transform_window",
                " -i %s --crop %d" % (fnRefVol, (newXdimR - self.newXdim)))
Exemplo n.º 30
0
    def _show3DFSCcolorSlices(self, param=None):
        """
        It opens 4 colores slices of the 3DFSC
        """
        errors = []
        if self.protocol.estimate3DFSC:
            img = ImageHandler().read(
                self.protocol._getExtraPath(OUTPUT_3DFSC))
            imgData = img.getData()

            xplotter = XmippPlotter(x=2,
                                    y=2,
                                    mainTitle="3DFSC Color Slices"
                                    "along %s-axis." % self._getAxis())
            # The slices to be shown are close to the center. Volume size is divided in
            # 9 segments, the fouth central ones are selected i.e. 3,4,5,6
            for i in range(3, 7):
                sliceNumber = self.getSlice(i, imgData)
                a = xplotter.createSubPlot("Slice %s" % (sliceNumber + 1), '',
                                           '')
                matrix = self.getSliceImage(imgData, sliceNumber,
                                            self._getAxis())
                plot = xplotter.plotMatrix(a,
                                           matrix,
                                           0,
                                           1,
                                           cmap=self.getColorMap(),
                                           interpolation="nearest")
            xplotter.getColorBar(plot)
            return [xplotter]
        else:
            errors.append("The 3dFSC estimation of the 3dFSC was not selected"
                          "in the protocol form.")
            return errors