Ejemplo n.º 1
0
def run(password, target, host, port):

    for i in range(1, 51):

        username = "******" % i
        print(username)
        conn = BlitzGateway(username, password, host=host, port=port)
        try:
            conn.connect()
            params = omero.sys.ParametersI()
            params.addString('username', username)
            query = "from Dataset where name='%s' \
                    AND details.owner.omeName=:username" % target
            query_service = conn.getQueryService()
            dataset = query_service.findAllByQuery(query, params,
                                                   conn.SERVICE_OPTS)

            if len(dataset) == 0:
                print("No dataset with name %s found" % target)
                continue
            dataset_id = dataset[0].getId().getValue()

            print('dataset', dataset_id)
            dataset = conn.getObject("Dataset", dataset_id)

            kvp_set1 = [["mitomycin-A", "0mM"], ["PBS", "10mM"],
                        ["incubation", "10min"], ["temperature", "37"],
                        ["Organism", "H**o sapiens"]]
            kvp_set2 = [["mitomycin-A", "20mM"], ["PBS", "10mM"],
                        ["incubation", "10min"], ["temperature", "37"],
                        ["Organism", "H**o sapiens"]]
            kvp_set3 = [["mitomycin-A", "10microM"], ["PBS", "10mM"],
                        ["incubation", "5min"], ["temperature", "37"],
                        ["Organism", "H**o sapiens"]]
            kvp_set4 = [["mitomycin-A", "0mM"], ["PBS", "10mM"],
                        ["incubation", "5min"], ["temperature", "68"],
                        ["Organism", "H**o sapiens"]]

            images_kvp_order = [('A10.pattern1.tif', kvp_set1),
                                ('A10.pattern2.tif', kvp_set2),
                                ('A10.pattern5.tif', kvp_set2),
                                ('A1.pattern1.tif', kvp_set4),
                                ('A1.pattern2.tif', kvp_set1),
                                ('A5.pattern1.tif', kvp_set3),
                                ('A5.pattern2.tif', kvp_set2),
                                ('A5.pattern3.tif', kvp_set2),
                                ('A5.pattern4.tif', kvp_set2),
                                ('A6.pattern1.tif', kvp_set3),
                                ('A6.pattern2.tif', kvp_set2),
                                ('A6.pattern3.tif', kvp_set2),
                                ('B12.pattern1.tif', kvp_set1),
                                ('B12.pattern2.tif', kvp_set1),
                                ('B12.pattern3.tif', kvp_set1),
                                ('B12.pattern4.tif', kvp_set3),
                                ('B12.pattern5.tif', kvp_set3),
                                ('C4.pattern1.tif', kvp_set2),
                                ('C4.pattern2.tif', kvp_set2),
                                ('C4.pattern3.tif', kvp_set2),
                                ('C4.pattern4.tif', kvp_set2),
                                ('C4.pattern5.tif', kvp_set2),
                                ('C4.pattern6.tif', kvp_set2),
                                ('C4.pattern7.tif', kvp_set3),
                                ('C4.pattern8.tif', kvp_set3),
                                ('C4.pattern9.tif', kvp_set1),
                                ('C4.pattern.tif', kvp_set1),
                                ('E4.pattern5.tif', kvp_set3),
                                ('E4.pattern6.tif', kvp_set1),
                                ('E4.pattern7.tif', kvp_set3),
                                ('E4.pattern8.tif', kvp_set3),
                                ('E4.pattern9.tif', kvp_set1)]

            images_kvp_order = dict(images_kvp_order)
            for image in dataset.listChildren():

                if image.getName() in images_kvp_order:
                    print(images_kvp_order[image.getName()])

                    key_value_data = images_kvp_order[image.getName()]
                    map_ann = omero.gateway.MapAnnotationWrapper(conn)
                    # Use 'client' namespace to allow editing in Insight & web
                    namespace = omero.constants.metadata.NSCLIENTMAPANNOTATION
                    map_ann.setNs(namespace)
                    map_ann.setValue(key_value_data)
                    map_ann.save()
                    # NB: only link a client map annotation to a single object
                    image.linkAnnotation(map_ann)
                    print('linking to image', image.getName())
        except Exception as exc:
            print("Error while setting key-value pairs: %s" % str(exc))
        finally:
            conn.close()
Ejemplo n.º 2
0
def NEW_get_mean_zstacks_data(index, imageId, zsize, h, w, Data_F):

    conn = BlitzGateway('tbacoyannis',
                        'd33pl34rn1ng',
                        port=4064,
                        host='chinensis.polytechnique.fr')
    connected = conn.connect()

    #imageId = 451
    image = conn.getObject("Image", imageId)
    pixels = image.getPrimaryPixels()  # get raw pixels information

    Matrix = np.zeros((zsize, h, w, 3))

    x = Data_F.iloc[index].X - w / 2
    y = (Data_F.iloc[index].Y) - h / 2
    z = (Data_F.iloc[index].Pos)
    xtiles = np.ones(zsize, dtype=int) * x
    ytiles = np.ones(zsize, dtype=int) * y
    tilewidths = np.ones(zsize, dtype=int) * w
    tileheights = np.ones(zsize, dtype=int) * h
    tilestacks = zip(xtiles, ytiles, tilewidths, tileheights)

    zstacks = np.tile(np.arange(z - zsize / 2, z + zsize / 2 + 1), 3)

    tstacks = np.zeros(zsize, dtype=int)

    # left up
    x_l_u = x - w / 2
    y_l_u = y - h / 2

    xtiles_l_u = np.ones(zsize, dtype=int) * x_l_u
    ytiles_l_u = np.ones(zsize, dtype=int) * y_l_u
    tilewidths_l_u = np.ones(zsize, dtype=int) * w
    tileheights_l_u = np.ones(zsize, dtype=int) * h
    tilestacks_l_u = zip(xtiles_l_u, ytiles_l_u, tilewidths_l_u,
                         tileheights_l_u)
    zstacks_l_u = np.tile(np.arange(z - zsize / 2, z + zsize / 2 + 1), 3)
    tstacks_l_u = np.zeros(zsize, dtype=int)
    # right up
    x_r_u = x + w / 2
    y_r_u = y - h / 2

    xtiles_r_u = np.ones(zsize, dtype=int) * x_r_u
    ytiles_r_u = np.ones(zsize, dtype=int) * y_r_u
    tilewidths_r_u = np.ones(zsize, dtype=int) * w
    tileheights_r_u = np.ones(zsize, dtype=int) * h
    tilestacks_r_u = zip(xtiles_r_u, ytiles_r_u, tilewidths_r_u,
                         tileheights_r_u)
    zstacks_r_u = np.tile(np.arange(z - zsize / 2, z + zsize / 2 + 1), 3)
    tstacks_r_u = np.zeros(zsize, dtype=int)
    # left down
    x_l_d = x - w / 2
    y_l_d = y + h / 2

    xtiles_l_d = np.ones(zsize, dtype=int) * x_l_d
    ytiles_l_d = np.ones(zsize, dtype=int) * y_l_d
    tilewidths_l_d = np.ones(zsize, dtype=int) * w
    tileheights_l_d = np.ones(zsize, dtype=int) * h
    tilestacks_l_d = zip(xtiles_l_d, ytiles_l_d, tilewidths_l_d,
                         tileheights_l_d)
    zstacks_l_d = np.tile(np.arange(z - zsize / 2, z + zsize / 2 + 1), 3)
    tstacks_l_d = np.zeros(zsize, dtype=int)
    # right down
    x_r_d = x + w / 2
    y_r_d = y + h / 2

    xtiles_r_d = np.ones(zsize, dtype=int) * x_r_d
    ytiles_r_d = np.ones(zsize, dtype=int) * y_r_d
    tilewidths_r_d = np.ones(zsize, dtype=int) * w
    tileheights_r_d = np.ones(zsize, dtype=int) * h
    tilestacks_r_d = zip(xtiles_r_d, ytiles_r_d, tilewidths_r_d,
                         tileheights_r_d)
    zstacks_r_d = np.tile(np.arange(z - zsize / 2, z + zsize / 2 + 1), 3)
    tstacks_r_d = np.zeros(zsize, dtype=int)

    for c in range(0, 3):
        cstacks = np.ones(zsize, dtype=int) * c
        liste = zip(zstacks, cstacks, tstacks, tilestacks)
        pxobj = pixels.getTiles(liste)
        for i, p in enumerate(pxobj):
            Matrix[i, :, :, c] = p
            Norm_Matrix = (Matrix - np.min(Matrix)) * 1.0 / (np.max(Matrix) -
                                                             np.min(Matrix))
    M_mean = np.mean(Norm_Matrix, axis=0)

    for c in range(0, 3):
        cstacks = np.ones(zsize, dtype=int) * c
        liste_l_u = zip(zstacks_l_u, cstacks, tstacks_l_u, tilestacks_l_u)
        pxobj_l_u = pixels.getTiles(liste_l_u)
        for i, p in enumerate(pxobj_l_u):
            Matrix_l_u[i, :, :, c] = p
            Norm_Matrix_l_u = (Matrix_l_u - np.min(Matrix_l_u)) * 1.0 / (
                np.max(Matrix_l_u) - np.min(Matrix_l_u))
    M_mean_l_u = np.mean(Norm_Matrix_l_u, axis=0)

    for c in range(0, 3):
        cstacks = np.ones(zsize, dtype=int) * c
        liste_r_u = zip(zstacks_r_u, cstacks, tstacks_r_u, tilestacks_r_u)
        pxobj_r_u = pixels.getTiles(liste_r_u)
        for i, p in enumerate(pxobj_r_u):
            Matrix_r_u[i, :, :, c] = p
            Norm_Matrix_r_u = (Matrix_r_u - np.min(Matrix_r_u)) * 1.0 / (
                np.max(Matrix_r_u) - np.min(Matrix_r_u))
    M_mean_r_u = np.mean(Norm_Matrix_r_u, axis=0)

    for c in range(0, 3):
        cstacks = np.ones(zsize, dtype=int) * c
        liste_l_d = zip(zstacks_l_d, cstacks, tstacks_l_d, tilestacks_l_d)
        pxobj_l_d = pixels.getTiles(liste_l_d)
        for i, p in enumerate(pxobj_l_d):
            Matrix_l_d[i, :, :, c] = p
            Norm_Matrix_l_d = (Matrix_l_d - np.min(Matrix_l_d)) * 1.0 / (
                np.max(Matrix_l_d) - np.min(Matrix_l_d))
    M_mean_l_d = np.mean(Norm_Matrix_l_d, axis=0)

    for c in range(0, 3):
        cstacks = np.ones(zsize, dtype=int) * c
        liste_r_d = zip(zstacks_r_d, cstacks, tstacks_r_d, tilestacks_r_d)
        pxobj_r_d = pixels.getTiles(liste_r_d)
        for i, p in enumerate(pxobj_r_d):
            Matrix_r_d[i, :, :, c] = p
            Norm_Matrix_r_d = (Matrix_r_d - np.min(Matrix_r_d)) * 1.0 / (
                np.max(Matrix_r_d) - np.min(Matrix_r_d))
    M_mean_r_d = np.mean(Norm_Matrix_r_d, axis=0)

    conn._closeSession()

    return (M_mean, M_mean_l_u, M_mean_r_u, M_mean_l_d, M_mean_r_d)
