Пример #1
0
def roi_figure(conn, command_args):
    """
    This processes the script parameters, adding defaults if needed.
    Then calls a method to make the figure, and finally uploads and attaches
    this to the primary image.

    @param: session         The OMERO session
    @param: command_args    Map of String:Object parameters for the script.
                            Objects are not rtypes, since getValue() was
                            called when the map was processed below.
                            But, list and map objects may contain rtypes (need
                            to call getValue())

    @return:                the id of the originalFileLink child. (ID object,
                            not value)
    """

    log("ROI figure created by OMERO on %s" % date.today())
    log("")

    message = ""  # message to be returned to the client
    pixel_ids = []
    image_ids = []
    image_labels = []

    # function for getting image labels.
    def get_image_names(full_name, tags_list, pd_list):
        name = full_name.split("/")[-1]
        return [name]

    # default function for getting labels is getName (or use datasets / tags)
    if "Image_Labels" in command_args:
        if command_args["Image_Labels"] == "Datasets":

            def get_datasets(name, tags_list, pd_list):
                return [dataset for project, dataset in pd_list]

            get_labels = get_datasets
        elif command_args["Image_Labels"] == "Tags":

            def get_tags(name, tags_list, pd_list):
                return tags_list

            get_labels = get_tags
        else:
            get_labels = get_image_names
    else:
        get_labels = get_image_names

    # Get the images
    images, log_message = script_utils.get_objects(conn, command_args)
    message += log_message
    if not images:
        return None, message

    # Check for rectangular ROIs and filter images list
    images = [image for image in images if image.getROICount("Rectangle") > 0]
    if not images:
        message += "No rectangle ROI found."
        return None, message

    # Attach figure to the first image
    omero_image = images[0]

    # process the list of images. If image_ids is not set, script can't run.
    log("Image details:")
    for image in images:
        image_ids.append(image.getId())
        pixel_ids.append(image.getPrimaryPixels().getId())

    # a map of imageId : list of (project, dataset) names.
    pd_map = figUtil.getDatasetsProjectsFromImages(conn.getQueryService(),
                                                   image_ids)
    tag_map = figUtil.getTagsFromImages(conn.getMetadataService(), image_ids)
    # Build a legend entry for each image
    for image in images:
        name = image.getName()
        image_date = image.getAcquisitionDate()
        iid = image.getId()
        tags_list = tag_map[iid]
        pd_list = pd_map[iid]

        tags = ", ".join(tags_list)
        pd_string = ", ".join(["%s/%s" % pd for pd in pd_list])
        log(" Image: %s  ID: %d" % (name, iid))
        if image_date:
            log("  Date: %s" % image_date)
        else:
            log("  Date: not set")
        log("  Tags: %s" % tags)
        log("  Project/Datasets: %s" % pd_string)

        image_labels.append(get_labels(name, tags_list, pd_list))

    # use the first image to define dimensions, channel colours etc.
    size_x = omero_image.getSizeX()
    size_y = omero_image.getSizeY()
    size_z = omero_image.getSizeZ()
    size_c = omero_image.getSizeC()

    width = size_x
    if "Width" in command_args:
        w = command_args["Width"]
        try:
            width = int(w)
        except ValueError:
            log("Invalid width: %s Using default value: %d" % (str(w), size_x))

    height = size_y
    if "Height" in command_args:
        h = command_args["Height"]
        try:
            height = int(h)
        except ValueError:
            log("Invalid height: %s Using default value" % (str(h), size_y))

    log("Image dimensions for all panels (pixels): width: %d  height: %d" %
        (width, height))

    merged_indexes = []  # the channels in the combined image,
    merged_colours = {}
    if "Merged_Colours" in command_args:
        c_colour_map = command_args["Merged_Colours"]
        for c in c_colour_map:
            rgb = c_colour_map[c]
            try:
                rgb = int(rgb)
                c_index = int(c)
            except ValueError:
                continue
            rgba = image_utils.int_to_rgba(rgb)
            merged_colours[c_index] = rgba
            merged_indexes.append(c_index)
        merged_indexes.sort()
    # make sure we have some merged channels
    if len(merged_indexes) == 0:
        merged_indexes = range(size_c)
    merged_indexes.reverse()

    merged_names = False
    if "Merged_Names" in command_args:
        merged_names = command_args["Merged_Names"]

    # Make channel-names map. If argument wasn't specified, name by index
    channel_names = {}
    if "Channel_Names" in command_args:
        c_name_map = command_args["Channel_Names"]
        for c in range(size_c):
            if str(c) in c_name_map:
                channel_names[c] = c_name_map[str(c)]
            else:
                channel_names[c] = str(c)
    else:
        for c in range(size_c):
            channel_names[c] = str(c)

    # Make split-indexes list. If no "Split_Indexes", show none:
    # http://www.openmicroscopy.org/community/viewtopic.php?f=4&t=940
    split_indexes = []
    if "Split_Indexes" in command_args:
        for index in command_args["Split_Indexes"]:
            split_indexes.append(index)

    colour_channels = True
    key = "Split_Panels_Grey"
    if key in command_args and command_args[key]:
        colour_channels = False

    algorithm = ProjectionType.MAXIMUMINTENSITY
    if "Algorithm" in command_args:
        a = command_args["Algorithm"]
        if (a == "Mean Intensity"):
            algorithm = ProjectionType.MEANINTENSITY

    stepping = 1
    if "Stepping" in command_args:
        s = command_args["Stepping"]
        if (0 < s < size_z):
            stepping = s

    scalebar = None
    if "Scalebar" in command_args:
        sb = command_args["Scalebar"]
        try:
            scalebar = int(sb)
            if scalebar <= 0:
                scalebar = None
            else:
                log("Scalebar is %d microns" % scalebar)
        except ValueError:
            log("Invalid value for scalebar: %s" % str(sb))
            scalebar = None

    overlay_colour = (255, 255, 255)
    if "Overlay_Colour" in command_args:
        r, g, b, a = OVERLAY_COLOURS[command_args["Overlay_Colour"]]
        overlay_colour = (r, g, b)

    roi_zoom = None
    if "ROI_Zoom" in command_args:
        roi_zoom = float(command_args["ROI_Zoom"])
        if roi_zoom == 0:
            roi_zoom = None

    roi_label = "FigureROI"
    if "ROI_Label" in command_args:
        roi_label = command_args["ROI_Label"]

    spacer = (width / 50) + 2

    fig = get_split_view(conn, image_ids, pixel_ids, split_indexes,
                         channel_names, merged_names, colour_channels,
                         merged_indexes, merged_colours, width, height,
                         image_labels, spacer, algorithm, stepping, scalebar,
                         overlay_colour, roi_zoom, roi_label)

    if fig is None:
        log_message = "No figure produced"
        log("\n" + log_message)
        message += log_message
        return None, message

    log("")
    fig_legend = "\n".join(log_strings)

    format = command_args["Format"]

    figure_name = "roi_figure"
    if "Figure_Name" in command_args:
        figure_name = command_args["Figure_Name"]
        figure_name = os.path.basename(figure_name)
    output = "localfile"
    if format == 'PNG':
        output = output + ".png"
        figure_name = figure_name + ".png"
        fig.save(output, "PNG")
        mimetype = "image/png"
    elif format == 'TIFF':
        output = output + ".tiff"
        figure_name = figure_name + ".tiff"
        fig.save(output, "TIFF")
        mimetype = "image/tiff"
    else:
        output = output + ".jpg"
        figure_name = figure_name + ".jpg"
        fig.save(output)
        mimetype = "image/jpeg"

    # Use util method to upload the figure 'output' to the server, attaching
    # it to the omeroImage, adding the
    # figLegend as the fileAnnotation description.
    # Returns the id of the originalFileLink child. (ID object, not value)
    namespace = NSCREATED + "/omero/figure_scripts/ROI_Split_Figure"
    file_annotation, fa_message = script_utils.create_link_file_annotation(
        conn,
        output,
        omero_image,
        output="ROI Split figure",
        mimetype=mimetype,
        namespace=namespace,
        description=fig_legend,
        orig_file_path_and_name=figure_name)
    message += fa_message

    return file_annotation, message
