def uploadImageToDataset(session, services, pixelsType, localImage, dataset=None, description="", imageName=None):
    
    """
    Uploads a local Spider image to an OMERO dataset. Same function exists in spider2omero.py.
    
    @param services     Map of OMERO services
    @param pixelsType   The OMERO PixelsType object for new image.
    @param imageName    The local image path/name. Also used for new image name. 
    @param dataset      Dataset to put images in, if specified. omero.model.Dataset
    """
    
    renderingEngine = services["renderingEngine"]
    queryService = services["queryService"]
    pixelsService = services["pixelsService"]
    rawPixelStore = services["rawPixelStore"]
    updateService = services["updateService"]
    rawFileStore = services["rawFileStore"]

    
    namespace = omero.constants.namespaces.NSCOMPANIONFILE 
    fileName = omero.constants.annotation.file.ORIGINALMETADATA
    
    if imageName == None:  imageName = localImage
    print "Importing image: %s" % imageName
    plane2D = spider2array(localImage)
    plane2Dlist = [plane2D]        # single plane image
    
    image = scriptUtil.createNewImage(session, plane2Dlist, imageName, description, dataset)
    
    # header is a list of values corresponding to attributes 
    header = getSpiderHeader(localImage)
    
    # if we know the pixel size, set it in the new image
    if len(header) >= 38:
        physicalSizeX = header[38]
        physicalSizeY = header[38]
        pixels = image.getPrimaryPixels()
        pixels.setPhysicalSizeX(rdouble(physicalSizeX))
        pixels.setPhysicalSizeY(rdouble(physicalSizeY))
        updateService.saveObject(pixels)
    
    # make a temp text file. 
    f = open(fileName, 'w')
    f.write("[GlobalMetadata]\n")

    # now add image attributes as "Original Metadata", sorted by key. 
    for i, h in enumerate(header):
        if i in spiderHeaderMap:
            f.write("%s=%s\n" % (spiderHeaderMap[i], h))
            
    f.close()

    scriptUtil.uploadAndAttachFile(queryService, updateService, rawFileStore, image, fileName, "text/plain", None, namespace)
    # delete temp file
    os.remove(fileName)
    return image
Beispiel #2
0
def volume2imagelist(filename):
    " converts a Spider volume into a list of PIL images"
    imlist = []
    V = spider2array(filename)
    x = V.flat  # flatten to 1D array to get extrema
    amax = max(x)
    amin = min(x)
    m = 255.0 / (amax - amin)
    b = -m * amin
    N = ((m * V) + b).astype(Numeric.UnsignedInt8)  # mV+b returns an array

    zsize, ysize, xsize = N.shape
    for z in range(zsize):
        im = array2image(N[z])
        im.info['filename'] = str(z)
        imlist.append(im)
    return imlist
def getPixelsType(queryService, imageName):
    """
    Get the OMERO pixelsType object appropriate for the image named. 
    """
    plane2D = spider2array(imageName)
    pType = plane2D.dtype.name
    pixelsType = queryService.findByQuery("from PixelsType as p where p.value='%s'" % pType, None) # omero::model::PixelsType
    
    if pixelsType == None and pType.startswith("float"):
        # try 'float'
        pixelsType = queryService.findByQuery("from PixelsType as p where p.value='%s'" % "float", None) # omero::model::PixelsType
    if pixelsType == None:
        print "Unknown pixels type for: " % pType
        return
    else:
        print "Using pixels type ", pixelsType.getValue().getValue()
    return pixelsType
 def visit(arg, dirname, names):
     rootpath = arg
     datasetName = dirname.replace(rootpath, "")
     pixelsType = None   # set by first image result - assume all the same
     dataset = None
     for n in names:
         fullname = os.path.join(dirname, n)
         imageArray = None
         try:
             # attempt to read pixel data. Only way to tell if this is a Spider image? 
             imageArray = spider2array(fullname)
         except:
             print "."
         if imageArray != None:
             #print "   " , fullname, " IS an image"
             if pixelsType == None:   
                 pixelsType = getPixelsType(queryService, imageArray)
             if dataset == None:     
                 print "Dataset" , datasetName
                 dataset = createDataset(updateService, project, datasetName)
             uploadImageToDataset(services, pixelsType, imageArray, fullname, dataset)
