예제 #1
0
def add_image(nwbfile, image_data, image_name, module_name, module_description, image_api=None):

    description = '{} image at pixels/cm resolution'.format(image_name)

    if image_api is None:
        image_api = ImageApi

    if isinstance(image_data, sitk.Image):
        data, spacing, unit = ImageApi.deserialize(image_data)
    elif isinstance(image_data, Image):
        data = image_data.data
        spacing = image_data.spacing
        unit = image_data.unit
    else:
        raise ValueError("Not a supported image_data type: {}".format(type(image_data)))

    assert spacing[0] == spacing[1] and len(spacing) == 2 and unit == 'mm'

    if module_name not in nwbfile.modules:
        ophys_mod = ProcessingModule(module_name, module_description)
        nwbfile.add_processing_module(ophys_mod)
    else:
        ophys_mod = nwbfile.modules[module_name]

    image = GrayscaleImage(image_name, data, resolution=spacing[0] / 10, description=description)

    if 'images' not in ophys_mod.containers:
        images = Images(name='images')
        ophys_mod.add_data_interface(images)
    else:
        images = ophys_mod['images']
    images.add_image(image)

    return nwbfile
예제 #2
0
def get_image(nwbfile: NWBFile, name: str, module: str) -> Image:
    nwb_img = nwbfile.processing[module].get_data_interface('images')[name]
    data = nwb_img.data
    resolution = nwb_img.resolution  # px/cm
    spacing = [resolution * 10, resolution * 10]

    img = ImageApi.serialize(data, spacing, 'mm')
    img = ImageApi.deserialize(img=img)
    return img
예제 #3
0
    def deserialize_image(self, sitk_image):
        '''
        Convert SimpleITK image returned by the api to an Image class:

        Args:
            sitk_image (SimpleITK image): image object returned by the api

        Returns
            img (allensdk.brain_observatory.behavior.image_api.Image)
        '''
        img = ImageApi.deserialize(sitk_image)
        return img
예제 #4
0
 def _from_filepath(filepath: str, pixel_size: float) -> Image:
     """
     :param filepath
         path to image
     :param pixel_size
         pixel size in um
     """
     img = mpimg.imread(filepath)
     img = ImageApi.serialize(img, [pixel_size / 1000., pixel_size / 1000.],
                              'mm')
     img = ImageApi.deserialize(img=img)
     return img
예제 #5
0
    def get_roi_masks_by_cell_roi_id(
            self,
            cell_roi_ids: Optional[Union[int, Iterable[int]]] = None):
        """ Obtains boolean masks indicating the location of one
        or more ROIs in this session.

        Parameters
        ----------
        cell_roi_ids : array-like of int, optional
            ROI masks for these rois will be returned.
            The default behavior is to return masks for all rois.

        Returns
        -------
        result : xr.DataArray
            dimensions are:
                - roi_id : which roi is described by this mask?
                - row : index within the underlying image
                - column : index within the image
            values are 1 where an ROI was present, otherwise 0.

        Notes
        -----
        This method helps Allen Institute scientists to look at sessions
        that have not yet had cell specimen ids assigned. You probably want
        to use get_roi_masks instead.
        """

        cell_specimen_table = self.get_cell_specimen_table()

        if cell_roi_ids is None:
            cell_roi_ids = cell_specimen_table["cell_roi_id"].unique()
        elif isinstance(cell_roi_ids, int):
            cell_roi_ids = np.array([int(cell_roi_ids)])
        elif np.issubdtype(type(cell_roi_ids), np.integer):
            cell_roi_ids = np.array([int(cell_roi_ids)])
        else:
            cell_roi_ids = np.array(cell_roi_ids)

        table = cell_specimen_table.copy()
        table.set_index("cell_roi_id", inplace=True)
        table = table.loc[cell_roi_ids, :]

        full_image_shape = table.iloc[0]["roi_mask"].shape
        output = np.zeros((len(cell_roi_ids),
                          full_image_shape[0],
                          full_image_shape[1]), dtype=np.uint8)

        for ii, (_, row) in enumerate(table.iterrows()):
            output[ii, :, :] = row["roi_mask"]

        # Pixel spacing and units of mask image will match either the
        # max or avg projection image of 2P movie.
        max_projection_image = ImageApi.deserialize(self.get_max_projection())
        # Spacing is in (col_spacing, row_spacing) order
        # Coordinates also start spacing_dim / 2 for first element in a
        # dimension. See:
        # https://simpleitk.readthedocs.io/en/master/fundamentalConcepts.html
        pixel_spacing = max_projection_image.spacing
        unit = max_projection_image.unit

        return xr.DataArray(
            data=output,
            dims=("cell_roi_id", "row", "column"),
            coords={
                "cell_roi_id": cell_roi_ids,
                "row": (np.arange(full_image_shape[0])
                        * pixel_spacing[1]
                        + (pixel_spacing[1] / 2)),
                "column": (np.arange(full_image_shape[1])
                           * pixel_spacing[0]
                           + (pixel_spacing[0] / 2))
            },
            attrs={
                "spacing": pixel_spacing,
                "unit": unit
            }
        ).squeeze(drop=True)