示例#1
0
def set_attributes(conn, parent_image, child):

    updateService = conn.getUpdateService()
    parent_pixels = parent_image.getPrimaryPixels()
    # note pixel sizes (if available) to set for the new images
    physicalSizeX = parent_pixels.physicalSizeX.getValue()
    physicalSizeY = parent_pixels.physicalSizeY.getValue()
    physicalSizeZ = parent_pixels.physicalSizeZ.getValue()

    child_image = conn.getObject("Image", child.getId())

    # Get the BlitzGateway wrapped pixels and unwrap it
    pixelsWrapper = child_image.getPrimaryPixels()
    child_pixels = pixelsWrapper._obj

    if physicalSizeX is not None:
        child_pixels.physicalSizeX.setValue(rdouble(physicalSizeX))

    if physicalSizeY is not None:
        child_pixels.physicalSizeY.setValue(rdouble(physicalSizeY))

    if physicalSizeZ is not None:
        child_pixels.physicalSizeZ.setValue(rdouble(physicalSizeZ))

    ptype = parent_pixels.getPixelsType().getValue()
    print "pixels type:", ptype

    pix_min = 0
    pix_max = 255

    if (ptype == 'uint16'):
        pix_min = 0.0
        pix_max = 65535.0

    colors = []
    print "Channel rendering settings:"
    for ch in parent_image.getChannels():
        if '405' in ch.getLabel():
            color = (0, 0, 255)
        if '488' in ch.getLabel():
            color = (0, 255, 0)
        if '561' in ch.getLabel():
            color = (255, 0, 0)
        if '640' in ch.getLabel():
            color = (255, 0, 255)
        alpha = 255
        colors.append(color + (alpha, ))

    child_pixelsId = pixelsWrapper.getId()
    for theC in range(child_image.getSizeC()):
        rgba = colors[theC]
        script_util.resetRenderingSettings(conn.createRenderingEngine(),
                                           child_pixelsId, theC, pix_min,
                                           pix_max, rgba)

    updateService.saveObject(child_pixels)
def set_attributes(conn,parent_image,child):
    
    updateService = conn.getUpdateService()
    parent_pixels = parent_image.getPrimaryPixels()
    # note pixel sizes (if available) to set for the new images
    physicalSizeX = parent_pixels.physicalSizeX.getValue()
    physicalSizeY = parent_pixels.physicalSizeY.getValue()
    physicalSizeZ = parent_pixels.physicalSizeZ.getValue()
    
    child_image = conn.getObject("Image", child.getId())
    
    # Get the BlitzGateway wrapped pixels and unwrap it
    pixelsWrapper = child_image.getPrimaryPixels()
    child_pixels = pixelsWrapper._obj
    
    if physicalSizeX is not None:
        child_pixels.physicalSizeX.setValue( rdouble(physicalSizeX) )
        
    if physicalSizeY is not None:
        child_pixels.physicalSizeY.setValue( rdouble(physicalSizeY) )
        
    if physicalSizeZ is not None:
        child_pixels.physicalSizeZ.setValue( rdouble(physicalSizeZ) )
        
    ptype = parent_pixels.getPixelsType().getValue()
    print "pixels type:",ptype
    
    pix_min = 0
    pix_max = 255
    
    if (ptype == 'uint16'):
        pix_min = 0.0
        pix_max = 65535.0
        
    colors = []
    print "Channel rendering settings:"
    for ch in parent_image.getChannels():
        if '405' in ch.getLabel():
            color = (0,0,255)
        if '488' in ch.getLabel():
            color = (0,255,0)
        if '561' in ch.getLabel():
            color = (255,0,0)
        if '640' in ch.getLabel():
            color = (255,0,255)
        alpha = 255
        colors.append(color + (alpha,))   
    
    child_pixelsId = pixelsWrapper.getId()
    for theC in range(child_image.getSizeC()):
        rgba = colors[theC]
        script_util.resetRenderingSettings(conn.createRenderingEngine(), 
                                          child_pixelsId, theC, pix_min, pix_max, rgba) 
    
    updateService.saveObject(child_pixels)