# this script reads the image name and convert it into a tag. It works only with images.
data_types = [rstring('Image')]
client = scripts.client(
    "create_tag_from_image_name.py",
    ("Customised script for creating a tag from the image name"),
    #scripts.Long("File_Annotation"),
    # first parameter
    scripts.String(
        "Data_Type", optional=False, values=data_types, default="Image"),
    # second parameter
    scripts.List("IDs", optional=False).ofType(rlong(0)),

)
# we can now create our Blitz Gateway by wrapping the client object
conn = BlitzGateway(client_obj=client)
script_params = client.getInputs(unwrap=True)
print script_params


# get the 'IDs' parameter of the Images
ids = unwrap(client.getInput("IDs"))
images = conn.getObjects("Image", ids)

for i in images:
    image_name = i.name
    print "image name is", image_name

    tag_ann = omero.gateway.TagAnnotationWrapper(conn)
    tag_ann.setValue(image_name)
    tag_ann.save()
Ejemplo n.º 4
0
import numpy as np
from PIL import Image
from omero.gateway import BlitzGateway

saveDir = '.'
DatasetID = 3702

# save parameters
if not os.path.isdir(saveDir):
    os.makedirs(saveDir)

host = raw_input('host location')
un = raw_input('enter your OMERO username for')
pw = getpass.getpass('enter your OMERO password')

conn = BlitzGateway(un, pw, host=host, port=4064)
conn.connect()

roi_service = conn.getRoiService()

# get list of imageIds in dataset here.
dataset = conn.getObject('Dataset', DatasetID)

fileNames = []
for i in dataset.listChildren():
    img = conn.getObject('Image', i.getId())
    name = img.getName()
    print('loading image', name)
    fileNames.append(str.split(name, ' ')[0])

    saveFile = os.path.splitext(name)[0] + '_mask.npy'
Ejemplo n.º 5
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from omero.gateway import BlitzGateway
import omero
from omero.rtypes import *
from Connect_To_OMERO import USERNAME, PASSWORD, HOST, PORT
# create a connection
conn = BlitzGateway(USERNAME, PASSWORD, host="gretzky.openmicroscopy.org.uk", port=PORT)
conn.connect()
from random import random
from numpy import array
import math
datasetId = 2651

dataset = conn.getObject("Dataset", datasetId)

# first create our table...
# columns we want are: imageId, roiId, shapeId, theZ, theT, lineLength, shapetext.
columns = [
    omero.grid.LongColumn('imageId', '', []),
    omero.grid.RoiColumn('roidId', '', []),
    omero.grid.LongColumn('shapeId', '', []),
    omero.grid.LongColumn('theZ', '', []),
    omero.grid.LongColumn('theT', '', []),
    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)
Ejemplo n.º 6
0
def connect(hostname, username, password):
    conn = BlitzGateway(username, password, host=hostname, secure=True)
    conn.connect()
    conn.c.enableKeepAlive(60)
    return conn
Ejemplo n.º 7
0
def runAsScript():
    """
    The main entry point of the script. Gets the parameters from the scripting
    service, makes the figure and returns the output to the client.
    def __init__(self, name, optional = False, out = False, description =
    None, type = None, min = None, max = None, values = None)
    """

    formats = [rstring('JPEG'), rstring('PNG'), rstring('TIFF')]
    dataTypes = [rstring('Dataset'), rstring('Image')]

    client = scripts.client(
        'Thumbnail_Figure.py',
        """Export a figure of thumbnails, optionally sorted by tag.
See http://help.openmicroscopy.org/scripts.html""",
        scripts.String("Data_Type",
                       optional=False,
                       grouping="1",
                       description="The data you want to work with.",
                       values=dataTypes,
                       default="Dataset"),
        scripts.List("IDs",
                     optional=False,
                     grouping="2",
                     description="List of Dataset IDs or Image"
                     " IDs").ofType(rlong(0)),
        scripts.List("Tag_IDs",
                     grouping="3",
                     description="Group thumbnails by these tags."),
        scripts.Bool("Show_Untagged_Images",
                     grouping="3.1",
                     default=False,
                     description="If true (and you're sorting by tagIds) also"
                     " show images without the specified tags"),
        scripts.Long("Parent_ID",
                     grouping="4",
                     description="Attach figure to this Project (if datasetIds"
                     " above) or Dataset if imageIds. If not specifed, attach"
                     " figure to first dataset or image."),
        # this will be ignored if only a single ID in list - attach to
        # that object instead.
        scripts.Int(
            "Thumbnail_Size",
            grouping="5",
            min=10,
            max=250,
            default=100,
            description="The dimension of each thumbnail. Default is 100"),
        scripts.Int(
            "Max_Columns",
            grouping="5.1",
            min=1,
            default=10,
            description="The max number of thumbnail columns. Default is 10"),
        scripts.String("Format",
                       grouping="6",
                       description="Format to save image.",
                       values=formats,
                       default="JPEG"),
        scripts.String("Figure_Name",
                       grouping="6.1",
                       default='Thumbnail_Figure',
                       description="File name of figure to create"),
        version="4.3.0",
        authors=["William Moore", "OME Team"],
        institutions=["University of Dundee"],
        contact="*****@*****.**",
    )

    try:
        conn = BlitzGateway(client_obj=client)

        commandArgs = client.getInputs(unwrap=True)
        print commandArgs

        # Makes the figure and attaches it to Project/Dataset. Returns
        # FileAnnotationI object
        fileAnnotation, message = makeThumbnailFigure(conn, commandArgs)

        # Return message and file annotation (if applicable) to the client
        client.setOutput("Message", rstring(message))
        if fileAnnotation is not None:
            client.setOutput("File_Annotation", robject(fileAnnotation._obj))
    finally:
        client.closeSession()
