コード例 #1
0
def readImageVolume(request, path, convert, dataType, reslice, axis, getStats):
    #_newPath = path
    _stats = None

    img = xmipp.Image()
    imgFn = os.path.join(request.session['projectPath'], path)

    if not convert and not reslice and not getStats:
        #         img.read(str(imgFn), xmipp.HEADER)
        pass
    else:
        img.read(str(imgFn))

    if getStats:
        _stats = img.computeStats()

    if convert:
        img.convert2DataType(dataType, xmipp.CW_ADJUST)

    if reslice:
        if axis != xmipp.VIEW_Z_NEG:
            img.reslice(axis)
    _newPath = getTmpVolumePath(imgFn.replace(':mrc', ''))
    if (convert and not os.path.exists(_newPath)) or reslice:
        img.write(_newPath)
    return _newPath, _stats
コード例 #2
0
    def normalize(self, what):
        # Get overall minimum and maximum
        V = xmipp.Image()
        minAll = 1e38
        maxAll = -1e38
        for prot in self.inputRuns:
            protId = prot.get().getObjId()
            protDir = prot.get()._getPath('')
            fnVol = os.path.join(protDir, "extra", "result_%s.vol" % what)
            V.read(fnVol)
            _, _, minVal, maxVal = V.computeStats()
            minAll = min(minAll, minVal)
            maxAll = max(maxAll, maxVal)

        # Write the Chimera file
        for prot in self.inputRuns:
            protId = prot.get().getObjId()
            protDir = prot.get()._getPath('')
            fnRoot = os.path.relpath(os.path.join(protDir, "extra", "result"),
                                     self._getPath(''))
            scriptFile = self._getPath('%d_result_%s_chimera.cmd' %
                                       (protId, what))
            fhCmd = open(scriptFile, 'w')
            fhCmd.write("open %s\n" % (fnRoot + "_final.vol"))
            fhCmd.write("open %s\n" % (fnRoot + "_%s.vol" % what))
            fhCmd.write("vol #1 hide\n")
            fhCmd.write(
                "scolor #0 volume #1 cmap rainbow cmapRange %f,%f reverseColors True\n"
                % (minAll, maxAll))
            fhCmd.close()
コード例 #3
0
ファイル: gui.py プロジェクト: mcgill-femr/scipion
def getImageFromPath(imagePath):
    """ Read an image using Xmipp, convert to PIL
    and then return as expected by Tk.
    """
    import xmipp
    img = xmipp.Image(imagePath)
    imgPIL = getPILImage(img)
    from PIL import ImageTk
    imgTk = ImageTk.PhotoImage(imgPIL)

    return imgTk
コード例 #4
0
def convertVolume(request, path):
    imgFn = os.path.join(request.session['projectPath'], path)
    imgConvertedFn = getTmpVolumePath(imgFn.replace(':mrc', ''))
    # For rendering volume slices over the web, PIL need that
    # the volume is stored with a specific datatype
    # So, we write a temporarly volume the first time
    if not os.path.exists(imgConvertedFn):
        img = xmipp.Image()
        img.read(str(imgFn))
        img.convert2DataType(xmipp.DT_UCHAR, xmipp.CW_ADJUST)
        img.write(imgConvertedFn)
    return imgConvertedFn
コード例 #5
0
    def createRandomMicAtep(self, mic):
        from pyworkflow.em.packages.xmipp3 import getEnviron

        # create image
        img = xmipp.Image()
        img.setDataType(xmipp.DT_FLOAT)
        img.resize(self.xDim, self.yDim)
        img.initRandom(0., 1., xmipp.XMIPP_RND_UNIFORM)
        baseFn = self._getExtraPath(self._singleImageFn)
        img.write(baseFn)

        md1 = xmipp.MetaData()
        md1.setColumnFormat(False)
        idctf = md1.addObject()

        baseFnCtf = self._getTmpPath("ctf_%d.param" % mic)
        baseFnImageCTF = self._getExtraPath("imageCTF_%d.xmp" % mic)

        md1.setValue(xmipp.MDL_CTF_SAMPLING_RATE, 1., idctf)
        md1.setValue(xmipp.MDL_CTF_VOLTAGE, 200., idctf)
        defocus = 20000 + 10000 * random.random()
        udefocus = defocus + 1000 * random.random()
        vdefocus = defocus + 1000 * random.random()
        if udefocus < vdefocus:
            aux = vdefocus
            vdefocus = udefocus
            udefocus = aux
        md1.setValue(xmipp.MDL_CTF_DEFOCUSU, udefocus, idctf)
        md1.setValue(xmipp.MDL_CTF_DEFOCUSV, vdefocus, idctf)
        md1.setValue(xmipp.MDL_CTF_DEFOCUS_ANGLE, 180.0 * random.random(),
                     idctf)
        md1.setValue(xmipp.MDL_CTF_CS, 2., idctf)
        md1.setValue(xmipp.MDL_CTF_Q0, 0.07, idctf)
        md1.setValue(xmipp.MDL_CTF_K, 1., idctf)

        md1.write(baseFnCtf)

        # apply ctf
        args = " -i %s" % baseFn
        args += " -o %s" % baseFnImageCTF
        args += " -f ctf %s" % baseFnCtf
        args += " --sampling %f" % self.samplingRate
        self.runJob("xmipp_transform_filter", args, env=getEnviron())
        self.dictObj[baseFnImageCTF] = True
        time.sleep(self.creationInterval.get())