示例#3
0
    def createTestImage(self, sizeX=16, sizeY=16, sizeZ=1, sizeC=1, sizeT=1, session=None):
        """
        Creates a test image of the required dimensions, where each pixel
        value is set to the value of x+y.
        Returns the image (ImageI)
        """
        from numpy import fromfunction, int16
        from omero.util import script_utils

        if session is None:
            session = self.root.sf
        renderingEngine = session.createRenderingEngine()
        queryService = session.getQueryService()
        pixelsService = session.getPixelsService()
        rawPixelStore = session.createRawPixelsStore()
        containerService = session.getContainerService()

        def f1(x, y):
            return y

        def f2(x, y):
            return (x + y) / 2

        def f3(x, y):
            return x

        pType = "int16"
        # look up the PixelsType object from DB
        # omero::model::PixelsType
        pixelsType = queryService.findByQuery("from PixelsType as p where p.value='%s'" % pType, None)
        if pixelsType is None and pType.startswith("float"):  # e.g. float32
            # omero::model::PixelsType
            pixelsType = queryService.findByQuery("from PixelsType as p where p.value='%s'" % "float", None)
        if pixelsType is None:
            print "Unknown pixels type for: " % pType
            raise Exception("Unknown pixels type for: " % pType)

        # code below here is very similar to combineImages.py
        # create an image in OMERO and populate the planes with numpy 2D arrays
        channelList = range(1, sizeC + 1)
        iId = pixelsService.createImage(sizeX, sizeY, sizeZ, sizeT, channelList, pixelsType, "testImage", "description")
        imageId = iId.getValue()
        image = containerService.getImages("Image", [imageId], None)[0]

        pixelsId = image.getPrimaryPixels().getId().getValue()
        rawPixelStore.setPixelsId(pixelsId, True)

        colourMap = {0: (0, 0, 255, 255), 1: (0, 255, 0, 255), 2: (255, 0, 0, 255), 3: (255, 0, 255, 255)}
        fList = [f1, f2, f3]
        for theC in range(sizeC):
            minValue = 0
            maxValue = 0
            f = fList[theC % len(fList)]
            for theZ in range(sizeZ):
                for theT in range(sizeT):
                    plane2D = fromfunction(f, (sizeY, sizeX), dtype=int16)
                    script_utils.uploadPlane(rawPixelStore, plane2D, theZ, theC, theT)
                    minValue = min(minValue, plane2D.min())
                    maxValue = max(maxValue, plane2D.max())
            pixelsService.setChannelGlobalMinMax(pixelsId, theC, float(minValue), float(maxValue))
            rgba = None
            if theC in colourMap:
                rgba = colourMap[theC]
        for theC in range(sizeC):
            script_utils.resetRenderingSettings(renderingEngine, pixelsId, theC, minValue, maxValue, rgba)

        renderingEngine.close()
        rawPixelStore.close()

        # See #9070. Forcing a thumbnail creation
        tb = session.createThumbnailStore()
        try:
            s = tb.getThumbnailByLongestSideSet(rint(16), [pixelsId])
            assert s[pixelsId] != ""

        finally:
            tb.close()

        # Reloading image to prevent error on old pixels updateEvent
        image = containerService.getImages("Image", [imageId], None)[0]
        return image
