Crop OMERO Image using Fiji

This notebook shows how to crop an OMERO image using the crop functionality available in Fiji.

Fiji has been installed with few other plugins including the omero_ij plugin to allow to connect to an OMERO server.

Description

The following section shows:

  • how to connect to OMERO
  • how to open an OMERO image using Bio-Formats
  • how to crop an image using Fiji
  • how to save the generated image as OME-TIFF
  • how to import the created OME-TIFF to OMERO

Setup: start the desktop if it is not already up

The link should open in a different window. If you see an error message try refreshing the window.

Setup: Add plugins to Classpath

First we had Fiji and the plugins to the classpath.

In [1]:
//Add dependencies to the classpath
%classpath add jar /srv/conda/vnc/Fiji.app/jars/*
%classpath add jar /srv/conda/vnc/Fiji.app/plugins/*

Enter credentials. Do not re-run this cell.

In [2]:
g = new EasyForm("Enter credentials and continue to the next cell. Do not re-run this cell")
g.addTextField("Server").onInit({g['Server'] = "wss://workshop.openmicroscopy.org/omero-ws"})
g.addTextField("UserName")
g.addPasswordField("Password")
g

Connect to OMERO

In [3]:
import omero.gateway.Gateway
import omero.gateway.LoginCredentials
import omero.log.SimpleLogger

// Method to connect to OMERO
def connect_to_omero() {
    "Connect to OMERO"

    credentials = new LoginCredentials()
    credentials.getServer().setHostname(g['Server'])
    credentials.getUser().setUsername(g['UserName'].trim())
    credentials.getUser().setPassword(g['Password'].trim())
    simpleLogger = new SimpleLogger()
    gateway = new Gateway(simpleLogger)
    gateway.connect(credentials)
    return gateway

}

// Connect to OMERO
println "connecting..."
gateway = connect_to_omero()
println "connected..."
connecting...
connected...
Out[3]:
null

Select the Image. Do not re-run this cell.

In [4]:
//Move to the next cell after entering a value
ga = new EasyForm("Select the Image to analyze")
ga.addTextField("ImageID")
ga

Collect parameters

In [5]:
//Connection information
HOST = g['Server']
USERNAME = g['UserName'].trim()
PASSWORD = g['Password'].trim()

//Image to analyze
image_id = ga['ImageID'].toLong()
group_id = "-1"
Out[5]:
-1

Open the image using Bio-Formats and crop it

In [6]:
import ij.IJ
//Function to Open an OMERO image using Bio-Formats
def open_image_plus(host, username, password, group_id, image_id) {
    "Open the image using the Bio-Formats Importer"

    StringBuilder options = new StringBuilder()
    options.append("location=[OMERO] open=[omero:server=")
    options.append(host)
    options.append("\nuser=")
    options.append(username)
    options.append("\nport=")
    options.append(443)
    options.append("\npass=")
    options.append(password)
    options.append("\ngroupID=")
    options.append(group_id)
    options.append("\niid=")
    options.append(image_id)
    options.append("] ")
    options.append("windowless=true view=Hyperstack ")
    IJ.runPlugIn("loci.plugins.LociImporter", options.toString())
}

println "opening Image..."
// Open the Image using Bio-Formats
open_image_plus(HOST, USERNAME, PASSWORD, group_id, String.valueOf(image_id))

// Crop the image
println "cropping..."
IJ.makeRectangle(0, 0, 200, 200)
IJ.run("Crop")
opening Image...
cropping...
Out[6]:
null

Save the cropped image as OME-TIFF

In [8]:
import ij.IJ
import java.io.File

// Save modified image as OME-TIFF using Bio-Formats Exporter
imp = IJ.getImage()
name = imp.getTitle().replaceAll("\\s","")
file = File.createTempFile(name, ".ome.tiff")
path_to_file = file.getAbsolutePath()
println  path_to_file
options = "outfile=" + path_to_file + " export compression=Uncompressed windowless=true"
IJ.runPlugIn("loci.plugins.LociExporter", options.toString())
imp.changes = false
imp.close()
/tmp/33676-EB1_dsRed_(red)_tracking_along_peripheral_SEPT2-YFP_fila...(green)._Spinning_disc_confocal_microscopy..ome.tiff_kymograph4297281605584244054.ome.tiff
Out[8]:
null

Import the OME-TIFF into a new dataset

In [9]:
import java.lang.reflect.Array

import omero.gateway.SecurityContext
import omero.gateway.facility.BrowseFacility
import omero.gateway.facility.DataManagerFacility
import omero.gateway.model.DatasetData

import ome.formats.importer.ImportConfig
import ome.formats.importer.OMEROWrapper
import ome.formats.importer.ImportLibrary
import ome.formats.importer.ImportCandidates
import ome.formats.importer.cli.ErrorHandler
import ome.formats.importer.cli.LoggingImportMonitor

import loci.formats.in.DefaultMetadataOptions
import loci.formats.in.MetadataLevel

//Find the dataset matching the specified ID
def find_dataset(gateway, dataset_id) {
    "Load the Dataset"
    browse = gateway.getFacility(BrowseFacility)
    user = gateway.getLoggedInUser()
    ctx = new SecurityContext(user.getGroupId())
    return browse.findIObject(ctx, "omero.model.Dataset", dataset_id)
}

//Upload the generated image
def upload_image(paths, gateway, id) {
    "Upload an image to OMERO"

    user = gateway.getLoggedInUser()
    sessionKey = gateway.getSessionId(user)

    config = new ImportConfig()
    config.debug.set('false')
    config.hostname.set(HOST)
    config.sessionKey.set(sessionKey)
    config.port.set(443)
    dataset = find_dataset(gateway, id)

    store = config.createStore()
    reader = new OMEROWrapper(config)

    library = new ImportLibrary(store, reader)
    error_handler = new ErrorHandler(config)

    library.addObserver(new LoggingImportMonitor())
    candidates = new ImportCandidates(reader, paths, error_handler)
    containers = candidates.getContainers()
    containers.each() { c ->
        c.setTarget(dataset)
    }
    reader.setMetadataOptions(new DefaultMetadataOptions(MetadataLevel.ALL))
    return library.importCandidates(config, candidates)
}

// Create a Dataset
d = new DatasetData()
d.setName("Cropped Image")
dm = gateway.getFacility(DataManagerFacility)
user = gateway.getLoggedInUser()
ctx = new SecurityContext(user.getGroupId())
d = dm.createDataset(ctx, d, null)

// Import the generated OME-TIFF to OMERO
println "importing..."
str2d = new String[1]
str2d[0] = path_to_file
success = upload_image(str2d, gateway, d.getId())
println "imported"
importing...
May 25, 2020 7:22:49 AM java.util.prefs.FileSystemPreferences$1 run
INFO: Created user preferences directory.
Image:57239
Other imported objects:
Fileset:39953
imported
Out[9]:
null

Close the connection and delete local file

In [10]:
// Close the connection
gateway.disconnect()
println "Done"
// delete the local OME-TIFF image
file.delete()
Done
Out[10]:
true

License (BSD 2-Clause)

Copyright (c) 2021, University of Dundee All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.