Ejemplo n.º 8
0
def runAsScript():
    """
    The main entry point of the script. Gets the parameters from the scripting
    service, makes the figure and returns the output to the client.
    """

    dataTypes = [rstring('Image')]
    labels = [rstring('Image Name'), rstring('Datasets'), rstring('Tags')]
    algorithums = [rstring('Maximum Intensity'), rstring('Mean Intensity')]
    tunits = [
        rstring("SECS"),
        rstring("MINS"),
        rstring("HOURS"),
        rstring("MINS SECS"),
        rstring("HOURS MINS")
    ]
    formats = [rstring('JPEG'), rstring('PNG'), rstring('TIFF')]
    ckeys = COLOURS.keys()
    ckeys.sort()
    oColours = wrap(OVERLAY_COLOURS.keys())

    client = scripts.client(
        'Movie_Figure.py',
        """Export a figure of a movie, showing a row of frames for each \
chosen image.
NB: OMERO.insight client provides a nicer UI for this script under \
'Publishing Options'
See https://www.openmicroscopy.org/site/support/omero4/\
users/client-tutorials/insight/insight-export-figures.html""",

        # provide 'Data_Type' and 'IDs' parameters so that Insight
        # auto-populates with currently selected images.
        scripts.String("Data_Type",
                       optional=False,
                       grouping="01",
                       description="The data you want to work with.",
                       values=dataTypes,
                       default="Image"),
        scripts.List("IDs",
                     optional=False,
                     grouping="02",
                     description="List of Image IDs").ofType(rlong(0)),
        scripts.List(
            "T_Indexes",
            grouping="03",
            description="The time frames to display in the figure for each"
            " image").ofType(rint(0)),
        scripts.String(
            "Image_Labels",
            grouping="04",
            description="Label images with Image name (default) or datasets"
            " or tags",
            values=labels),
        scripts.Int(
            "Width",
            grouping="06",
            description="The max width of each image panel. Default is first"
            " image width",
            min=1),
        scripts.Int(
            "Height",
            grouping="07",
            description="The max height of each image panel. Default is first"
            " image height",
            min=1),
        scripts.Bool("Z_Projection", grouping="08", default=True),
        scripts.Int(
            "Z_Start",
            grouping="08.1",
            description="Projection range (if not specified, use defaultZ"
            " only - no projection)",
            min=0),
        scripts.Int(
            "Z_End",
            grouping="08.2",
            description="Projection range (if not specified or, use defaultZ"
            " only - no projection)",
            min=0),
        scripts.String("Algorithm",
                       grouping="08.3",
                       description="Algorithum for projection.",
                       values=algorithums),
        scripts.Int("Stepping",
                    grouping="08.4",
                    description="The Z increment for projection.",
                    default=1,
                    min=1),
        scripts.Bool("Show_Scalebar", grouping="10", default=True),
        scripts.Int(
            "Scalebar_Size",
            grouping="10.1",
            description="Scale bar size in microns. Only shown if image has"
            " pixel-size info.",
            min=1),
        scripts.String("Scalebar_Colour",
                       grouping="10.2",
                       description="The colour of the scalebar.",
                       default='White',
                       values=oColours),
        scripts.String("Format",
                       grouping="11",
                       description="Format to save image.",
                       values=formats,
                       default='JPEG'),
        scripts.String("Figure_Name",
                       grouping="12",
                       description="File name of the figure to save."),
        scripts.String("Time_Units",
                       grouping="13",
                       description="The units to use for time display",
                       values=tunits),
        scripts.Int(
            "Max_Columns",
            grouping="04.1",
            default=10,
            description="The maximum number of columns in the figure, for"
            " movie frames.",
            min=1),
        version="4.3.0",
        authors=["William Moore", "OME Team"],
        institutions=["University of Dundee"],
        contact="*****@*****.**",
    )

    try:
        commandArgs = {}
        conn = BlitzGateway(client_obj=client)

        for key in client.getInputKeys():
            if client.getInput(key):
                commandArgs[key] = client.getInput(key, unwrap=True)

        print commandArgs

        # Makes the figure and attaches it to Image. Returns the id of the
        # originalFileLink child. (ID object, not value)
        fileAnnotation, message = movieFigure(conn, commandArgs)

        # Return message and file annotation (if applicable) to the client
        client.setOutput("Message", rstring(message))
        if fileAnnotation:
            client.setOutput("File_Annotation", robject(fileAnnotation._obj))
    finally:
        client.closeSession()
Ejemplo n.º 9
0
def run_script():
    """
    The main entry point of the script, as called by the client via the
    scripting service, passing the required parameters.
    """
    data_types = [rstring('Dataset'), rstring('Image')]

    client = scripts.client(
        'Images_From_ROIs.py',
        """Crop an Image using Rectangular ROIs, to create new Images.
ROIs that extend across Z and T will crop according to the Z and T limits
of each ROI. If NO Z set, use all Z planes. If NO T set, use all T planes.
If you choose to 'make an image stack' from all the ROIs, the script \
will create a single new Z-stack image with a single plane from each ROI.
ROIs that are 'Big', typically over 3k x 3k pixels will create 'tiled'
images using the specified tile size.
""",

        scripts.String(
            "Data_Type", optional=False, grouping="1",
            description="Choose Images via their 'Dataset' or directly by "
            " 'Image' IDs.", values=data_types, default="Image"),

        scripts.List(
            "IDs", optional=False, grouping="2",
            description="List of Dataset IDs or Image IDs to "
            " process.").ofType(rlong(0)),

        scripts.String(
            "Container_Name", grouping="3",
            description="Option: put Images in new Dataset with this name"
            " OR use this name for new Image stacks, if 'Make_Image_Stack')",
            default="From_ROIs"),

        scripts.Bool(
            "Make_Image_Stack", grouping="4", default=False,
            description="If true, make a single Image (stack) from all the"
            " ROIs of each parent Image"),

        scripts.Int(
            "Tile_Size", optional=False, grouping="5",
            min=50, max=2500,
            description="If the new image is large and tiled, "
            "create tiles of this width & height", default=1024),

        version="5.3.0",
        authors=["William Moore", "OME Team"],
        institutions=["University of Dundee"],
        contact="*****@*****.**",
    )

    try:
        parameter_map = client.getInputs(unwrap=True)

        # create a wrapper so we can use the Blitz Gateway.
        conn = BlitzGateway(client_obj=client)

        robj, message = make_images_from_rois(conn, parameter_map)

        client.setOutput("Message", rstring(message))
        if robj is not None:
            client.setOutput("Result", robject(robj))

    finally:
        client.closeSession()
Ejemplo n.º 10
0
import os
import getpass
import threading
import time
import pandas as pd
from PIL import Image
import xml.etree.ElementTree as ET
#root = ET.fromstring(imageDesc)

# initialise OMERO
USER = getpass.getuser()
print 'username: '******'Enter password:'******'omero1.bioch.ox.ac.uk'

conn = BlitzGateway(USER, PASS, host=HOST, port=4064)
conn.connect()
conn.SERVICE_OPTS.setOmeroGroup(-1)

print 'login successful'


# keep connection to OMERO alive
def keep_connection_alive():
    while True:
        conn.keepAlive()
        time.sleep(60)


th_ka = threading.Thread(target=keep_connection_alive)
th_ka.daemon = True
Ejemplo n.º 11
0
def connect(hostname, username, password):
    conn = BlitzGateway(username, password, host=hostname, secure=True)
    conn.connect()
    return conn
Ejemplo n.º 12
0
def runAsScript():

    dataTypes = [rstring('Image')]

    models_path=os.path.join(SCRIPT_PATH, "sample/classifiers/")
    systems=['carver']

    segmentationModel = []
    for file in os.listdir(models_path):
        if file.endswith(".model"):
            segmentationModel.append(str(os.path.join(models_path,file)))

    client = scripts.client('weka_tfmq.py', """Segment a dataset using Random Forest and a known classifier""",

    scripts.String("Data_Type", optional=False, grouping="1",
        description="Pick Images by 'Image' ID or by the ID of their 'Dataset'", values=dataTypes, default="Image"),

    scripts.List("IDs", optional=False, grouping="1.1",
        description="List of Dataset IDs or Image IDs to process.").ofType(rlong(0)),

    scripts.String("Segmentation_model", optional=False, grouping="2",
        description="Select model", values=segmentationModel, default=segmentationModel[0]),

    scripts.String("System", optional=False, grouping="3",
        description="Select the system", values=systems, default=systems[0]),

    scripts.String("Wall_time", grouping="3.1",
        description="Wall time", default='0:30:00'),

    scripts.String("Private_memory", grouping="3.2",
        description="Private memory", default='4GB'),

    scripts.Bool("Big_memory_nodes", grouping="3.2.1",
        description="Big memory nodes", default='False'),

    scripts.String("Nodes", grouping="3.3",
        description="Nodes", default='1'),

    scripts.String("PPN", grouping="3.4",
        description="PPN", default='5'),

    version = "0",
    authors = ["Joaquin Correa", "Data and Analytics services"],
    institutions = ["National Energy Research Scientific Computing Center (NERSC)"],
    contact = "*****@*****.**",
    )

    try:
        session = client.getSession();

        scriptParams = {}
        for key in client.getInputKeys():
            if client.getInput(key):
                scriptParams[key] = client.getInput(key, unwrap=True)

        conn = BlitzGateway(client_obj=client)

        admin = conn.getAdminService()
        uuid = admin.getEventContext().sessionUuid
        weka_segmentation(conn, scriptParams, uuid)

    finally:
        client.closeSession()