示例#4
0
def makeSingleImage(services, parameterMap, imageIds, dataset, colourMap):
    """
    This takes the images specified by imageIds, sorts them in to Z,C,T dimensions according to parameters
    in the parameterMap, assembles them into a new Image, which is saved in dataset. 
    """

    if len(imageIds) == 0:
        return

    renderingEngine = services["renderingEngine"]
    queryService = services["queryService"]
    pixelsService = services["pixelsService"]
    rawPixelStore = services["rawPixelStore"]
    rawPixelStoreUpload = services["rawPixelStoreUpload"]
    updateService = services["updateService"]
    rawFileStore = services["rawFileStore"]
    containerService = services["containerService"]

    print "imageIds", len(imageIds)

    # Filter images by name if user has specified filter.
    idNameMap = None
    if "Filter_Names" in parameterMap:
        filterString = parameterMap["Filter_Names"]
        if len(filterString) > 0:
            print "Filtering images for names containing '%s'" % filterString
            idNameMap = getImageNames(queryService, imageIds)
            imageIds = [i for i in imageIds if idNameMap[i].find(filterString) > -1]

    print "imageIds", len(imageIds)
    imageId = imageIds[0]

    # get pixels, with pixelsType, from the first image
    query_string = "select p from Pixels p join fetch p.image i join fetch p.pixelsType pt where i.id='%d'" % imageId
    pixels = queryService.findByQuery(query_string, None)
    pixelsType = pixels.getPixelsType()  # use the pixels type object we got from the first image.

    # combined image will have same X and Y sizes...
    sizeX = pixels.getSizeX().getValue()
    sizeY = pixels.getSizeY().getValue()
    sourceZ = pixels.getSizeZ().getValue()  # if we have a Z stack, use this in new image (don't combine Z)

    # Now we need to find where our planes are coming from.
    # imageMap is a map of destination:source, defined as (newX, newY, newZ):(imageId, z)
    if "Manually_Define_Dimensions" in parameterMap and parameterMap["Manually_Define_Dimensions"]:
        sizeZ, sizeC, sizeT, imageMap = manuallyAssignImages(parameterMap, imageIds, sourceZ)
        cNames = {}
    else:
        sizeZ, cNames, sizeT, imageMap = assignImagesByRegex(parameterMap, imageIds, queryService, sourceZ, idNameMap)
        sizeC = len(cNames)

    print "sizeZ: %s  sizeC: %s  sizeT: %s" % (sizeZ, sizeC, sizeT)

    if "Channel_Names" in parameterMap:
        for c, name in enumerate(parameterMap["Channel_Names"]):
            cNames[c] = name.getValue()

    imageName = "combinedImage"
    description = "created from image Ids: %s" % imageIds

    channelList = range(sizeC)
    iId = pixelsService.createImage(sizeX, sizeY, sizeZ, sizeT, channelList, pixelsType, imageName, description)
    image = containerService.getImages("Image", [iId.getValue()], None)[0]

    pixelsId = image.getPrimaryPixels().getId().getValue()
    rawPixelStoreUpload.setPixelsId(pixelsId, True)

    for theC in range(sizeC):
        minValue = 0
        maxValue = 0
        for theZ in range(sizeZ):
            for theT in range(sizeT):
                if (theZ, theC, theT) in imageMap:
                    imageId, planeZ = imageMap[(theZ, theC, theT)]
                    print "Getting plane from Image ID:", imageId
                    query_string = (
                        "select p from Pixels p join fetch p.image i join fetch p.pixelsType pt where i.id='%d'"
                        % imageId
                    )
                    pixels = queryService.findByQuery(query_string, None)
                    plane2D = getPlane(rawPixelStore, pixels, planeZ, 0, 0)
                else:
                    print "Creating blank plane for theZ, theC, theT", theZ, theC, theT
                    plane2D = zeros((sizeY, sizeX))
                print "Uploading plane: theZ: %s, theC: %s, theT: %s" % (theZ, theC, theT)
                scriptUtil.uploadPlaneByRow(rawPixelStoreUpload, plane2D, theZ, theC, theT)
                minValue = min(minValue, plane2D.min())
                maxValue = max(maxValue, plane2D.max())
        print "Setting the min, max ", minValue, maxValue
        pixelsService.setChannelGlobalMinMax(pixelsId, theC, float(minValue), float(maxValue))
        rgba = COLOURS["White"]
        if theC in colourMap:
            rgba = colourMap[theC]
            print "Setting the Channel colour:", rgba
        scriptUtil.resetRenderingSettings(renderingEngine, pixelsId, theC, minValue, maxValue, rgba)

    # rename new channels
    pixels = renderingEngine.getPixels()  # has channels loaded - (getting Pixels from image doesn't)
    i = 0
    for c in pixels.iterateChannels():  # c is an instance of omero.model.ChannelI
        if i >= len(cNames):
            break
        lc = c.getLogicalChannel()  # returns omero.model.LogicalChannelI
        lc.setName(rstring(cNames[i]))
        updateService.saveObject(lc)
        i += 1

    # put the image in dataset, if specified.
    if dataset:
        link = omero.model.DatasetImageLinkI()
        link.parent = omero.model.DatasetI(dataset.id.val, False)
        link.child = omero.model.ImageI(image.id.val, False)
        updateService.saveAndReturnObject(link)

    return image
