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 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)