Ejemplo n.º 13
0
    def testGetROICount(self):
        """
        Test no ROI couting method
        """

        # Create group with two member and one image
        group = self.new_group(perms="rwrw--")
        owner = self.new_client(group=group)  # Owner of share
        member = self.new_client(group=group)  # Member of group
        img = self.createTestImage(session=owner.sf)

        from omero.gateway import ImageWrapper, BlitzGateway
        conn = BlitzGateway(client_obj=owner)

        # Test no ROI count
        wrapper = ImageWrapper(conn, img)
        assert wrapper.getROICount() == 0

        # Test ROI shape
        roi1 = omero.model.RoiI()
        roi1.addShape(omero.model.RectangleI())
        roi1.addShape(omero.model.RectangleI())
        roi1.setImage(img)
        roi1 = owner.sf.getUpdateService().saveAndReturnObject(roi1)

        roi2 = omero.model.RoiI()
        roi2.addShape(omero.model.RectangleI())
        roi2.addShape(omero.model.EllipseI())
        roi2.setImage(img)
        roi2 = owner.sf.getUpdateService().saveAndReturnObject(roi2)

        wrapper = ImageWrapper(conn, img)
        assert wrapper.getROICount() == 2
        assert wrapper.getROICount("Rectangle") == 2
        assert wrapper.getROICount("Ellipse") == 1
        assert wrapper.getROICount("Line") == 0
        assert wrapper.getROICount(["Rectangle", "Ellipse"]) == 2

        # Test ROI permissions
        roi3 = omero.model.RoiI()
        roi3.addShape(omero.model.EllipseI())
        roi3.setImage(img)
        roi3 = member.sf.getUpdateService().saveAndReturnObject(roi3)
        assert wrapper.getROICount() == 3
        assert wrapper.getROICount(filterByCurrentUser=True) == 2
        assert wrapper.getROICount("Ellipse") == 2
        assert wrapper.getROICount("Ellipse", None) == 2
        assert wrapper.getROICount("Ellipse", 1) == 1
        assert wrapper.getROICount("Ellipse", True) == 1
        assert wrapper.getROICount("Rectangle") == 2
        assert wrapper.getROICount("Rectangle", None) == 2
        assert wrapper.getROICount("Rectangle", 1) == 2
        assert wrapper.getROICount("Rectangle", True) == 2

        # Member gateway
        conn = BlitzGateway(client_obj=member)
        wrapper = ImageWrapper(conn, img)
        assert wrapper.getROICount() == 3
        assert wrapper.getROICount(filterByCurrentUser=True) == 1
        assert wrapper.getROICount("Ellipse") == 2
        assert wrapper.getROICount("Ellipse", None) == 2
        assert wrapper.getROICount("Ellipse", 1) == 1
        assert wrapper.getROICount("Ellipse", True) == 1
        assert wrapper.getROICount("Rectangle") == 2
        assert wrapper.getROICount("Rectangle", None) == 2
        assert wrapper.getROICount("Rectangle", 1) == 0
        assert wrapper.getROICount("Rectangle", True) == 0
Ejemplo n.º 14
0
src_dir = os.path.abspath(os.path.dirname(__file__))
frame_dir = os.path.join(src_dir, '..', 'temp', 'sampattavanich_2014',
                         'frames')

HOST = 'lincs-omero.hms.harvard.edu'
PORT = 4064
GROUP = 'Public'

# Read username and password.
print "Connecting to OMERO server: %s:%d" % (HOST, PORT)
username = getpass._raw_input('Username: '******'s needed.
# -JLM 2013/12/04)
try:
    group = next(g for g in conn.listGroups() if g.getName() == GROUP)
except StopIteration:
    print >> sys.stderr, "Error: could not find group '%s'" % GROUP
Ejemplo n.º 15
0
def run_script():
    """
    The main entry point of the script, as called by the client via the
    scripting service, passing the required parameters.
    """

    data_types = [rstring('Image')]
    labels = [rstring('Image Name'), rstring('Datasets'), rstring('Tags')]
    algorithms = [rstring('Maximum Intensity'), rstring('Mean Intensity')]
    roi_label = """Specify an ROI to pick by specifying its shape label. \
'FigureROI' by default, (not case sensitive). If matching ROI not found, use \
any ROI."""
    formats = [rstring('JPEG'), rstring('PNG'), rstring('TIFF')]
    ckeys = COLOURS.keys()
    ckeys.sort()
    o_colours = wrap(OVERLAY_COLOURS.keys())

    client = scripts.client(
        'ROI_Split_Figure.py',
        """Create a figure of an ROI region as separate zoomed split-channel \
panels.
NB: OMERO.insight client provides a nicer UI for this script under \
'Publishing Options'
See http://help.openmicroscopy.org/publish.html#figures""",

        # provide 'Data_Type' and 'IDs' parameters so that Insight
        # auto-populates with currently selected images.
        scripts.String("Data_Type",
                       optional=False,
                       grouping="01",
                       description="The data you want to work with.",
                       values=data_types,
                       default="Image"),
        scripts.List("IDs",
                     optional=False,
                     grouping="02",
                     description="List of Dataset IDs or Image IDs").ofType(
                         rlong(0)),
        scripts.Map("Channel_Names",
                    grouping="03",
                    description="Map of index: channel name for All channels"),
        scripts.Bool(
            "Merged_Names",
            grouping="04",
            description="If true, label the merged panel with channel names."
            " Otherwise label with 'Merged'"),
        scripts.List(
            "Split_Indexes",
            grouping="05",
            description="List of the channels in the split view panels"),
        scripts.Bool("Split_Panels_Grey",
                     grouping="06",
                     description="If true, all split panels are grayscale"),
        scripts.Map(
            "Merged_Colours",
            grouping="07",
            description="Map of index:int colors for each merged channel."
            " Otherwise use existing color settings"),
        scripts.Int("Width",
                    grouping="08",
                    description="Max width of each image panel",
                    min=1),
        scripts.Int("Height",
                    grouping="09",
                    description="The max height of each image panel",
                    min=1),
        scripts.String(
            "Image_Labels",
            grouping="10",
            description="Label images with the Image's Name or its Datasets"
            " or Tags",
            values=labels),
        scripts.String("Algorithm",
                       grouping="11",
                       description="Algorithm for projection.",
                       values=algorithms),
        scripts.Int(
            "Stepping",
            grouping="12",
            description="The Z-plane increment for projection. Default is 1",
            min=1),
        scripts.Int(
            "Scalebar",
            grouping="13",
            description="Scale bar size in microns. Only shown if image has"
            " pixel-size info.",
            min=1),
        scripts.String("Format",
                       grouping="14",
                       description="Format to save image e.g 'PNG'.",
                       values=formats,
                       default='JPEG'),
        scripts.String("Figure_Name",
                       grouping="15",
                       description="File name of the figure to save."),
        scripts.String("Overlay_Colour",
                       grouping="16",
                       description="The color of the scale bar.",
                       default='White',
                       values=o_colours),
        scripts.Float(
            "ROI_Zoom",
            grouping="17",
            description="How much to zoom the ROI e.g. x 2. If 0 then zoom"
            " roi panel to fit",
            min=0),
        scripts.String("ROI_Label", grouping="18", description=roi_label),
        version="4.3.0",
        authors=["William Moore", "OME Team"],
        institutions=["University of Dundee"],
        contact="*****@*****.**",
    )
    try:
        conn = BlitzGateway(client_obj=client)

        command_args = client.getInputs(unwrap=True)

        # call the main script, attaching resulting figure to Image. Returns
        # the id of the originalFileLink child. (ID object, not value)
        file_annotation, message = roi_figure(conn, command_args)

        # Return message and file annotation (if applicable) to the client
        client.setOutput("Message", rstring(message))
        if file_annotation is not None:
            client.setOutput("File_Annotation", robject(file_annotation._obj))

    finally:
        client.closeSession()
from Figure_To_Pdf import TiffExport
from PIL import Image
import logging

# specify output directory
outdir = ('/usr/people/bioc1301/src/Zegami_scripts/Zegami_collection_March_2020')
zegami_csv = ('zegami.csv')
logging.basicConfig(filename='zegami.log',level=logging.DEBUG)

# specify a list of figureIDs 
figure_IDs = '/usr/people/bioc1301/src/Zegami_scripts/fig_IDs.csv'
figure_IDs = open(figure_IDs).read().splitlines()

# BlitzGateway details to initialise OMERO
PASS = getpass.getpass("Enter Password:"******"figure_id","Gene","Collection", "Compartment","Probe"])

    for fig in conn.getObjects('FileAnnotation',attributes={'ns': 'omero.web.figure.json'}):
        figure_id = ('%d' % (fig.getId()))	
	#if figure_id in figure_IDs:
	filename = fig.getFileName()
        if 'zegami1' not in filename and 'zegami2' not in filename:
	    continue
