Skip to content
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
244 lines (199 sloc) 7.92 KB
# -----------------------------------------------------------------------------
# Copyright (C) 2018 University of Dundee. All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# ------------------------------------------------------------------------------
# This Jython script uses ImageJ to analyse particles, the generated ROIs are
# saved to OMERO and the generated measurements are saved as OMERO tables.
# In this script, the analysis can be done on behalf of another user by a person
# with more privileges e.g. analyst.
# More details about restricted privileges can be found at
# Use this script in the Scripting Dialog of Fiji (File > New > Script).
# Select Python as language in the Scripting Dialog.
# Error handling is omitted to ease the reading of the script but
# this should be added
# if used in production to make sure the services are closed
# Information can be found at
from java.lang import Long
from java.lang import Double
from java.lang import String
from java.lang import System
from java.lang import Math
from java.util import ArrayList
from jarray import zeros
# OMERO Dependencies
from omero.gateway import Gateway
from omero.gateway import LoginCredentials
from omero.gateway import SecurityContext
from omero.gateway.facility import BrowseFacility
from omero.gateway.facility import AdminFacility
from omero.gateway.facility import ROIFacility, TablesFacility
from omero.log import SimpleLogger
from import ROIReader
from loci.formats import FormatTools, ImageTools
from loci.common import DataTools
from ij import IJ, ImagePlus, ImageStack
from ij.process import ByteProcessor, ShortProcessor
from ij.plugin.frame import RoiManager
from ij.measure import ResultsTable
from omero.gateway.model import TableData, TableDataColumn
# Setup
# =====
# OMERO Server details
HOST = ""
PORT = 4064
group_id = -1
# parameters to edit
dataset_id = 51
USERNAME = "username"
PASSWORD = "password"
# If you want to do analysis for someone else,
# specify their username
target_user = ""
def connect_to_omero():
"Connect to OMERO. Returns a reference to the gateway"
credentials = LoginCredentials()
simpleLogger = SimpleLogger()
gateway = Gateway(simpleLogger)
user = gateway.connect(credentials)
print user.getGroupId()
return gateway
def get_image_ids(gateway, ctx, dataset_id):
"List all image's ids contained in a Dataset"
browse = gateway.getFacility(BrowseFacility)
ctx = switch_security_context(ctx, target_user)
ids = ArrayList(1)
val = Long(dataset_id)
images = browse.getImagesForDatasets(ctx, ids)
j = images.iterator()
image_ids = []
while j.hasNext():
image =
return image_ids
def switch_security_context(ctx, target_user):
"Switch security context"
if not target_user:
target_user = USERNAME
service = gateway.getFacility(AdminFacility)
user = service.lookupExperimenter(ctx, target_user)
ctx = SecurityContext(user.getGroupId())
return ctx
def open_image_plus(HOST, USERNAME, PASSWORD, PORT, group_id, image_id):
"Open the image using the Bio-Formats Importer"
options = """location=[OMERO]
windowless=true view=Hyperstack """ % (HOST, USERNAME, PORT, PASSWORD, group_id, image_id)
IJ.runPlugIn("loci.plugins.LociImporter", options)
def convert_to_omero_table(rt, ctx, image_id, roivec):
"Convert results into an OMERO table"
roivec_cols = ['ROI-id', 'Shape-id', 'Z', 'C', 'T']
length = len(roivec_cols)
no_of_columns = rt.getLastColumn() + length
no_of_rows = rt.size()
data = [[Double(0) for x in range(no_of_rows)] for y in range(no_of_columns)]
columns = [TableDataColumn] * no_of_columns
for c in range(0, no_of_columns):
if c < length:
colname = roivec_cols[c]
rows = [Double(i[c]) for i in roivec]
columns[c] = TableDataColumn(colname, c, Double)
colname = rt.getColumnHeading(c-length)
rows = rt.getColumnAsDoubles(c-length)
columns[c] = TableDataColumn(colname, c, Double)
if rows is None:
for r in range(0, len(rows)):
data[c][r] = rows[r]
table_data = TableData(columns, data)
browse = gateway.getFacility(BrowseFacility)
image = browse.getImage(ctx, long(image_id))
table_facility = gateway.getFacility(TablesFacility)
table_facility.addTable(ctx, image, "ROIs_from_Fiji", table_data)
def save_rois_to_omero(ctx, image_id, imp):
# Save ROI's back to OMERO
reader = ROIReader()
roi_list = reader.readImageJROIFromSources(image_id, imp)
roi_facility = gateway.getFacility(ROIFacility)
result = roi_facility.saveROIs(ctx, image_id, exp_id, roi_list)
roivec = []
j = result.iterator()
while (j.hasNext()):
roidata =
roi_id = roidata.getId()
i = roidata.getIterator()
while (i.hasNext()):
roi =
shape = roi[0]
t = shape.getZ()
z = shape.getT()
c = shape.getC()
shape_id = shape.getId()
roivec.append([roi_id, shape_id, z, c, t])
return roivec
# Prototype analysis example
gateway = connect_to_omero()
exp = gateway.getLoggedInUser()
exp_id = exp.getId()
group_id = exp.getGroupId()
ctx = SecurityContext(group_id)
# get all images_ids in an omero dataset
ids = get_image_ids(gateway, ctx, dataset_id)
# if target_user ~= None:
# Switch context to target user and open omeroImage as ImagePlus object
ctx = switch_security_context(ctx, target_user)
for id1 in ids:
# if target_user ~= None:
# Switch context to target user and open omeroImage as ImagePlus object
open_image_plus(HOST, USERNAME, PASSWORD, PORT, group_id, id1)
imp = IJ.getImage()
# Some analysis which creates ROI's and Results Table"8-bit")
# white might be required depending on the version of Fiji, "Auto Threshold", "method=MaxEntropy stack"), "Analyze Particles...", "size=10-Infinity pixel display clear add stack");"Set Measurements...", "area mean standard modal min centroid center \
perimeter bounding fit shape feret's integrated median skewness \
kurtosis area_fraction stack display redirect=None decimal=3")
rm = RoiManager.getInstance()
rm.runCommand(imp, "Measure")
rt = ResultsTable.getResultsTable()
roivec = save_rois_to_omero(ctx, id1, imp)
convert_to_omero_table(rt, ctx, id1, roivec)
# Close the various components
IJ.selectWindow("ROI Manager")"Close")
imp.changes = False # Prevent "Save Changes?" dialog
# Close the connection
print "processing done"
You can’t perform that action at this time.