コード例 #6
0
def get_slice(request):
    sliceNo = None
    imagePath = request.GET.get('image')
    imageDim = request.GET.get('dim', 150)
    mirrorY = 'mirrorY' in request.GET
    #    applyTransformMatrix = 'applyTransformMatrix' in request.GET
    #    onlyApplyShifts = request.GET.get('onlyApplyShifts',False)
    #    wrap = request.GET.get('wrap',False)
    #    transformMatrix = request.GET.get('transformMatrix',None)

    # This validations not works for volumes into a stack
    if '__slice__' in imagePath:
        parts = imagePath.split('__slice__', 1)
        sliceNo = int(parts[0])
        imagePath = parts[1]

#     if '@' in imagePath:
#             parts = imagePath.split('@')
#             imageNo = parts[0]
#             imagePath = parts[1]
    imagePath = convertVolume(request, imagePath)
    imgXmipp = xmipp.Image()
    if sliceNo is None:
        imgXmipp.readPreview(imagePath, int(imageDim))
    else:
        imgXmipp.readPreview(imagePath, int(imageDim), sliceNo)

#        if applyTransformMatrix and transformMatrix != None:
#            imgXmipp.applyTransforMatScipion(transformMatrix, onlyApplyShifts, wrap)
#
    if mirrorY:
        imgXmipp.mirrorY()

    # from PIL import Image


#   img = getPILImage(imgXmipp, None, False)
    img = getPILImage(imgXmipp, normalize=False)
    response = HttpResponse(mimetype="image/png")

    if img.mode != 'RGB':
        img = img.convert('RGB')
    img.save(response, "PNG")

    return response
コード例 #7
0
ファイル: matplotlib_image.py プロジェクト: totalcos/scipion
    def __init__(self, filename=None, dim=256, dpi=96, image=None, label=None):
        pwgui.Window.__init__(self, minsize=None)
        if image is None:
            image = xmipp.Image()
            if dim is None:
                image.read(filename)
                dim, _, _, _ = image.getDimensions()
            else:
                image.readPreview(filename, dim)

        dpi = min(dpi, dim)

        self.imagePreview = ImagePreview(self.root, dim, dpi, label, 0)

        if image is None and filename is None:
            raise Exception(
                "ImageWindow: image or filename should be provided.")

        if filename is None:
            filename = "No filename"

        self.updateImage(image)

        self.imagePreview.grid(row=0, column=0)
コード例 #8
0
def get_image(request):
    imageNo = None

    # TO DO: Change the way to obtain the separate string of the imagePath
    imagePath = request.GET.get('image')
    imageDim = request.GET.get('dim', 150)

    # This prefix can be passed to avoid that image is not refresh when cached by browser (name does not change)
    prefix = request.GET.get('prefix', "")

    mirrorY = 'mirrorY' in request.GET

    applyTransformMatrix = 'applyTransformMatrix' in request.GET
    onlyShifts = 'onlyShifts' in request.GET
    wrap = 'wrap' in request.GET

    matrix = request.GET.get('matrix', None)

    try:
        # PAJM: Como vamos a gestionar lsa imagen
        if imagePath.endswith('png') or imagePath.endswith('gif'):
            imagePathTmp = os.path.join(request.session['projectPath'],
                                        prefix + imagePath)
            img = getImage(imagePathTmp, tkImage=False)
        else:
            if '@' in imagePath:
                parts = imagePath.split('@')
                imageNo = parts[0]
                imagePath = parts[1]

            if 'projectPath' in request.session:
                imagePathTmp = os.path.join(request.session['projectPath'],
                                            imagePath)
                if not os.path.isfile(imagePathTmp):
                    raise Exception('should not use getInputPath')
                    #imagePath = getInputPath('showj', imagePath)

            if imageNo:
                imagePath = '%s@%s' % (imageNo, imagePath)

            imgXmipp = xmipp.Image()
            imgXmipp.readPreview(imagePath, int(imageDim))

            #===================================================================
            # Transform Matrix
            if applyTransformMatrix:
                takarras = [
                    tMatrix[0][0], tMatrix[0][1], tMatrix[0][2],
                    x if x != None else 0, tMatrix[1][0], tMatrix[1][1],
                    tMatrix[1][2], y if y != None else 0, tMatrix[2][0],
                    tMatrix[2][1], tMatrix[2][2], z if z != None else 0
                ]
                #               imgXmipp.applyTransforMatScipion(matrix, onlyShifts, wrap)
                imgXmipp.applyTransforMatScipion(takarras, onlyShifts, wrap)
            #===================================================================

            #===================================================================
            # Invert Y axis
            if mirrorY:
                imgXmipp.mirrorY()
            #===================================================================

            #TO DO: PSD FIX
            if imagePath.endswith('.psd'):
                imgXmipp.convertPSD()

            # from PIL import Image
            img = getPILImage(imgXmipp, None)
    except Exception:
        img = getImage(findResource(getResourceIcon("no_image")),
                       tkImage=False)

    response = HttpResponse(mimetype="image/png")
    img.save(response, "PNG")
    return response