Ejemplo n.º 17
0
    def test_chgrp_old_container(self, dataset, credentials):
        """
        Tests Admin moving user's Dataset to their Private group and
        linking it to an existing Project there.
        Bug from https://github.com/openmicroscopy/openmicroscopy/pull/3420
        """

        django_client = self.get_django_client(credentials)
        # user creates project in their target group
        project = ProjectI()
        projectName = "chgrp-target-%s" % self.client.getSessionId()
        project.name = rstring(projectName)
        ctx = {"omero.group": str(self.group2.id.val)}
        project = self.sf.getUpdateService().saveAndReturnObject(project, ctx)
        request_url = reverse('chgrp')

        data = {
            "group_id": self.group2.id.val,
            "Dataset": dataset.id.val,
            "target_id": "project-%s" % project.id.val,
        }
        data = _csrf_post_response_json(django_client, request_url, data)
        expected = {"update": {"childless": {"project": [],
                                             "orphaned": False,
                                             "dataset": []},
                               "remove": {"project": [],
                                          "plate": [],
                                          "screen": [],
                                          "image": [],
                                          "dataset": [dataset.id.val]}}}
        assert data == expected

        activities_url = reverse('activities_json')

        data = _get_response_json(django_client, activities_url, {})

        # Keep polling activities until no jobs in progress
        while data['inprogress'] > 0:
            time.sleep(0.5)
            data = _get_response_json(django_client, activities_url, {})

        # individual activities/jobs are returned as dicts within json data
        for k, o in data.items():
            if hasattr(o, 'values'):    # a dict
                if 'report' in o:
                    print o['report']
                assert o['status'] == 'finished'
                assert o['job_name'] == 'Change group'
                assert o['to_group_id'] == self.group2.id.val

        # Dataset should now be in new group, contained in Project
        conn = BlitzGateway(client_obj=self.client)
        userId = conn.getUserId()
        conn.SERVICE_OPTS.setOmeroGroup('-1')
        d = conn.getObject("Dataset", dataset.id.val)
        assert d is not None
        assert d.getDetails().group.id.val == self.group2.id.val
        p = d.getParent()
        assert p is not None
        assert p.getName() == projectName
        # Project owner should be current user
        assert p.getDetails().owner.id.val == userId
        assert p.getId() == project.id.val
Ejemplo n.º 18
0
def runScript():
    """
    The main entry point of the script, as called by the client via the
    scripting service, passing the required parameters.
    """

    dataTypes = [rstring('Image')]
    axes = [rstring('Y'), rstring('X')]

    client = scripts.client(
        'ImageJ_Processing.py',
        """Does ImageJ 'Rotation Projection' macro processing, creating a new\
Image in OMERO""",

        scripts.String(
            "Data_Type", optional=False, grouping="1",
            description="The data you want to work with.", values=dataTypes,
            default="Image"),

        scripts.List(
            "IDs", optional=False, grouping="2",
            description="List of Dataset IDs or Image IDs").ofType(rlong(0)),

        scripts.String(
            "Rotation_Axis", optional=False, grouping="3",
            description="3D rotation over Y or X axis", values=axes,
            default="Y"),

        scripts.Bool(
            "Use_Raw_Data", grouping="4", default=False,
            description="Convert raw pixel data to Tiff for processing?"
            " Otherwise use rendered data"),

        scripts.Int(
            "Channel_To_Analyse", grouping="4.1", default=1, min=1,
            description="This channel will be analysed as greyscale Tiffs"),

        scripts.Bool(
            "Analyse_ROI_Regions", grouping="5", default=False,
            description="Use Rectangle ROIs to define regions to analyse."
            " By default analyse whole image"),


        authors=["William Moore", "Asmi Shah"],
        institutions=["University of Dundee", "KIT"],
        contact="*****@*****.**",
    )

    try:
        scriptParams = {}

        conn = BlitzGateway(client_obj=client)

        # process the list of args above.
        for key in client.getInputKeys():
            if client.getInput(key):
                scriptParams[key] = client.getInput(key, unwrap=True)
        print scriptParams

        robj, message = rotation_proj_stitch(conn, scriptParams)

        client.setOutput("Message", rstring(message))
        if robj is not None:
            client.setOutput("Result", robject(robj))

    finally:
        client.closeSession()
Ejemplo n.º 19
0
def run_script():

    dataTypes = [rstring('Project'), rstring('Dataset')]
    # TODO: enable attaching to images
    dataTypes_attach = [rstring('Dataset'), rstring('Project')]
    """
    The main entry point of the script, as called by the client via the
    scripting service, passing the required parameters.
    """
    client = scripts.client(
        'Remote_Import.py',
        """Remote import from dedicated workstations:

        * Import the content of the OMERO_ImportData/<username>/ folder on the selected workstation.
        * Appends files with the specified suffix to the Project or Dataset.
        * The scanned subfolder depth is 10
        ---------------------------------------------------------------
        INPUT:
        ---------------------------------------------------------------
        Select PROJECT as TARGET for import : : A Dataset object is created for each subdirectory on OMERO_ImportData/<username>/

        Select DATASET as TARGET for import : : All images (also images in subdirectories) are imported into this Dataset


        """,
        scripts.String(
            PARAM_WS,
            optional=False,
            grouping="1",
            description="Choose a workstation where you want to import from",
            values=WORKSTATION_NAMES),
        scripts.String(PARAM_DATATYPE,
                       optional=True,
                       grouping="2",
                       description="Choose kind of destination object.",
                       values=dataTypes),
        scripts.Long(
            PARAM_ID,
            optional=False,
            grouping="3",
            description=
            "ID of destination object. Please select only ONE object."),
        scripts.Bool(
            PARAM_SKIP_EXISTING,
            grouping="4",
            description=
            "skip files that are already uploaded (checked 'import from' path).",
            default=False),
        scripts.Bool(PARAM_ATTACH,
                     grouping="5",
                     description="Attach containing non image files",
                     default=False),
        scripts.String(PARAM_DEST_ATTACH,
                       grouping="5.1",
                       description="Object to that should be attach",
                       values=dataTypes_attach,
                       default="Dataset"),
        scripts.String(
            PARAM_ATTACH_FILTER,
            grouping="5.2",
            description=
            "Filter files by given file extension (for example txt, pdf). Separated by ','."
        ),
        namespaces=[omero.constants.namespaces.NSDYNAMIC],
        version="1.1.0",
        authors=["Susanne Kunis", "CellNanOs"],
        institutions=["University of Osnabrueck"],
        contact="*****@*****.**",
    )  # noqa

    try:
        params = client.getInputs(unwrap=True)
        if os.path.exists(MOUNT_PATH):
            conn = BlitzGateway(client_obj=client)

            datapath = checkWorkstation(conn, params.get(PARAM_WS), MOUNT_PATH,
                                        conn.getUser().getName())
            if datapath:
                robj, message = remoteImport(conn, params, datapath)
            else:
                message = "No data available on %s for user" % (
                    params.get(PARAM_WS))
                robj = None

            client.setOutput("Message", rstring(message))
            if robj is not None:
                client.setOutput("Result", robject(robj._obj))
        else:
            client.setOutput(
                "ERROR", rstring("No such Mount directory: %s" % MOUNT_PATH))
    finally:
        client.closeSession()
Ejemplo n.º 20
0
def run_script():
    # Script definition
    # Script name, description and 2 parameters are defined here.
    # These parameters will be recognised by the Insight and web clients and
    # populated with the currently selected Image(s)
    # A username and password will be entered too.
    # this script takes Images or Datasets
    message = "Script to export a file to another omero server."
    data_types = [rstring('Dataset'), rstring('Image')]

    omero_config = check_omero_config()

    has_privs = omero_config["has_privs"]
    scripts_timeout = omero_config["scripts_timeout"]
    scripts_timeout = (scripts_timeout / 1000) / 60

    if has_privs == True:
        message = "\n\n".join([
            message, "You are running this script with"
            " administrator privileges and the omero.scripts.timeout"
            " configuration parameter is {}"
            " minutes.".format(scripts_timeout)
        ])
    else:
        message = "\n\n".join([
            message, "Please note, you are running this script as a"
            " non-administrator so we are unable to provide an accurate"
            " value for the omero.scripts.timeout configuration"
            " parameter. The default of {} minutes is assumed,"
            " though you should check with your OMERO"
            " administrator.".format(scripts_timeout)
        ])

    image_formats = [rstring('Hypercube'), rstring('TIFF')]

    client = scripts.client(
        "Export_to_other_omero.py",
        message,
        scripts.String("Data_Type",
                       optional=False,
                       values=data_types,
                       default="Image",
                       description="The data you want to work with.",
                       grouping="1.1"),
        scripts.List("IDs",
                     optional=False,
                     grouping="1.2",
                     description="List of Dataset IDs or Image IDs").ofType(
                         rlong(0)),

        # Username
        scripts.String("Username", optional=False, grouping="2.1"),
        scripts.String("Password", optional=False, grouping="2.2"),
        scripts.String("Image_Format",
                       optional=False,
                       values=image_formats,
                       default="Hypercube",
                       grouping="3.1"),
        scripts.Bool("Include_Annotations", grouping="3.2", default=True))

    try:
        # we can now create our local Blitz Gateway by wrapping the client.
        local_conn = BlitzGateway(client_obj=client)
        script_params = client.getInputs(unwrap=True)

        message = copy_to_remote_omero(client, local_conn, script_params)
    finally:
        client.setOutput("Message: ", rstring(message))

        # Return some value(s).
        # Here, we return anything useful the script has produced.
        # NB: The Insight and web clients will display the "Message" output.
        # msg = "Script ran with Image ID: %s, Name: %s and \nUsername: %s"\
        #       % (image_id, image.getName(), username)
        # client.setOutput("Message", rstring(msg))
        client.closeSession()

        try:
            local_conn.close()
        except Exception as e:
            msg = "Error closing local connection: %s" % (e)