示例#5
0
    def upload_image_pixels(self,
                            imageId,
                            query_service,
                            omero_session,
                            pixels_service,
                            rgb,
                            imageMap,
                            sizeC,
                            sizeZ,
                            sizeT,
                            sizeX,
                            sizeY,
                            channels,
                            colourMap,
                            convert_to_uint16=False):
        params = sys.ParametersI()
        params.addId(imageId)
        pixelsId = query_service.projection(
            "select p.id from Image i join i.pixels p where i.id = :id",
            params)[0][0].val

        rawPixelStore = omero_session.createRawPixelsStore()
        rawPixelStore.setPixelsId(pixelsId, True)

        zStart = 1  # could be 0 or 1 ?
        tStart = 1

        try:
            for theC in range(sizeC):
                minValue = 0
                maxValue = 0
                for theZ in range(sizeZ):
                    zIndex = theZ + zStart
                    for theT in range(sizeT):
                        tIndex = theT + tStart
                        if rgb:
                            c = "0"
                        else:
                            c = channels[theC]
                        if (zIndex, c, tIndex) in imageMap:
                            imagePath = imageMap[(zIndex, c, tIndex)]
                            if rgb:
                                PROCESSING_LOG.debug(
                                    "Getting rgb plane from: %s" % imagePath)
                                plane2D = script_utils.getPlaneFromImage(
                                    imagePath, theC)
                            else:
                                PROCESSING_LOG.debug("Getting plane from: %s" %
                                                     imagePath)
                                plane2D = script_utils.getPlaneFromImage(
                                    imagePath)
                        else:
                            PROCESSING_LOG.debug("Creating blank plane for .",
                                                 theZ, channels[theC], theT)
                            plane2D = np.zeros((sizeY, sizeX))
                        PROCESSING_LOG.debug(
                            "Uploading plane: theZ: %s, theC: %s, theT: %s" %
                            (theZ, theC, theT))

                        if convert_to_uint16 == True:
                            plane2D = np.array(plane2D, dtype=np.uint16)

                        script_utils.upload_plane(rawPixelStore, plane2D, theZ,
                                                  theC, theT)
                        minValue = min(minValue, plane2D.min())
                        maxValue = max(maxValue, plane2D.max())
                pixels_service.setChannelGlobalMinMax(pixelsId, theC,
                                                      float(minValue),
                                                      float(maxValue))
                rgba = None
                if theC in colourMap:
                    rgba = colourMap[theC]
                try:
                    renderingEngine = omero_session.createRenderingEngine()
                    script_utils.resetRenderingSettings(
                        renderingEngine, pixelsId, theC, minValue, maxValue,
                        rgba)
                finally:
                    renderingEngine.close()
        finally:
            rawPixelStore.close()

        return pixelsId
