Пример #1
0
def run(name, password, dataset_name, dataset_id, host, port):

    conn = BlitzGateway(name, password, host=host, port=port)
    try:
        conn.connect()
        roi_service = conn.getRoiService()
        datasets = []
        if dataset_id >= 0:
            datasets.append(conn.getObject("Dataset", dataset_id))
        else:
            datasets = conn.getObjects("Dataset",
                                       attributes={"name": dataset_name})
        for dataset in datasets:
            print(dataset.getId())
            for image in dataset.listChildren():
                result = roi_service.findByImage(image.getId(), None,
                                                 conn.SERVICE_OPTS)
                if result is not None:
                    roi_ids = [roi.id.val for roi in result.rois]
                    if len(roi_ids) > 0:
                        print("Deleting %s ROIs..." % len(roi_ids))
                        conn.deleteObjects("Roi", roi_ids, wait=True)
    except Exception as exc:
        print("Error while deleting Rois: %s" % str(exc))
    finally:
        conn.close()
Пример #2
0
def main():
    try:
        conn = BlitzGateway(username, password, host=server, port=4064)
        conn.connect()  #Returns True when connected
        updateService = conn.getUpdateService()
        from omero.rtypes import rdouble, rint, rstring
        images = conn.getObjects("Image",
                                 opts={
                                     'owner': owner_id,
                                     'dataset': datasetID
                                 })
        for image in images:
            imageId = image.getId()
            roi_service = conn.getRoiService()
            result = roi_service.findByImage(imageId, None)
            for roi in result.rois:
                print("ROI:  ID:", roi.getId().getValue())
                for s in roi.copyShapes():
                    if type(s) == omero.model.EllipseI:
                        ctr_x = s.getX().getValue()
                        ctr_y = s.getY().getValue()
                        x, y, w, h = rect_roi_frm_ctr(image, ctr_x, ctr_y,
                                                      width, height)
                        MAX_GFP = max_proj(image, max_ch, x, y, w, h)
                        BFZ9 = load_stack_plane(image, slc_ch, slc, x, y, w, h)
                        hstk = np.stack((MAX_GFP, BFZ9), axis=0)
                        tmp_str = 'output_' + str(imageId) + '_' + str(
                            roi.getId().getValue()) + '.tif'
                        output_hyperstack(hstk, tmp_str)
    finally:
        if conn:
            conn.close()
Пример #3
0
    omero.grid.DoubleColumn("lineLength", "", []),
    omero.grid.StringColumn("shapeText", "", 64, []),
]
# create and initialize the table
table = conn.c.sf.sharedResources().newTable(1, "LineLengths%s" % str(random()))
table.initialize(columns)

# make a local array of our data (add it to table in one go)
imageIds = []
roiIds = []
shapeIds = []
theZs = []
theTs = []
lineLengths = []
shapeTexts = []
roiService = conn.getRoiService()
lengthsForImage = []
for image in dataset.listChildren():
    result = roiService.findByImage(image.getId(), None)
    for roi in result.rois:
        for s in roi.copyShapes():
            if type(s) == omero.model.LineI:
                imageIds.append(image.getId())
                roiIds.append(roi.getId().getValue())
                shapeIds.append(s.getId().getValue())
                theZs.append(s.getTheZ().getValue())
                theTs.append(s.getTheT().getValue())
                x1 = s.getX1().getValue()
                x2 = s.getX2().getValue()
                y1 = s.getY1().getValue()
                y2 = s.getY2().getValue()
Пример #4
0
# create an ROI with a single polygon, setting colors and lineWidth
polygon = omero.model.PolygonI()
polygon.theZ = rint(z)
polygon.theT = rint(t)
polygon.fillColor = rint(rgba_to_int(255, 0, 255, 50))
polygon.strokeColor = rint(rgba_to_int(255, 255, 0))
polygon.strokeWidth = omero.model.LengthI(10, UnitsLength.PIXEL)
points = "10,20 50,150 200,200 250,75"
polygon.points = rstring(points)
polygon.textValue = rstring("test-Polygon")
create_roi(image, [polygon])