Ejemplo n.º 21
0
def runAsScript():
    """
    The main entry point of the script, as called by the client via the scripting service, passing the required parameters. 
    """
    printDuration(False)  # start timer

    ckeys = COLOURS.keys()
    ckeys.sort()
    cOptions = [rstring(col) for col in ckeys]
    dataTypes = [rstring('Dataset'), rstring('Image')]
    firstDim = [rstring('Time'), rstring('Channel'), rstring('Z')]
    extraDims = [
        rstring(''),
        rstring('Time'),
        rstring('Channel'),
        rstring('Z')
    ]
    channelRegs = [rstring(r) for r in channelRegexes.keys()]
    zRegs = [rstring(r) for r in zRegexes.keys()]
    tRegs = [rstring(r) for r in timeRegexes.keys()]

    client = scripts.client(
        'Combine_Images.py',
        """Combine several single-plane images (or Z-stacks) into one with 
greater Z, C, T dimensions.
See http://www.openmicroscopy.org/site/support/omero4/users/client-tutorials/insight/insight-util-scripts.html""",
        scripts.String(
            "Data_Type",
            optional=False,
            grouping="1",
            description=
            "Use all the images in specified 'Datasets' or choose individual 'Images'.",
            values=dataTypes,
            default="Image"),
        scripts.List(
            "IDs",
            optional=False,
            grouping="2",
            description="List of Dataset IDs or Image IDs to combine.").ofType(
                rlong(0)),
        scripts.String(
            "Filter_Names",
            grouping="2.1",
            description="Filter the images by names that contain this value"),
        scripts.Bool(
            "Auto_Define_Dimensions",
            grouping="3",
            default=True,
            description=
            """Choose new dimensions with respect to the order of the input images. See URL above."""
        ),
        scripts.String(
            "Channel_Name_Pattern",
            grouping="3.1",
            default=DEFAULT_C_REGEX,
            values=channelRegs,
            description="""Auto-pick images by channel in the image name"""),
        scripts.String(
            "Z_Name_Pattern",
            grouping="3.2",
            default=DEFAULT_Z_REGEX,
            values=zRegs,
            description="""Auto-pick images by Z-index in the image name"""),
        scripts.String(
            "Time_Name_Pattern",
            grouping="3.3",
            default=DEFAULT_T_REGEX,
            values=tRegs,
            description="""Auto-pick images by T-index in the image name"""),
        scripts.Bool(
            "Manually_Define_Dimensions",
            grouping="4",
            default=False,
            description=
            """Choose new dimensions with respect to the order of the input images. See URL above."""
        ),
        scripts.String("Dimension_1",
                       grouping="4.1",
                       description="The first Dimension to change",
                       values=firstDim),
        scripts.String(
            "Dimension_2",
            grouping="4.2",
            values=extraDims,
            default="",
            description=
            "The second Dimension to change. Only specify this if combining multiple dimensions."
        ),
        scripts.String(
            "Dimension_3",
            grouping="4.3",
            values=extraDims,
            default="",
            description=
            "The third Dimension to change. Only specify this if combining multiple dimensions."
        ),
        scripts.Int("Size_Z",
                    grouping="4.4",
                    description="Number of Z planes in new image",
                    min=1),
        scripts.Int("Size_C",
                    grouping="4.5",
                    description="Number of channels in new image",
                    min=1),
        scripts.Int("Size_T",
                    grouping="4.6",
                    description="Number of time-points in new image",
                    min=1),
        scripts.List("Channel_Colours",
                     grouping="7",
                     description="List of Colours for channels.",
                     default="White",
                     values=cOptions).ofType(rstring("")),
        scripts.List(
            "Channel_Names",
            grouping="8",
            description="List of Names for channels in the new image."),
        version="4.2.0",
        authors=["William Moore", "OME Team"],
        institutions=["University of Dundee"],
        contact="*****@*****.**",
    )

    try:
        session = client.getSession()

        # process the list of args above.
        parameterMap = {}
        for key in client.getInputKeys():
            if client.getInput(key):
                parameterMap[key] = client.getInput(key).getValue()

        print parameterMap

        conn = BlitzGateway(client_obj=client)

        # create the combined image
        images, message = combineImages(conn, parameterMap)

        client.setOutput("Message", rstring(message))
        if images:
            if len(images) == 1:
                client.setOutput("Combined_Image", robject(images[0]))
            elif len(images) > 1:
                client.setOutput("First_Image", robject(images[0]))

    finally:
        client.closeSession()
        printDuration()
Ejemplo n.º 22
0
def run_script():
    """The main entry point of the script, as called by the client."""
    data_types = [
        rstring(s) for s in ['Screen', 'Plate', 'Project', 'Dataset', 'Image']
    ]

    client = scripts.client(
        'Batch_ROI_Export.py',
        """Export ROI intensities for selected Images as a CSV file.""",
        scripts.String("Data_Type",
                       optional=False,
                       grouping="1",
                       description="The data you want to work with.",
                       values=data_types,
                       default="Image"),
        scripts.List("IDs",
                     optional=False,
                     grouping="2",
                     description="List of Dataset IDs or Image IDs").ofType(
                         rlong(0)),
        scripts.List(
            "Channels",
            grouping="3",
            default=[1, 2, 3, 4],
            description="Indices of Channels to measure intensity.").ofType(
                rint(0)),
        scripts.Bool("Export_All_Planes",
                     grouping="4",
                     description=("Export all Z and T planes for shapes "
                                  "where Z and T are not set?"),
                     default=False),
        scripts.Bool("Include_Points_Coords",
                     grouping="5",
                     description=("Export the Points string for Polygons "
                                  "and Polylines. Disable this to reduce the "
                                  "size of the CSV file when exporting large "
                                  "numbers of ROIs"),
                     default=True),
        scripts.String("File_Name",
                       grouping="6",
                       default=DEFAULT_FILE_NAME,
                       description="Name of the exported CSV file"),
        authors=["William Moore", "OME Team"],
        institutions=["University of Dundee"],
        contact="*****@*****.**",
    )

    try:
        conn = BlitzGateway(client_obj=client)

        script_params = client.getInputs(unwrap=True)
        log("script_params:")
        log(script_params)

        # call the main script
        result = batch_roi_export(conn, script_params)

        # Return message and file_annotation to client
        if result is None:
            message = "No images found"
        else:
            file_ann, message = result
            if file_ann is not None:
                client.setOutput("File_Annotation", robject(file_ann._obj))

        client.setOutput("Message", rstring(message))

    finally:
        client.closeSession()
Ejemplo n.º 23
0
def runAsScript():
    """
    The main entry point of the script, as called by the client via the
    scripting service, passing the required parameters.
    """

    dataTypes = [rstring('Dataset')]
    firstAxis = [rstring('column'), rstring('row')]
    rowColNaming = [rstring('letter'), rstring('number')]

    client = scripts.client(
        'Dataset_To_Plate.py',
        """Take a Dataset of Images and put them in a new Plate, \
arranging them into rows or columns as desired.
Optionally add the Plate to a new or existing Screen.
See http://help.openmicroscopy.org/utility-scripts.html""",
        scripts.String(
            "Data_Type",
            optional=False,
            grouping="1",
            description="Choose source of images (only Dataset supported)",
            values=dataTypes,
            default="Dataset"),
        scripts.List("IDs",
                     optional=False,
                     grouping="2",
                     description="List of Dataset IDs to convert to new"
                     " Plates.").ofType(rlong(0)),
        scripts.String(
            "Filter_Names",
            grouping="2.1",
            description="Filter the images by names that contain this value"),
        scripts.String(
            "First_Axis",
            grouping="3",
            optional=False,
            default='column',
            values=firstAxis,
            description="""Arrange images accross 'column' first or down"
            " 'row'"""),
        scripts.Int(
            "First_Axis_Count",
            grouping="3.1",
            optional=False,
            default=12,
            description="Number of Rows or Columns in the 'First Axis'",
            min=1),
        scripts.String(
            "Column_Names",
            grouping="4",
            optional=False,
            default='number',
            values=rowColNaming,
            description="""Name plate columns with 'number' or 'letter'"""),
        scripts.String(
            "Row_Names",
            grouping="5",
            optional=False,
            default='letter',
            values=rowColNaming,
            description="""Name plate rows with 'number' or 'letter'"""),
        scripts.String(
            "Screen",
            grouping="6",
            description="Option: put Plate(s) in a Screen. Enter Name of new"
            " screen or ID of existing screen"
            ""),
        scripts.Bool(
            "Remove_From_Dataset",
            grouping="7",
            default=True,
            description="Remove Images from Dataset as they are added to"
            " Plate"),
        version="4.3.2",
        authors=["William Moore", "OME Team"],
        institutions=["University of Dundee"],
        contact="*****@*****.**",
    )

    try:
        scriptParams = client.getInputs(unwrap=True)
        print scriptParams

        # wrap client to use the Blitz Gateway
        conn = BlitzGateway(client_obj=client)

        # convert Dataset(s) to Plate(s). Returns new plates or screen
        newObj, message = datasets_to_plates(conn, scriptParams)

        client.setOutput("Message", rstring(message))
        if newObj:
            client.setOutput("New_Object", robject(newObj))

    finally:
        client.closeSession()