示例#6
0
def makeSingleImage(services, parameterMap, imageIds, dataset, colourMap):
    """
    This takes the images specified by imageIds, sorts them in to Z,C,T dimensions according to parameters
    in the parameterMap, assembles them into a new Image, which is saved in dataset. 
    """

    if len(imageIds) == 0:
        return

    renderingEngine = services["renderingEngine"]
    queryService = services["queryService"]
    pixelsService = services["pixelsService"]
    rawPixelStore = services["rawPixelStore"]
    rawPixelStoreUpload = services["rawPixelStoreUpload"]
    updateService = services["updateService"]
    rawFileStore = services["rawFileStore"]
    containerService = services["containerService"]

    print "imageIds", len(imageIds)

    # Filter images by name if user has specified filter.
    idNameMap = None
    if "Filter_Names" in parameterMap:
        filterString = parameterMap["Filter_Names"]
        if len(filterString) > 0:
            print "Filtering images for names containing '%s'" % filterString
            idNameMap = getImageNames(queryService, imageIds)
            imageIds = [
                i for i in imageIds if idNameMap[i].find(filterString) > -1
            ]

    print "imageIds", len(imageIds)
    imageId = imageIds[0]

    # get pixels, with pixelsType, from the first image
    query_string = "select p from Pixels p join fetch p.image i join fetch p.pixelsType pt where i.id='%d'" % imageId
    pixels = queryService.findByQuery(query_string, None)
    pixelsType = pixels.getPixelsType(
    )  # use the pixels type object we got from the first image.

    # combined image will have same X and Y sizes...
    sizeX = pixels.getSizeX().getValue()
    sizeY = pixels.getSizeY().getValue()
    sourceZ = pixels.getSizeZ().getValue(
    )  # if we have a Z stack, use this in new image (don't combine Z)

    # Now we need to find where our planes are coming from.
    # imageMap is a map of destination:source, defined as (newX, newY, newZ):(imageId, z)
    if "Manually_Define_Dimensions" in parameterMap and parameterMap[
            "Manually_Define_Dimensions"]:
        sizeZ, sizeC, sizeT, imageMap = manuallyAssignImages(
            parameterMap, imageIds, sourceZ)
        cNames = {}
    else:
        sizeZ, cNames, sizeT, imageMap = assignImagesByRegex(
            parameterMap, imageIds, queryService, sourceZ, idNameMap)
        sizeC = len(cNames)

    print "sizeZ: %s  sizeC: %s  sizeT: %s" % (sizeZ, sizeC, sizeT)

    if "Channel_Names" in parameterMap:
        for c, name in enumerate(parameterMap["Channel_Names"]):
            cNames[c] = name.getValue()

    imageName = "combinedImage"
    description = "created from image Ids: %s" % imageIds

    channelList = range(sizeC)
    iId = pixelsService.createImage(sizeX, sizeY, sizeZ, sizeT, channelList,
                                    pixelsType, imageName, description)
    image = containerService.getImages("Image", [iId.getValue()], None)[0]

    pixelsId = image.getPrimaryPixels().getId().getValue()
    rawPixelStoreUpload.setPixelsId(pixelsId, True)

    for theC in range(sizeC):
        minValue = 0
        maxValue = 0
        for theZ in range(sizeZ):
            for theT in range(sizeT):
                if (theZ, theC, theT) in imageMap:
                    imageId, planeZ = imageMap[(theZ, theC, theT)]
                    print "Getting plane from Image ID:", imageId
                    query_string = "select p from Pixels p join fetch p.image i join fetch p.pixelsType pt where i.id='%d'" % imageId
                    pixels = queryService.findByQuery(query_string, None)
                    plane2D = getPlane(rawPixelStore, pixels, planeZ, 0, 0)
                else:
                    print "Creating blank plane for theZ, theC, theT", theZ, theC, theT
                    plane2D = zeros((sizeY, sizeX))
                print "Uploading plane: theZ: %s, theC: %s, theT: %s" % (
                    theZ, theC, theT)
                scriptUtil.uploadPlaneByRow(rawPixelStoreUpload, plane2D, theZ,
                                            theC, theT)
                minValue = min(minValue, plane2D.min())
                maxValue = max(maxValue, plane2D.max())
        print "Setting the min, max ", minValue, maxValue
        pixelsService.setChannelGlobalMinMax(pixelsId, theC, float(minValue),
                                             float(maxValue))
        rgba = COLOURS["White"]
        if theC in colourMap:
            rgba = colourMap[theC]
            print "Setting the Channel colour:", rgba

    for theC in range(sizeC):
        scriptUtil.resetRenderingSettings(renderingEngine, pixelsId, theC,
                                          minValue, maxValue, rgba)

    # rename new channels
    pixels = renderingEngine.getPixels(
    )  # has channels loaded - (getting Pixels from image doesn't)
    i = 0
    for c in pixels.iterateChannels(
    ):  # c is an instance of omero.model.ChannelI
        if i >= len(cNames): break
        lc = c.getLogicalChannel()  # returns omero.model.LogicalChannelI
        lc.setName(rstring(cNames[i]))
        updateService.saveObject(lc)
        i += 1

    # put the image in dataset, if specified.
    if dataset and dataset.canLink():
        link = omero.model.DatasetImageLinkI()
        link.parent = omero.model.DatasetI(dataset.getId(), False)
        link.child = omero.model.ImageI(image.id.val, False)
        updateService.saveAndReturnObject(link)
    else:
        link = None

    return image, link