# Retrieve ROIs linked to an Image
# ================================
roi_service = conn.getRoiService()
result = roi_service.findByImage(imageId, None)
for roi in result.rois:
    print("ROI:  ID:", roi.getId().getValue())
    for s in roi.copyShapes():
        shape = {}
        shape['id'] = s.getId().getValue()
        shape['theT'] = s.getTheT().getValue()
        shape['theZ'] = s.getTheZ().getValue()
        if s.getTextValue():
            shape['textValue'] = s.getTextValue().getValue()
        if type(s) == omero.model.RectangleI:
            shape['type'] = 'Rectangle'
            shape['x'] = s.getX().getValue()
            shape['y'] = s.getY().getValue()
            shape['width'] = s.getWidth().getValue()
Пример #5
0
class TestSavedMasks(ITest):
    def setup_method(self):
        self.conn = BlitzGateway(client_obj=self.client)

    def save_and_return_masks(self, im, masks):
        roi = omero.model.RoiI()
        for mask in masks:
            roi.addShape(mask)

        us = self.conn.getUpdateService()
        roi.setImage(im._obj)
        roi = us.saveAndReturnObject(roi)
        assert roi

        rois = self.conn.getRoiService().findByImage(im.id, None)
        assert len(rois.rois) == 1
        shapes = rois.rois[0].copyShapes()
        assert len(shapes) == len(masks)
        assert all((type(mask) == omero.model.MaskI) for mask in shapes)

        return shapes

    @pytest.mark.parametrize('args', [{}, {
        'rgba': (255, 128, 64, 128),
        'z': 1,
        'c': 2,
        't': 3,
        'text': 'test'
    }])
    def test_mask_from_binary_image(self, binary_image, args):
        im = self.conn.createImageFromNumpySeq(iter([binary_image]),
                                               'omero-rois-integration')
        # Reload
        im = self.conn.getObject('Image', im.id)
        px = im.getPrimaryPixels().getPlane()

        mask = mask_from_binary_image(px, **args)
        mask = self.save_and_return_masks(im, [mask])[0]

        # The rest of this is more or less the same as the unit test

        assert unwrap(mask.getWidth()) == 2
        assert unwrap(mask.getHeight()) == 2
        assert unwrap(mask.getX()) == 1
        assert unwrap(mask.getY()) == 1

        assert np.array_equal(np.frombuffer(mask.getBytes(), np.uint8),
                              np.array([224], dtype=np.uint8))

        if args:
            assert unwrap(mask.getTheZ()) == 1
            assert unwrap(mask.getTheC()) == 2
            assert unwrap(mask.getTheT()) == 3
            assert unwrap(mask.getTextValue()) == 'test'
        else:
            assert unwrap(mask.getTheZ()) is None
            assert unwrap(mask.getTheC()) is None
            assert unwrap(mask.getTheT()) is None
            assert unwrap(mask.getTextValue()) is None

    def test_mask_from_binary_full_image(self):
        binim = np.ones((4, 4), dtype=np.uint8)
        im = self.conn.createImageFromNumpySeq(iter([binim]),
                                               'omero-rois-integration')
        # Reload
        im = self.conn.getObject('Image', im.id)
        px = im.getPrimaryPixels().getPlane()

        mask = mask_from_binary_image(px)
        mask = self.save_and_return_masks(im, [mask])[0]

        # The rest of this is more or less the same as the unit test

        assert unwrap(mask.getWidth()) == 4
        assert unwrap(mask.getHeight()) == 4
        assert np.array_equal(np.frombuffer(mask.getBytes(), np.uint8),
                              np.array([255, 255], dtype=np.uint8))

    @pytest.mark.parametrize('args', [{}, {
        'rgba': (255, 128, 64, 128),
        'z': 1,
        'c': 2,
        't': 3,
        'text': 'test'
    }])
    def test_masks_from_label_image(self, label_image, args):
        im = self.conn.createImageFromNumpySeq(iter([label_image]),
                                               'omero-rois-integration')
        # Reload
        im = self.conn.getObject('Image', im.id)
        px = im.getPrimaryPixels().getPlane()

        masks = masks_from_label_image(px, **args)
        masks = self.save_and_return_masks(im, masks)

        # The rest of this is more or less the same as the unit test

        expected = (
            # w, h, x, y, bytes
            (2, 2, 1, 1, np.array([224], dtype=np.uint8)),
            (2, 3, 2, 0, np.array([72], dtype=np.uint8)),
        )

        assert len(masks) == 2

        for i, mask in enumerate(masks):
            assert unwrap(mask.getWidth()) == expected[i][0]
            assert unwrap(mask.getHeight()) == expected[i][1]
            assert unwrap(mask.getX()) == expected[i][2]
            assert unwrap(mask.getY()) == expected[i][3]

            assert np.array_equal(np.frombuffer(mask.getBytes(), np.uint8),
                                  expected[i][4])

            if args:
                assert unwrap(mask.getTheZ()) == 1
                assert unwrap(mask.getTheC()) == 2
                assert unwrap(mask.getTheT()) == 3
                assert unwrap(mask.getTextValue()) == 'test'
            else:
                assert unwrap(mask.getTheZ()) is None
                assert unwrap(mask.getTheC()) is None
                assert unwrap(mask.getTheT()) is None
                assert unwrap(mask.getTextValue()) is None

    @pytest.mark.parametrize('args', [{}, {
        'rgba': (255, 128, 64, 128),
        'z': 1,
        'c': 2,
        't': 3,
        'text': 'test'
    }])
    def test_empty_mask_from_binary_image(self, args):
        empty_binary_image = np.array([[0]], dtype=np.uint8)
        raise_on_no_mask = False
        im = self.conn.createImageFromNumpySeq(iter([empty_binary_image]),
                                               'omero-rois-integration')
        # Reload
        im = self.conn.getObject('Image', im.id)
        px = im.getPrimaryPixels().getPlane()

        mask = mask_from_binary_image(px,
                                      raise_on_no_mask=raise_on_no_mask,
                                      **args)
        mask = self.save_and_return_masks(im, [mask])[0]

        # The rest of this is more or less the same as the unit test

        assert unwrap(mask.getWidth()) == 0
        assert unwrap(mask.getHeight()) == 0
        assert unwrap(mask.getX()) == 0
        assert unwrap(mask.getY()) == 0
        assert np.array_equal(np.frombuffer(mask.getBytes(), np.uint8), [])

        if args:
            assert unwrap(mask.getTheZ()) == 1
            assert unwrap(mask.getTheC()) == 2
            assert unwrap(mask.getTheT()) == 3
            assert unwrap(mask.getTextValue()) == 'test'
        else:
            assert unwrap(mask.getTheZ()) is None
            assert unwrap(mask.getTheC()) is None
            assert unwrap(mask.getTheT()) is None
            assert unwrap(mask.getTextValue()) is None