Ejemplo n.º 24
0
 def _clientconn(self, args):
     client = self.ctx.conn(args)
     conn = BlitzGateway(client_obj=client)
     return client, conn
Ejemplo n.º 25
0
def runAsScript():
    """
    The main entry point of the script, as called by the client via the scripting service, passing the required parameters. 
    """

    dataTypes = [rstring('Image')]
    labels = [rstring('Image Name'), rstring('Datasets'), rstring('Tags')]
    algorithums = [rstring('Maximum Intensity'), rstring('Mean Intensity')]
    formats = [rstring('JPEG'), rstring('PNG')]
    ckeys = COLOURS.keys()
    ckeys.sort()
    cOptions = wrap(ckeys)
    oColours = wrap(OVERLAY_COLOURS.keys())

    client = scripts.client(
        'Split_View_Figure.py',
        """Create a figure of split-view images.
NB: OMERO.insight client provides a nicer UI for this script under 'Publishing Options'
See http://www.openmicroscopy.org/site/support/omero4/users/client-tutorials/insight/insight-export-figures.html
""",

        # provide 'Data_Type' and 'IDs' parameters so that Insight auto-populates with currently selected images.
        scripts.String("Data_Type",
                       optional=False,
                       grouping="01",
                       description="The data you want to work with.",
                       values=dataTypes,
                       default="Image"),
        scripts.List("IDs",
                     optional=False,
                     grouping="02",
                     description="List of Image IDs").ofType(rlong(0)),
        scripts.String(
            "Algorithm",
            grouping="3",
            description=
            "Algorithum for projection. Only used if a Z-range is chosen below",
            values=algorithums,
            default='Maximum Intensity'),
        scripts.Int(
            "Z_Start",
            grouping="3.1",
            description=
            "Projection range (if not specified, use defaultZ only - no projection)",
            min=0),
        scripts.Int(
            "Z_End",
            grouping="3.2",
            description=
            "Projection range (if not specified, use defaultZ only - no projection)",
            min=0),
        scripts.Map("Channel_Names",
                    grouping="4",
                    description="Map of index: channel name for all channels"),
        scripts.List(
            "Split_Indexes",
            grouping="5",
            description="List of the channels in the split view").ofType(
                rint(0)),
        scripts.Bool("Split_Panels_Grey",
                     grouping="6",
                     description="If true, all split panels are greyscale",
                     default=False),
        scripts.Map(
            "Merged_Colours",
            grouping="7",
            description="Map of index:int colours for each merged channel"),
        scripts.Bool(
            "Merged_Names",
            grouping="8",
            description=
            "If true, label the merged panel with channel names. Otherwise label with 'Merged'",
            default=True),
        scripts.Int(
            "Width",
            grouping="9",
            description=
            "The max width of each image panel. Default is first image width",
            min=1),
        scripts.Int(
            "Height",
            grouping="91",
            description=
            "The max height of each image panel. Default is first image height",
            min=1),
        scripts.String(
            "Image_Labels",
            grouping="92",
            description=
            "Label images with Image name (default) or datasets or tags",
            values=labels,
            default='Image Name'),
        scripts.Int("Stepping",
                    grouping="93",
                    description="The Z increment for projection.",
                    default=1,
                    min=1),
        scripts.Int(
            "Scalebar",
            grouping="94",
            description=
            "Scale bar size in microns. Only shown if image has pixel-size info.",
            min=1),
        scripts.String("Format",
                       grouping="95",
                       description="Format to save image",
                       values=formats,
                       default='JPEG'),
        scripts.String("Figure_Name",
                       grouping="96",
                       description="File name of the figure to save.",
                       default='Split_View_Figure'),
        scripts.String("Overlay_Colour",
                       grouping="97",
                       description="The colour of the scalebar.",
                       default='White',
                       values=oColours),
        version="4.3.0",
        authors=["William Moore", "OME Team"],
        institutions=["University of Dundee"],
        contact="*****@*****.**",
    )

    try:
        session = client.getSession()
        scriptParams = {}
        conn = BlitzGateway(client_obj=client)

        # process the list of args above.
        for key in client.getInputKeys():
            if client.getInput(key):
                scriptParams[key] = unwrap(client.getInput(key))
        print scriptParams

        # call the main script, attaching resulting figure to Image. Returns the FileAnnotationI
        [fileAnnotation, message] = splitViewFigure(conn, scriptParams)

        # Return message and file annotation (if applicable) to the client
        client.setOutput("Message", rstring(message))
        if fileAnnotation is not None:
            client.setOutput("File_Annotation", robject(fileAnnotation._obj))

    finally:
        client.closeSession()
Ejemplo n.º 26
0
        dictionary = {}
        for row in csv_reader:
            k = row[0]
            v = row[1]
            v = v.replace('[', '')
            v = v.replace(']', '')
            dictionary[k] = np.fromstring(v, sep=' ')
    return dictionary


# ## Method
# ### Connect to OMERO

# In[5]:

conn = BlitzGateway(usernm, passwd, host='camdu.warwick.ac.uk', port=4064)
conn.connect()  #Returns true when connected

# ### Get OMERO IDs
# List the details of the datasets we are interested in from OMERO. We need the IDs to call the images we want to analyse. The output allows us to identify the relevant datasets.

# In[6]:

print("\nList Datasets: \n", "=" * 50)
datasets = conn.getObjects("Dataset",
                           opts={'owner':
                                 3})  #get all datasets from owner 3 (SR)