示例#7
0
    def createTestImage(self,
                        sizeX=16,
                        sizeY=16,
                        sizeZ=1,
                        sizeC=1,
                        sizeT=1,
                        session=None):
        """
        Creates a test image of the required dimensions, where each pixel
        value is set to the value of x+y.
        Returns the image (ImageI)
        """
        from numpy import fromfunction, int16
        from omero.util import script_utils

        if session is None:
            session = self.root.sf
        renderingEngine = session.createRenderingEngine()
        queryService = session.getQueryService()
        pixelsService = session.getPixelsService()
        rawPixelStore = session.createRawPixelsStore()
        containerService = session.getContainerService()

        def f1(x, y):
            return y

        def f2(x, y):
            return (x + y) / 2

        def f3(x, y):
            return x

        pType = "int16"
        # look up the PixelsType object from DB
        # omero::model::PixelsType
        pixelsType = queryService.findByQuery(
            "from PixelsType as p where p.value='%s'" % pType, None)
        if pixelsType is None and pType.startswith("float"):  # e.g. float32
            # omero::model::PixelsType
            pixelsType = queryService.findByQuery(
                "from PixelsType as p where p.value='%s'" % "float", None)
        if pixelsType is None:
            print "Unknown pixels type for: " % pType
            raise Exception("Unknown pixels type for: " % pType)

        # code below here is very similar to combineImages.py
        # create an image in OMERO and populate the planes with numpy 2D arrays
        channelList = range(1, sizeC + 1)
        iId = pixelsService.createImage(sizeX, sizeY, sizeZ, sizeT,
                                        channelList, pixelsType, "testImage",
                                        "description")
        imageId = iId.getValue()
        image = containerService.getImages("Image", [imageId], None)[0]

        pixelsId = image.getPrimaryPixels().getId().getValue()
        rawPixelStore.setPixelsId(pixelsId, True)

        colourMap = {
            0: (0, 0, 255, 255),
            1: (0, 255, 0, 255),
            2: (255, 0, 0, 255),
            3: (255, 0, 255, 255)
        }
        fList = [f1, f2, f3]
        for theC in range(sizeC):
            minValue = 0
            maxValue = 0
            f = fList[theC % len(fList)]
            for theZ in range(sizeZ):
                for theT in range(sizeT):
                    plane2D = fromfunction(f, (sizeY, sizeX), dtype=int16)
                    script_utils.uploadPlane(rawPixelStore, plane2D, theZ,
                                             theC, theT)
                    minValue = min(minValue, plane2D.min())
                    maxValue = max(maxValue, plane2D.max())
            pixelsService.setChannelGlobalMinMax(pixelsId, theC,
                                                 float(minValue),
                                                 float(maxValue))
            rgba = None
            if theC in colourMap:
                rgba = colourMap[theC]
        for theC in range(sizeC):
            script_utils.resetRenderingSettings(renderingEngine, pixelsId,
                                                theC, minValue, maxValue, rgba)

        renderingEngine.close()
        rawPixelStore.close()

        # See #9070. Forcing a thumbnail creation
        tb = session.createThumbnailStore()
        try:
            s = tb.getThumbnailByLongestSideSet(rint(16), [pixelsId])
            assert s[pixelsId] != ''

        finally:
            tb.close()

        # Reloading image to prevent error on old pixels updateEvent
        image = containerService.getImages("Image", [imageId], None)[0]
        return image