Пример #6
0
class OMEROConnection(object):
    def __init__(self, args, configs):
        self.args = args
        self.configs = configs
        self.connect_with = self.configs['CONNECT_WITH']
        self.host = self.configs['OMERO_{}_HOST'.format(self.connect_with)]
        self.user = self.configs['OMERO_{}_USER'.format(self.connect_with)]
        self.password = self.configs['OMERO_{}_PASSWORD'.format(
            self.connect_with)]
        self.port = self.configs['OMERO_{}_PORT'.format(self.connect_with)]

    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 __exit__(self, exc_type, exc_value, traceback):  # @UnusedVariable
        self.conn._closeSession()
        if self.args.verbose:
            print_date('Connection closed.')
        self.connected = False

    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)

    @property
    def projects(self):
        if self.args.project is not None:
            projects = self.conn.searchObjects(["Project"], self.args.project)
            return projects
        else:
            return self.conn.listProjects(self.userId)

    def datasets(self, project=None):
        """List the datasets associated with the current user
        
        :param project: a project
        :param bool in_project: are these datasets contained within a project?
        """
        datasets = list()
        if self.args.dataset is not None:
            datasets += self.conn.searchObjects(["Dataset"], self.args.dataset)
        else:
            if project is not None:
                projects = self.conn.searchObjects(["Project"], project)
                for p in projects:
                    datasets += p.listChildren()
            else:
                params = omero.sys.ParametersI()  # @UndefinedVariable
                params.exp(self.userId)
                datasets += self.conn.getObjects("Dataset", params=params)
        return datasets

    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 getImage(self, image_id):
        """Get the image with the image ID specified on the command line
        
        :param int image_id: command line arguments
        :return image: an image
        :rtype image: ``OMEROImage``
        """
        return self.conn.getObject("Image", image_id)

    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 getROIs(self, image_id):
        result = self.roiService.findByImage(image_id, None)
        return result.rois

    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

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

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