Beispiel #5
0
def loadImageSeries(filelist=None, parent=None, byte=1, istart=None, iend=-1,
                    verbose=1, DISPLAY_ALL=None):
    " create a list of PIL images from SPIDER files "
    if filelist == None or len(filelist) < 1:
        return []

    # see if the first filelist argument is a flag or range (overrides istart?)

    firstarg = filelist[0]
    if firstarg == '-a' or firstarg == '-1':
        if verbose: print "displaying all..."
        DISPLAY_ALL = 1
        filelist = filelist[1:]
        istart=1; iend=len(filelist)
    elif isNumberRange(firstarg):
        istart,iend = isNumberRange(firstarg)
        DISPLAY_ALL = 0
        filelist = filelist[1:]

    # check the first file, to see if exists, is stack, or is volume
        
    Nfiles = len(filelist)
    if Nfiles < 1: return []
    file = filelist[0]
    if not os.path.exists(file):
        print "unable to find %s" % file
        return []

    info = spiderInfo(file)
    if info:
        type, size = info[0], info[1]
    else:
        type = 'non-spider'
        try:
            im = Image.open(file)
            size = im.size
        except:
            size = (100,100) # placeholder

    if type == "volume":
        Nimages = size[2]
    elif type == "stack":
        hdr = getSpiderHeader(filelist[0])
        Nimages = int(hdr[26])
    else:
        Nimages = Nfiles
    if DISPLAY_ALL == 1:
        istart = 1
        iend = Nimages

    # IF start,end not set by first argument in filelist, see if they will
    # fit onscreen. Get number of images; if too many to fit, get start, end images.
    if DISPLAY_ALL == None:
        if istart == None:
            if verbose: print "computing if images will fit on screen..."
            res = getImageRange(Nimages, size, parent)
            if not res:
                return []
            istart, iend = res
            
    if istart==0: istart=1  # use Spider indexing

    # Load the SPIDER files as PIL images
    imglist = []

    # ----------------------------------------------
    if type == "image" or type == "non-spider":
        newlist = filelist[istart-1:iend]    # SHOULD USE FILE NUMBERS??!!!
        for file in newlist:
            if not os.path.exists(file):
                print "Unable to find %s" % file
                continue
            try:
                im = Image.open(file)
                if byte and im.format == 'SPIDER':
                    im = im.convert2byte()
                else:
                    im = Image.open(file)
                im.info['filename'] = os.path.basename(file)
                imglist.append(im)
            except:
               print "Unable to load %s" % file

    # ----------------------------------------------
    elif type == "stack": 

        basename = os.path.basename(file)
        try:
            im = Image.open(file)
            ni = im.nimages
            s1 = istart - 1 # go from SPIDER 1 to Python 0
            if iend > s1 and iend < ni:
                s2 = iend   # don't subtract 1, cos used by range()
            else:
                s2 = ni
            for i in range(s1,s2):   #ni):
                im.seek(i)
                im.info['filename'] = "%s@%d" % (basename[:-4], i+1)
                #im.info['filename'] = str(i+1)
                if byte:
                    imglist.append(im.convert2byte())
                else:
                    imglist.append(im)
        except:
           print "Error trying to load SPIDER stack " + file
           return []

    # ----------------------------------------------
    elif type == "volume":
        
        V = spider2array(file)  # V is a 3D numpy array
        N = V[istart-1:iend]
        if byte:
            V = N
            amax = max(V.flat) # flatten to 1D array to get extrema
            amin = min(V.flat)
            if amax == amin:
                print "*** Error: volume slices contain constant data"
                return []
            m = 255.0 / (amax-amin)
            b = -m * amin
            if _HAS_NUMPY_:
                N = ((m*V)+b).astype(numpy.uint8) # mV+b returns an array
            else:
                N = ((m*V)+b).astype(Numeric.UnsignedInt8) 
        
        zsize, ysize, xsize = N.shape
        for z in range(zsize):
            im = array2image(N[z])
            im.info['filename'] = str(z+1 + istart-1)
            imglist.append(im)

    return imglist