コード例 #9
0
    def testCtfdiscrepancyWorkflow(self):
        # create one micrograph set
        fnMicSet = self.proj.getTmpPath("mics.sqlite")
        fnMic = self.proj.getTmpPath("mic.mrc")
        mic = Micrograph()
        mic.setFileName(fnMic)
        micSet = SetOfMicrographs(filename=fnMicSet)

        # create two CTFsets
        fnCTF1 = self.proj.getTmpPath("ctf1.sqlite")
        fnCTF2 = self.proj.getTmpPath("ctf2.sqlite")
        ctfSet1 = SetOfCTF(filename=fnCTF1)
        ctfSet2 = SetOfCTF(filename=fnCTF2)

        # create one fake micrographs image
        projSize = 32
        img = xmipp.Image()
        img.setDataType(xmipp.DT_FLOAT)
        img.resize(projSize, projSize)
        img.write(fnMic)

        # fill the sets
        for i in range(1, 4):
            mic = Micrograph()
            mic.setFileName(fnMic)
            micSet.append(mic)

            defocusU = 1000 + 10 * i
            defocusV = 1000 + i
            defocusAngle = i * 10
            psdFile = "psd_1%04d" % i
            ctf = self._getCTFModel(defocusU, defocusV, defocusAngle, psdFile)
            ctf.setMicrograph(mic)
            ctfSet1.append(ctf)

            defocusU = 1000 + 20 * i
            defocusV = 1000 + i
            defocusAngle = i * 20
            psdFile = "psd_2%04d" % i
            ctf = self._getCTFModel(defocusU, defocusV, defocusAngle, psdFile)
            ctf.setMicrograph(mic)
            ctfSet2.append(ctf)
        ctfSet1.write()
        ctfSet2.write()
        micSet.write()

        # import micrograph set
        args = {
            'importFrom': ProtImportMicrographs.IMPORT_FROM_SCIPION,
            'sqliteFile': fnMicSet,
            'amplitudConstrast': 0.1,
            'sphericalAberration': 2.,
            'voltage': 100,
            'samplingRate': 2.1
        }

        protMicImport = self.newProtocol(ProtImportMicrographs, **args)
        protMicImport.setObjLabel('import micrographs from sqlite ')
        self.launchProtocol(protMicImport)

        # import ctfsets
        protCTF1 = \
            self.newProtocol(ProtImportCTF,
                             importFrom=ProtImportCTF.IMPORT_FROM_SCIPION,
                             filesPath=fnCTF1)
        protCTF2 = \
            self.newProtocol(ProtImportCTF,
                             importFrom=ProtImportCTF.IMPORT_FROM_SCIPION,
                             filesPath=fnCTF2)
        protCTF1.inputMicrographs.set(protMicImport.outputMicrographs)
        protCTF2.inputMicrographs.set(protMicImport.outputMicrographs)
        protCTF1.setObjLabel('import ctfs from scipion_1 ')
        protCTF2.setObjLabel('import ctfs from scipion_2 ')
        self.launchProtocol(protCTF1)
        self.launchProtocol(protCTF2)

        # launch CTF discrepancy protocol
        protCtfDiscrepancy = self.newProtocol(XmippProtCTFDiscrepancy)
        protCtfDiscrepancy.inputCTF1.set(protCTF1.outputCTF)
        protCtfDiscrepancy.inputCTF2.set(protCTF2.outputCTF)
        protCtfDiscrepancy.setObjLabel('ctf discrepancy')
        self.launchProtocol(protCtfDiscrepancy)
        ctf0 = protCtfDiscrepancy.outputCTF.getFirstItem()
        resolution = int(ctf0.getResolution())
        defocusU = int(ctf0.getDefocusU())
        self.assertEqual(resolution, 2)
        self.assertEqual(defocusU, 1010)