def emanFilter(session, parameterMap):
    """
    This is where the action happens.
    For each image, we get the data from OMERO as an EMData object, do the filtering and write back to OMERO. 
    """
    
    # create services we need 
    queryService = session.getQueryService()
    rawFileStore = session.createRawFileStore()
    rawPixelStore = session.createRawPixelsStore()
    rawPixelStoreUpload = session.createRawPixelsStore()
    renderingEngine = session.createRenderingEngine()
    pixelsService = session.getPixelsService()
    containerService = session.getContainerService()
    updateService = session.getUpdateService()
    
    imageIds = []
    
    dataType = parameterMap["Data_Type"]
    if dataType == "Image":
        for imageId in parameterMap["IDs"]:
            iId = long(imageId.getValue())
            imageIds.append(iId)
    else:   # Dataset
        for datasetId in parameterMap["IDs"]:
            datasetIds = []
            try:
                dId = long(datasetId.getValue())
                datasetIds.append(dId)
            except: pass
            # simply aggregate all images from the datasets
            images = containerService.getImages("Dataset", datasetIds, None)
            for i in images:
                imageIds.append(i.getId().getValue())
            
    if len(imageIds) == 0:
        return
        
    # get the project from the first image
    project = None
    dataset = None
    imageId = imageIds[0]
    query_string = "select i from Image i join fetch i.datasetLinks idl join fetch idl.parent d join fetch d.projectLinks pl join fetch pl.parent where i.id in (%s)" % imageId
    image = queryService.findByQuery(query_string, None)
    if image:
        for link in image.iterateDatasetLinks():
            dataset = link.parent
            print "Dataset", dataset.name.val
            for dpLink in dataset.iterateProjectLinks():
                project = dpLink.parent
                print "Project", project.name.val
                break # only use 1st Project
            break    # only use 1st Dataset
    
    if "New_Dataset_Name" in parameterMap:
        # make a dataset for images
        dataset = omero.model.DatasetI()
        dataset.name = rstring(parameterMap["New_Dataset_Name"])
        from datetime import datetime
        dt = datetime.now()
        dataset.description = rstring("Images generated by EMAN2 Filtering on %s" % dt.strftime("%A, %d. %B %Y %I:%M%p"))
        dataset = updateService.saveAndReturnObject(dataset)
        if project:        # and put it in the same project
            link = omero.model.ProjectDatasetLinkI()
            link.parent = omero.model.ProjectI(project.id.val, False)
            link.child = omero.model.DatasetI(dataset.id.val, False)
            updateService.saveAndReturnObject(link)
    
    filterName = parameterMap["Filter_Name"]
    paramStrings = []
    filterParamMap = None
    if "Filter_Params" in parameterMap:
        filterParamMap = {}
        fpMap = parameterMap["Filter_Params"]
        for p, v in fpMap.items():
            paramStrings.append("%s: %s" % (p, v.getValue())) # get value from rtype
            try:
                filterParamMap[p] = float(v.getValue())  # if the value is a float
            except:
                filterParamMap[p] = v.getValue()
    paramString = ", ".join(paramStrings)   # just for adding to new image description
    
    e = EMData()
    bypassOriginalFile = True
    
    newImages = []
    for imageId in imageIds:
        # set up pixel-store and get the pixels object
        query_string = "select p from Pixels p join fetch p.image as i join fetch p.pixelsType where i.id='%d'" % imageId
        pixels = queryService.findByQuery(query_string, None)
        sizeX = pixels.getSizeX().getValue()
        sizeY = pixels.getSizeY().getValue()
        sizeZ = pixels.getSizeZ().getValue()
        sizeC = pixels.getSizeC().getValue()
        sizeT = pixels.getSizeT().getValue()
        rawPixelStore.setPixelsId(pixels.getId().getValue(), bypassOriginalFile)
        em = EMData(sizeX,sizeY,sizeZ)
        pixelsType = pixels.pixelsType
        # create the new image, ready to take planes
        description = "Created from image ID: %s by applying EMAN2 filter: '%s' with parameters: %s" % (imageId, filterName, paramString)
        imageName = pixels.image.name.val   # new image has same name
        print imageName, description
        
        iId = None
        image = None
        # need to loop through extra dimensions, since EMAN2 only handles 3D. 
        for theC in range(sizeC):
            minValue = None
            maxValue = 0
            for theT in range(sizeT):
                for z in range(sizeZ):
                    plane2D = scriptUtil.downloadPlane(rawPixelStore, pixels, z, theC, theT)
                    try:    # method seems to depend which version of EMAN2 you have
                        EMNumPy.numpy2em(plane2D, e)
                    except:
                        e = EMNumPy.numpy2em(plane2D)
                    em.insert_clip(e,(0,0,z))
                # do the filtering
                if filterParamMap:  em.process_inplace(filterName, filterParamMap)
                else:   em.process_inplace(filterName)
                # convert back to numpy (datatype may be different) and upload to OMERO as new image
                filteredPlanes = EMNumPy.em2numpy(em)
                print "em.get_zsize()", em.get_zsize()
                print "filteredPlanes", filteredPlanes.shape
                if iId == None:
                    iId = createImage(pixelsService, queryService, filteredPlanes, sizeT, sizeC, imageName, description)
                    image = containerService.getImages("Image", [iId], None)[0]
                    pixelsId = image.getPrimaryPixels().getId().getValue()
                    rawPixelStoreUpload.setPixelsId(pixelsId, bypassOriginalFile)
                if em.get_zsize() > 1:      # 3D array
                    for z, plane in enumerate(filteredPlanes):
                        if minValue == None: minValue = plane.min()
                        minValue = min(minValue, plane.min())
                        maxValue = max(maxValue, plane.max())
                        scriptUtil.uploadPlane(rawPixelStoreUpload, plane, z, theC, theT)
                else:   # 2D array
                    if minValue == None: minValue = filteredPlanes.min()
                    minValue = min(minValue, filteredPlanes.min())
                    maxValue = max(maxValue, filteredPlanes.max())
                    scriptUtil.uploadPlane(rawPixelStoreUpload, filteredPlanes, z, theC, theT)
            print "Setting the min, max ", minValue, maxValue
            pixelsService.setChannelGlobalMinMax(pixelsId, theC, float(minValue), float(maxValue))
            scriptUtil.resetRenderingSettings(renderingEngine, pixelsId, theC, minValue, maxValue)

        
        image.name = rstring(imageName)
        image.description = rstring(description)
        newImages.append(updateService.saveAndReturnObject(image))
        # put image in dataset
        if dataset:
            dlink = omero.model.DatasetImageLinkI()
            dlink.parent = omero.model.DatasetI(dataset.id.val, False)
            dlink.child = omero.model.ImageI(iId, False)
            updateService.saveAndReturnObject(dlink)
    
    return (dataset, newImages)