Beispiel #6
0
def loadImageSeries(filelist=None, parent=None, byte=1, istart=None, iend=-1,
                    verbose=1, DISPLAY_ALL=None):
    " create a list of PIL images from SPIDER files "
    
    print "Hunting " 
    
    if filelist == None or len(filelist) < 1:
        return []

    # see if the first filelist argument is a flag or range (overrides istart?)

    firstarg = filelist[0]
    if firstarg == '-a' or firstarg == '-1':
        if verbose: print "displaying all..."
        DISPLAY_ALL = 1
        filelist = filelist[1:]
        istart=1; iend=len(filelist)
    elif isNumberRange(firstarg):
        istart,iend = isNumberRange(firstarg)
        DISPLAY_ALL = 0
        filelist = filelist[1:]

    # check the first file, to see if exists, is stack, or is volume
        
    Nfiles = len(filelist)
    if Nfiles < 1: return []
    file = filelist[0]
    if not os.path.exists(file):
        print "unable to find %s" % file
        return []

    print "Found %s" % file
    
    
    
    info = spiderInfo(file)
    if info:
        type, size = info[0], info[1]
    else:
        type = 'non-spider'
        try:
            im = Image.open(file)
            size = im.size
        except:
            size = (100,100) # placeholder

    if type == "volume":
        Nimages = size[2]
    elif type == "stack":
        hdr = getSpiderHeader(filelist[0])
        Nimages = int(hdr[26])
    else:
        Nimages = Nfiles
    if DISPLAY_ALL == 1:
        istart = 1
        iend = Nimages

    # IF start,end not set by first argument in filelist, see if they will
    # fit onscreen. Get number of images; if too many to fit, get start, end images.
    if DISPLAY_ALL == None:
        if istart == None:
            if verbose: print "computing if images will fit on screen..."
            res = getImageRange(Nimages, size, parent)
            if not res:
                return []
            istart, iend = res
            
    if istart==0: istart=1  # use Spider indexing

    # Load the SPIDER files as PIL images
    imglist = []

    # ----------------------------------------------
    if type == "image" or type == "non-spider":
        newlist = filelist[istart-1:iend]    # SHOULD USE FILE NUMBERS??!!!
        for file in newlist:
            if not os.path.exists(file):
                print "Unable to find %s" % file
                continue
            try:
                im = Image.open(file)
                if byte and im.format == 'SPIDER':
                    im = im.convert2byte()
                else:
                    im = Image.open(file)
                im.info['filename'] = os.path.basename(file)
                imglist.append(im)
            except:
               print "Unable to sleep:: %s" % file
               print "Unable to load:: %s" % file

    # ----------------------------------------------
    elif type == "stack": 

        basename = os.path.basename(file)
        try:
            im = Image.open(file)
            ni = im.nimages
            s1 = istart - 1 # go from SPIDER 1 to Python 0
            if iend > s1 and iend < ni:
                s2 = iend   # don't subtract 1, cos used by range()
            else:
                s2 = ni
            for i in range(s1,s2):   #ni):
                im.seek(i)
                im.info['filename'] = "%s@%d" % (basename[:-4], i+1)
                #im.info['filename'] = str(i+1)
                if byte:
                    imglist.append(im.convert2byte())
                else:
                    imglist.append(im)
        except:
           print "Error trying to load SPIDER stack " + file
           return []

    # ----------------------------------------------
    elif type == "volume":
        
        V = spider2array(file)  # V is a 3D numpy array
        N = V[istart-1:iend]
        if byte:
            V = N
            amax = max(V.flat) # flatten to 1D array to get extrema
            amin = min(V.flat)
            if amax == amin:
                print "*** Error: volume slices contain constant data"
                return []
            m = 255.0 / (amax-amin)
            b = -m * amin
            if _HAS_NUMPY_:
                N = ((m*V)+b).astype(numpy.uint8) # mV+b returns an array
            else:
                N = ((m*V)+b).astype(Numeric.UnsignedInt8) 
        
        zsize, ysize, xsize = N.shape
        for z in range(zsize):
            im = array2image(N[z])
            im.info['filename'] = str(z+1 + istart-1)
            imglist.append(im)

    return imglist