Пример #2
0
def split_view_figure(conn, script_params):
    """
    Processes the arguments, populating defaults if necessary. Prints the
    details to log (fig-legend).
    Even handles missing arguments that are not optional (from when this ran
    from commandline with everything optional)
    then calls make_split_view_figure() to make the figure, attaches it to the
    Image as an 'originalFile' annotation, with fig-legend as the description.

    @return: the id of the originalFileLink child. (ID object, not value)
    """

    log("Split-View figure created by OMERO on %s" % date.today())
    log("")

    message = ""  # message to be returned to the client
    image_ids = []
    pixel_ids = []
    image_labels = []

    # function for getting image labels.
    def get_image_names(full_name, tags_list, pd_list):
        name = full_name.split("/")[-1]
        return [name.decode('utf8')]

    # default function for getting labels is getName (or use datasets / tags)
    if script_params["Image_Labels"] == "Datasets":

        def get_datasets(name, tags_list, pd_list):
            return [dataset.decode('utf8') for project, dataset in pd_list]

        get_labels = get_datasets
    elif script_params["Image_Labels"] == "Tags":

        def get_tags(name, tags_list, pd_list):
            return [t.decode('utf8') for t in tags_list]

        get_labels = get_tags
    else:
        get_labels = get_image_names

    # Get the images
    images, log_message = script_utils.get_objects(conn, script_params)
    message += log_message
    if not images:
        return None, message

    # Attach figure to the first image
    omero_image = images[0]

    # process the list of images
    log("Image details:")
    for image in images:
        image_ids.append(image.getId())
        pixel_ids.append(image.getPrimaryPixels().getId())

    # a map of imageId : list of (project, dataset) names.
    pd_map = figUtil.getDatasetsProjectsFromImages(conn.getQueryService(),
                                                   image_ids)
    tag_map = figUtil.getTagsFromImages(conn.getMetadataService(), image_ids)
    # Build a legend entry for each image
    for image in images:
        name = image.getName()
        image_date = image.getAcquisitionDate()
        iid = image.getId()
        tags_list = tag_map[iid]
        pd_list = pd_map[iid]

        tags = ", ".join(tags_list)
        pd_string = ", ".join(["%s/%s" % pd for pd in pd_list])
        log(" Image: %s  ID: %d" % (name, iid))
        if image_date:
            log("  Date: %s" % image_date)
        else:
            log("  Date: not set")
        log("  Tags: %s" % tags)
        log("  Project/Datasets: %s" % pd_string)

        image_labels.append(get_labels(name, tags_list, pd_list))

    # use the first image to define dimensions, channel colours etc.
    size_x = omero_image.getSizeX()
    size_y = omero_image.getSizeY()
    size_z = omero_image.getSizeZ()
    size_c = omero_image.getSizeC()

    # set image dimensions
    z_start = -1
    z_end = -1
    if "Z_Start" in script_params:
        z_start = script_params["Z_Start"]
    if "Z_End" in script_params:
        z_end = script_params["Z_End"]

    width = "Width" in script_params and script_params["Width"] or size_x
    height = "Height" in script_params and script_params["Height"] or size_y

    log("Image dimensions for all panels (pixels): width: %d  height: %d" %
        (width, height))

    # Make split-indexes list. If argument wasn't specified, include them all.
    split_indexes = []
    if "Split_Indexes" in script_params:
        split_indexes = script_params["Split_Indexes"]
    else:
        split_indexes = range(size_c)

    # Make channel-names map. If argument wasn't specified, name by index
    channel_names = {}
    for c in range(size_c):
        channel_names[c] = str(c)
    if "Channel_Names" in script_params:
        c_name_map = script_params["Channel_Names"]
        for c in c_name_map:
            index = int(c)
            channel_names[index] = c_name_map[c].decode('utf8')

    merged_indexes = []  # the channels in the combined image,
    merged_colours = {}
    if "Merged_Colours" in script_params:
        c_colour_map = script_params["Merged_Colours"]
        for c in c_colour_map:
            rgb = c_colour_map[c]
            try:
                rgb = int(rgb)
                c_index = int(c)
            except ValueError:
                continue
            rgba = image_utils.int_to_rgba(rgb)
            merged_colours[c_index] = rgba
            merged_indexes.append(c_index)
        merged_indexes.sort()
    else:
        merged_indexes = range(size_c)

    colour_channels = not script_params["Split_Panels_Grey"]

    algorithm = ProjectionType.MAXIMUMINTENSITY
    if "Mean Intensity" == script_params["Algorithm"]:
        algorithm = ProjectionType.MEANINTENSITY

    stepping = min(script_params["Stepping"], size_z)

    scalebar = None
    if "Scalebar" in script_params:
        scalebar = script_params["Scalebar"]
        log("Scalebar is %d microns" % scalebar)

    r, g, b, a = OVERLAY_COLOURS[script_params["Overlay_Colour"]]
    overlay_colour = (r, g, b)

    merged_names = script_params["Merged_Names"]

    fig = make_split_view_figure(conn, pixel_ids, z_start, z_end,
                                 split_indexes, channel_names, colour_channels,
                                 merged_indexes, merged_colours, merged_names,
                                 width, height, image_labels, algorithm,
                                 stepping, scalebar, overlay_colour)

    fig_legend = "\n".join(log_strings)

    figure_name = script_params["Figure_Name"]
    figure_name = os.path.basename(figure_name)
    output = "localfile"
    format = script_params["Format"]
    if format == 'PNG':
        output = output + ".png"
        figure_name = figure_name + ".png"
        fig.save(output, "PNG")
        mimetype = "image/png"
    elif format == 'TIFF':
        output = output + ".tiff"
        figure_name = figure_name + ".tiff"
        fig.save(output, "TIFF")
        mimetype = "image/tiff"
    else:
        output = output + ".jpg"
        figure_name = figure_name + ".jpg"
        fig.save(output)
        mimetype = "image/jpeg"

    # Upload the figure 'output' to the server, creating a file annotation and
    # attaching it to the omero_image, adding the
    # fig_legend as the fileAnnotation description.
    namespace = NSCREATED + "/omero/figure_scripts/Split_View_Figure"
    file_annotation, fa_message = script_utils.create_link_file_annotation(
        conn,
        output,
        omero_image,
        output="Split view figure",
        mimetype=mimetype,
        namespace=namespace,
        description=fig_legend,
        orig_file_path_and_name=figure_name)
    message += fa_message

    return file_annotation, message
Пример #3
0
 def test_int_to_rgba(self, color):
     v = image_utils.int_to_rgba(color[4])
     for x in range(0, 3):
         assert color[x] == v[x]