keys = []  #create empty lists
values = []
for obj in datasets:
    print("""%s%s:%s  Name:"%s" (owner=%s)""" %
Ejemplo n.º 27
0
def run_script():

    data_types = [rstring('Image')]

    client = scripts.client(
        'Channel_Offsets.py',
        """Create new Images from existing images, applying an x, y and z \
shift to each channel independently.
See http://help.openmicroscopy.org/scripts.html""",
        scripts.String(
            "Data_Type",
            optional=False,
            grouping="1",
            description="Pick Images by 'Image' ID or by the ID of their "
            "Dataset'",
            values=data_types,
            default="Image"),
        scripts.List("IDs",
                     optional=False,
                     grouping="2",
                     description="List of Dataset IDs or Image IDs to "
                     "process.").ofType(rlong(0)),
        scripts.String(
            "New_Dataset_Name",
            grouping="3",
            description="If you want the new image(s) in a new Dataset, "
            "put name here"),
        scripts.Bool(
            "Channel_1",
            grouping="4",
            default=True,
            description="Choose to include this channel in the output image"),
        scripts.Int(
            "Channel1_X_shift",
            grouping="4.1",
            default=0,
            description="Number of pixels to shift this channel in the X "
            "direction. (negative to shift left)"),
        scripts.Int(
            "Channel1_Y_shift",
            grouping="4.2",
            default=0,
            description="Number of pixels to shift this channel in the Y"
            " direction. (negative to shift up)"),
        scripts.Int("Channel1_Z_shift",
                    grouping="4.3",
                    default=0,
                    description="Offset channel by a number of Z-sections"),
        scripts.Bool(
            "Channel_2",
            grouping="5",
            default=True,
            description="Choose to include this channel in the output image"),
        scripts.Int(
            "Channel2_X_shift",
            grouping="5.1",
            default=0,
            description="Number of pixels to shift this channel in the X "
            "direction. (negative to shift left)"),
        scripts.Int(
            "Channel2_Y_shift",
            grouping="5.2",
            default=0,
            description="Number of pixels to shift this channel in the Y "
            "direction. (negative to shift up)"),
        scripts.Int("Channel2_Z_shift",
                    grouping="5.3",
                    default=0,
                    description="Offset channel by a number of Z-sections"),
        scripts.Bool(
            "Channel_3",
            grouping="6",
            default=True,
            description="Choose to include this channel in the output image"),
        scripts.Int(
            "Channel3_X_shift",
            grouping="6.1",
            default=0,
            description="Number of pixels to shift this channel in the X "
            "direction. (negative to shift left)"),
        scripts.Int(
            "Channel3_Y_shift",
            grouping="6.2",
            default=0,
            description="Number of pixels to shift this channel in the Y "
            "direction. (negative to shift up)"),
        scripts.Int("Channel3_Z_shift",
                    grouping="6.3",
                    default=0,
                    description="Offset channel by a number of Z-sections"),
        scripts.Bool(
            "Channel_4",
            grouping="7",
            default=True,
            description="Choose to include this channel in the output image"),
        scripts.Int(
            "Channel4_X_shift",
            grouping="7.1",
            default=0,
            description="Number of pixels to shift this channel in the X "
            "direction. (negative to shift left)"),
        scripts.Int(
            "Channel4_Y_shift",
            grouping="7.2",
            default=0,
            description="Number of pixels to shift this channel in the Y "
            "direction. (negative to shift up)"),
        scripts.Int("Channel4_Z_shift",
                    grouping="7.3",
                    default=0,
                    description="Offset channel by a number of Z-sections"),
        version="4.2.0",
        authors=["William Moore", "OME Team"],
        institutions=["University of Dundee"],
        contact="*****@*****.**",
    )

    try:
        script_params = client.getInputs(unwrap=True)

        # wrap client to use the Blitz Gateway
        conn = BlitzGateway(client_obj=client)

        images, dataset, message = process_images(conn, script_params)

        # Return message, new image and new dataset (if applicable) to the
        # client
        client.setOutput("Message", rstring(message))
        if len(images) == 1:
            client.setOutput("Image", robject(images[0]._obj))
        if dataset is not None:
            client.setOutput("New Dataset", robject(dataset._obj))

    finally:
        client.closeSession()
Ejemplo n.º 28
0
        roi = omero.model.RoiI()
        for m in mask:
            roi.addShape(m)
        rois.append(roi)
    print("{} rois created.".format(len(rois)))
    return rois


def main(conn):
    for im in get_images(conn):
        seg_im = get_segmented_image(conn, im)
        if seg_im is None:
            continue
        try:
            print("Processing {} - {}".format(im.name, seg_im.name))
            delete_rois(conn, im)
            rois = create_rois(seg_im)
            if not DRYRUN and len(rois) > 0:
                save_rois(conn, im, rois)
        except Exception as e:
            print(e)


if __name__ == '__main__':
    host = os.environ.get('OMERO_HOST', 'localhost')
    port = os.environ.get('OMERO_PORT', '4064')
    user = os.environ.get('OMERO_USER', 'NA')
    pw = os.environ.get('OMERO_PASSWORD', 'NA')
    with BlitzGateway(user, pw, host=host, port=port) as conn:
        main(conn)
Ejemplo n.º 29
0
from omero.rtypes import rint
from omero.gateway import BlitzGateway
from Parse_OMERO_Properties import USERNAME, PASSWORD, HOST, PORT
# from Parse_OMERO_Properties import imageId, datasetId
import sys
import os
import omero.util.script_utils as script_utils
from omero.constants.namespaces import NSCREATED, NSOMETIFF

conn = BlitzGateway(USERNAME, PASSWORD, host=HOST, port=PORT)
conn.connect()
ret = conn.setGroupForSession(long(sys.argv[1]))

datasetId = sys.argv[2]
imageId = sys.argv[3]


def save_as_ome_tiff(conn, image, folder_name=None):
    """
    Saves the image as an ome.tif in the specified folder
    """

    extension = "ome.tif"
    name = os.path.basename(image.getName())
    iid = image.getId()
    img_name = "%s-%d.%s" % (name, iid, extension)
    if folder_name is not None:
        img_name = os.path.join(folder_name, img_name)
    # check we don't overwrite existing file
    i = 1
    path_name = img_name[:-(len(extension) + 1)]
Ejemplo n.º 30
0
def download_image_data(image_ids_or_dataset_id,
                        dataset=False,
                        channel=None,
                        z_stack=0,
                        frame=0,
                        coord=(0, 0),
                        width=0,
                        height=0,
                        region_spec='rectangle',
                        skip_failed=False,
                        download_tar=False,
                        omero_host='idr.openmicroscopy.org',
                        omero_secured=False,
                        config_file=None):

    if config_file is None:  # IDR connection
        omero_username = '******'
        omero_password = '******'
    else:  # other omero instance
        with open(config_file) as f:
            cfg = json.load(f)
            omero_username = cfg['username']
            omero_password = cfg['password']

            if omero_username == "" or omero_password == "":
                omero_username = '******'
                omero_password = '******'

    if region_spec not in ['rectangle', 'center']:
        raise ValueError(
            'Got unknown value "{0}" as region_spec argument'.format(
                region_spec))
    with ExitStack() as exit_stack:
        conn = exit_stack.enter_context(
            BlitzGateway(omero_username,
                         omero_password,
                         host=omero_host,
                         secure=omero_secured))
        # exit_stack.callback(conn.connect().close)
        if download_tar:
            # create an archive file to write images to
            archive = exit_stack.enter_context(
                tarfile.open('images.tar', mode='w'))
            tempdir = exit_stack.enter_context(TemporaryDirectory())

        if dataset:
            dataset_warning_id = 'Dataset-ID: {0}'.format(
                image_ids_or_dataset_id[0])
            try:
                dataset_id = int(image_ids_or_dataset_id[0])
            except ValueError:
                image_ids = None
            else:
                try:
                    dataset = conn.getObject("Dataset", dataset_id)
                except Exception as e:
                    # respect skip_failed on unexpected errors
                    if skip_failed:
                        warn(str(e), dataset_warning_id, warn_skip=True)
                    else:
                        raise
                else:
                    image_ids = [image.id for image in dataset.listChildren()]

            if image_ids is None:
                if skip_failed:
                    warn(
                        'Unable to find a dataset with this ID in the '
                        'database.',
                        dataset_warning_id,
                        warn_skip=True)
                else:
                    raise ValueError(
                        '{0}: Unable to find a dataset with this ID in the '
                        'database. Aborting!'.format(dataset_warning_id))

        else:
            # basic argument sanity checks and adjustments
            prefix = 'image-'
            # normalize image ids by stripping off prefix if it exists
            image_ids = [
                iid[len(prefix):] if iid[:len(prefix)] == prefix else iid
                for iid in image_ids_or_dataset_id
            ]
        for image_id in image_ids:
            image_warning_id = 'Image-ID: {0}'.format(image_id)
            try:
                image_id = int(image_id)
            except ValueError:
                image = None
            else:
                try:
                    image = conn.getObject("Image", image_id)
                except Exception as e:
                    # respect skip_failed on unexpected errors
                    if skip_failed:
                        warn(str(e), image_warning_id, warn_skip=True)
                        continue
                    else:
                        raise

            if image is None:
                if skip_failed:
                    warn(
                        'Unable to find an image with this ID in the '
                        'database.',
                        image_warning_id,
                        warn_skip=True)
                    continue
                raise ValueError(
                    '{0}: Unable to find an image with this ID in the '
                    'database. Aborting!'.format(image_warning_id))

            try:
                # try to extract image properties
                # if anything goes wrong here skip the image
                # or abort.
                image_name = os.path.splitext(image.getName())[0]
                image_warning_id = '{0} (ID: {1})'.format(image_name, image_id)

                if region_spec == 'rectangle':
                    tile = get_clipping_region(image, *coord, width, height)
                elif region_spec == 'center':
                    tile = get_clipping_region(
                        image, *_center_to_ul(*coord, width, height))

                ori_z, z_stack = z_stack, confine_plane(image, z_stack)
                ori_frame, frame = frame, confine_frame(image, frame)
                num_channels = image.getSizeC()
                if channel is None:
                    channel_index = 0
                else:
                    channel_index = find_channel_index(image, channel)
            except Exception as e:
                # respect skip_failed on unexpected errors
                if skip_failed:
                    warn(str(e), image_warning_id, warn_skip=True)
                    continue
                else:
                    raise

            # region sanity checks and warnings
            if tile[2] < width or tile[3] < height:
                # The downloaded image region will have smaller dimensions
                # than the specified width x height.
                warn(
                    'Downloaded image dimensions ({0} x {1}) will be smaller '
                    'than the specified width and height ({2} x {3}).'.format(
                        tile[2], tile[3], width, height), image_warning_id)

            # z-stack sanity checks and warnings
            if z_stack != ori_z:
                warn(
                    'Specified image plane ({0}) is out of bounds. Using {1} '
                    'instead.'.format(ori_z, z_stack), image_warning_id)

            # frame sanity checks and warnings
            if frame != ori_frame:
                warn(
                    'Specified image frame ({0}) is out of bounds. Using '
                    'frame {1} instead.'.format(ori_frame, frame),
                    image_warning_id)

            # channel index sanity checks and warnings
            if channel is None:
                if num_channels > 1:
                    warn(
                        'No specific channel selected for multi-channel '
                        'image. Using first of {0} channels.'.format(
                            num_channels), image_warning_id)
            else:
                if channel_index == -1 or channel_index >= num_channels:
                    if skip_failed:
                        warn(str(channel) +
                             ' is not a known channel name for this image.',
                             image_warning_id,
                             warn_skip=True)
                        continue
                    else:
                        raise ValueError(
                            '"{0}" is not a known channel name for image {1}. '
                            'Aborting!'.format(channel, image_warning_id))

            # download and save the region as TIFF
            fname = '__'.join([image_name, str(image_id)] +
                              [str(x) for x in tile])
            try:
                if fname[-5:] != '.tiff':
                    fname += '.tiff'

                fname = fname.replace(' ', '_')

                im_array = get_image_array(image, tile, z_stack, channel_index,
                                           frame)

                if download_tar:
                    fname = os.path.join(tempdir, fname)
                try:
                    tiff = TIFF.open(fname, mode='w')
                    tiff.write_image(im_array)
                finally:
                    tiff.close()
                # move image into tarball
                if download_tar:
                    archive.add(fname, os.path.basename(fname))
                    os.remove(fname)
            except Exception as e:
                if skip_failed:
                    # respect skip_failed on unexpected errors
                    warn(str(e), image_warning_id, warn_skip=True)
                    continue
                else:
                    raise