def __init__(self, name, image, orientation=None, *args, **kwargs): """ Initialiser of an ROI by name and image object :param str name: the name of this ROI :param `omero.gateway._ImageWrapper` image: the associated image """ super(OMEROROI, self).__init__(*args, **kwargs) if isinstance(name, str): self.setName(name) if isinstance(image, omero.gateway._ImageWrapper): self.setImage(image) self.__image = image if orientation is not None: directions = ['x', 'y', 'z'] try: assert orientation in directions except AssertionError: print_date("Invalid orientation: {}; should be in {}".format( orientation, ", ".join(directions))) sys.exit(1) self._orientation = orientation # try to determine the orientation from the image name else: if re.match(r'.*\-front\..*$', image.name, re.IGNORECASE): self._orientation = 'x' elif re.match(r'.*\-side\..*$', image.name, re.IGNORECASE): self._orientation = 'y' elif re.match(r'.*\-top\..*$', image.name, re.IGNORECASE): self._orientation = 'z' else: print_date( "Unable to determine ROI orientation. Ensure image name has one of the form '*-front.*' (x), '*-side.*' (y) or '*-top.*' (z)." ) sys.exit(1)
def attachRois(self, omero_rois): """Attach the rois from the iterable""" non_rois = filter(lambda r: not isinstance(r, OMEROROI), omero_rois) try: assert len(non_rois) == 0 except AssertionError: print_date("Found {:,} non-ROI objects".format(len(non_rois))) return 1 for roi in omero_rois: self.saveRoi(roi) return os.EX_OK
def saveRoi(self, roi): """Save the given ROI :param roi: an ROI object :type roi: `omero.model.Roi` """ import Ice try: self.updateService.saveObject(roi) except Ice.MemoryLimitException as e: # @UndefinedVariable print_date(str(e)) sys.exit(1)
def list(self): """List images or ROIs :return int count: the number of images/ROIs """ if self.args.images: print_date("Listing images...") images = self.images() if self.args.summary: pass else: print_date("Structuring output...") image_view = ImageView(images) print(image_view) return len(images) elif self.args.rois: print_date("Listing ROIs...") rois = self.rois() if self.args.summary: pass else: print_date("Structuring output...") roi_view = ROIView(rois) print(roi_view) return len(rois)
def rois(self, project=None, dataset=None): """Get an iterator over the ROIs associated with the specified image ID :param int image_id: image ID """ rois = list() print_date("Retrieving ROIs...") if self.args.image_id is not None: return self.getROIs(self.args.image_id) else: for image in self.images(project, dataset): if image.getROICount() > 0: rois.append((image, self.getROIs(image.getId()))) roi_count = sum(map(lambda r: len(r[1]), rois)) print_date("Found {:,} ROIs in {:,} images.".format( roi_count, len(rois))) return rois
def deleteRoi(self, roi_id): """ Delete the given ROI :param roi: an ROI object :type roi: `omero.model.Roi` """ from omero.callbacks import CmdCallbackI # @UnresolvedImport handle = self.conn.deleteObjects("Roi", [roi_id], deleteAnns=True, deleteChildren=True) callback = CmdCallbackI(self.conn.c, handle) while not callback.block(500): if self.args.verbose: print_date(".", newline=False, incl_date=False) time.sleep(2) callback.close(True)
def __enter__(self): from omero.gateway import BlitzGateway # @UnresolvedImport self.conn = BlitzGateway(host=self.host, username=self.user, passwd=self.password, port=self.port) self.connected = self.conn.connect() # failed to connect if not self.connected: print_date( "Unable to connect to host '{}' on port {} using user '{}'". format(self.host, self.port, self.user)) print_date("Check that server is up") sys.exit(1) # keepalive self.conn.c.enableKeepAlive(5) self.omero_user = self.conn.getUser() self.userId = self.omero_user.getId() self.updateService = self.conn.getUpdateService() self.roiService = self.conn.getRoiService() return self
def images(self, project=None, dataset=None): """The list of images associated with the current user If the image ID is specified only the required image is returned. (The project and dataset are ignored.) Otherwise: - If a project object is provided all images in all datasets in the project are returned. (The dataset is ignored.) - If a project object and dataset object are provided then only those images in the project and dataset are return. - If no project object is provided but a dataset object is provided then only those images in the dataset are returned. :param str project: OMERO project name :param str dataset: OMERO dataset name :return list images: a list of OMERO ``Image`` objects """ # assertions images = list() print_date("Retrieving images...") if self.args.image_id is not None: try: assert isinstance(self.args.image_id, int) or isinstance( self.args.image_id, long) except AssertionError: print_date("Invalid type for image ID: {}".format( type(self.args.image_id))) sys.exit(1) image = self.getImage(self.args.image_id) if image is not None: images.append(image) elif self.args.image_name is not None: images = self.conn.searchObjects(["Image"], self.args.image_name) else: if project is not None: # project specified print_date( "Searching for images in project '{}'".format(project)) # get all projects matching projects = self.conn.searchObjects(["Project"], project) # get all datasets in projects matching datasets_in_projects = dict() for p in projects: for d in p.listChildren(): datasets_in_projects[d.getName()] = d print_date("Found {} datasets in project '{}'".format( len(datasets_in_projects), project)) # dataset specified if dataset is not None: print_date( "Searching for images in dataset '{}'".format(dataset)) if dataset in datasets_in_projects.keys(): images += datasets_in_projects[dataset].listChildren() else: # dataset not specified print_date( "Searching for images in all {} datasets".format( len(datasets_in_projects))) for dataset in datasets_in_projects.keys(): images += datasets_in_projects[dataset].listChildren() else: # project not specified # dataset specified if dataset is not None: print_date( "Searching for images in dataset '{}'".format(dataset)) datasets = self.conn.searchObjects(["Dataset"], dataset) for dataset in datasets: images += dataset.listChildren() else: datasets = self.datasets() print_date( "Searching for images in all {} datasets".format( len(datasets))) for dataset in datasets: images += dataset.listChildren() print_date("Found {} image(s).".format(len(images))) return images
def __exit__(self, exc_type, exc_value, traceback): # @UnusedVariable self.conn._closeSession() if self.args.verbose: print_date('Connection closed.') self.connected = False