Skip to content

Commit

Permalink
Merge pull request #10 from jburel/python_ij_review
Browse files Browse the repository at this point in the history
Python ij review
  • Loading branch information
jburel committed Jun 17, 2020
2 parents 10e95f9 + e35b874 commit 38eba42
Show file tree
Hide file tree
Showing 6 changed files with 233 additions and 10 deletions.
7 changes: 7 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,13 @@ cache: pip
env:
- SPHINXOPTS="-W"

install:
- pip install --upgrade jupyter-repo2docker
- pip install --upgrade sphinx
- pip install --upgrade flake8

script:
- repo2docker --no-run .
- flake8 scripts/python
- cd docs
- make clean html linkcheck
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
# User guide for Fiji and OMERO
[![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/ome/omero-guide-fiji/master?filepath=notebooks)

[![Documentation Status](https://readthedocs.org/projects/omero-guide-fiji/badge/?version=latest)](https://omero-guides.readthedocs.io/en/latest/fiji/docs/index.html)

The documentation is deployed at [How to use Fiji](https://omero-guides.readthedocs.io/en/latest/fiji/docs/index.html).

This guide demonstrates how to analyze data stored in OMERO in Fiji.
This can be done using the User Interface or via the scripting facility in Fiji.
Expand Down
130 changes: 121 additions & 9 deletions docs/imagej_python.rst
Original file line number Diff line number Diff line change
Expand Up @@ -7,36 +7,148 @@ Description:
This section shows how to use ImageJ as a Python library to analyze data in OMERO.

Using the Python API allows us to easily load the 2D-plane we need to see or analyze.
This is much easier that when using the Java API and Bio-Formats plugin.
This is much easier than using the Java API and Bio-Formats plugin.

We will show in the notebooks:
We will show in the examples:

- How to start ImageJ in Python
- How to start ImageJ in Python.

- How to load data from OMERO
- How to load data from OMERO.

- How to run ImageJ macro from Python
- How to run ImageJ macro from Python.

Setup
-----

In this case, Fiji has been installed locally. It is possible to install Fiji "on the fly",
see `ImageJ Tutorials <https://nbviewer.jupyter.org/github/imagej/tutorials/blob/master/notebooks/ImageJ-Tutorials-and-Demo.ipynb>`_ for more options.
For using the Python examples and notebooks of this guide we recommend using Conda (Option 1).
Conda manages programming environments in a manner similar to
`virtualenv <https://virtualenv.pypa.io/en/stable/>`_.

Alternatively you can use ``repo2docker`` to build and run a Docker image locally (Option 2).
This Docker image will provide the Conda environment and Jupyter notebooks with some image
analysis workflows.

*Option 1*
~~~~~~~~~~

Install omero-py and `pyimagej <https://pypi.org/project/pyimagej/>`_ via Conda:

- Install `Miniconda <https://docs.conda.io/en/latest/miniconda.html>`_ if necessary.

- Create a programming environment using Conda and activate it::

$ conda create -n fiji_python python=3.6
$ conda create -n imagej_python python=3.6

$ conda activate fiji_python
$ conda activate imagej_python

- Install omero-py and `pyimagej <https://pypi.org/project/pyimagej/>`_::

$ conda install -c conda-forge pyimagej

$ conda install -c ome omero-py

Note: we have noticed problems using the Option 1 approach when running the scripts on some operating systems due to issues with the ImageJ1-ImageJ2 bridge.

*Option 2*
~~~~~~~~~~

Create a local Docker Image using ``repo2docker``, see :download:`README.md <https://github.com/ome/omero-guide-fiji/blob/master/README.md>`::

$ pip install jupyter-repo2docker
$ git clone https://github.com/ome/omero-guide-fiji.git
$ cd omero-guide-fiji
$ repo2docker .

When the Image is ready:

- Copy the URL displayed in the terminal in your favorite browser

- Click the ``New`` button on the right-hand side of the window

- Select ``Terminal``

\ |image0|

- A Terminal will open in a new Tab

- A Conda environment has already been created when the Docker Image was built

- To list all the Conda environments, run::

$ conda env list

- The environment with the OMERO Python bindings and a few other libraries is named ``notebook``, activate it::

$ conda activate notebook

Step-by-Step
------------

The script used in this document is :download:`run_macro_python.py <../scripts/python/run_macro_python.py>`.
One of the advantages of this approach is that we can load only the 2D-planes we wish to analyze.

The script used in this document contains an ImageJ1 macro that needs graphical user interface (GUI) elements, and thus it requires using ImageJ in GUI mode. In this GUI mode, the resulting windows content is handled.
If you are running the example in the Docker container,
you will also need to start UI environment if it is not already up.
If you have used the Option 2 above, select ``desktop`` to start the UI environment.

\ |image0|


If you are using the Option 1 above, you will first need to update the script to point to your local installation of Fiji or use one of the options described in `ImageJ Tutorials <https://nbviewer.jupyter.org/github/imagej/tutorials/blob/master/notebooks/ImageJ-Tutorials-and-Demo.ipynb>`_.
You can now run the script. To run the script, go to the folder ``scripts/python`` and run::

$ python run_macro_python.py

If you do not use any ImageJ1 features e.g. macro, you do **not** need the UI environment.

Below we explain the various methods in the scripts: how to start Fiji, how to load the planes to analyze and how to run an ImageJ1 macro.

In this example, Fiji has been installed locally.

Script's description
~~~~~~~~~~~~~~~~~~~~

**Import** modules needed:

.. literalinclude:: ../scripts/python/run_macro_python.py
:start-after: # Imports
:end-before: # Step 1

**Load Fiji**. If you run the script locally, point to your local installation of Fiji or load Fiji "on the fly". Note that the parameter `headless` has been set to `False` since we need the graphical user interface to run the ImageJ1 macro:

.. literalinclude:: ../scripts/python/run_macro_python.py
:start-after: # Step 1
:end-before: # Step 2

**Connect to the server**. It is also important to close the connection again
to clear up potential resources held on the server. This is done in the
``disconnect`` method:

.. literalinclude:: ../scripts/python/run_macro_python.py
:start-after: # Step 2
:end-before: # Step 4

**Load an image** from IDR:

.. literalinclude:: ../scripts/python/run_macro_python.py
:start-after: # Step 3
:end-before: # -

**Load the binary plane** as numpy array:

.. literalinclude:: ../scripts/python/run_macro_python.py
:start-after: # Step 4
:end-before: # Step 5

To be used in ImageJ, the numpy array will be converted into ImageJ types using the `to_java()` method.
In order the use the methods implemented above in a proper standalone script:
**Wrap it all up** in an ``analyse`` method and call it from ``main``:

.. literalinclude:: ../scripts/python/run_macro_python.py
:start-after: # Step 5


.. |image0| image:: images/terminal.png
:width: 1.0in
:height: 2.24105in
Binary file added docs/images/terminal.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 1 addition & 1 deletion notebooks/imagej_python.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
"source": [
"## Starting ImageJ from Python\n",
"\n",
"To run the macro,we use ImageJ1 windows so it requires using ImageJ in GUI mode and requires handling the resulting windows. This is the reason the parameter `headless` is set to `False`.\n",
"To run the macro, we use ImageJ1 windows so it requires using ImageJ in GUI mode and requires handling the resulting windows. This is the reason the parameter `headless` is set to `False`.\n",
"\n",
"You will also need to start the **[desktop](../../desktop)** if it is not already up.\n",
"The link should open in a different window. If you see an error message try refreshing the window.\n",
Expand Down
101 changes: 101 additions & 0 deletions scripts/python/run_macro_python.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-

# -----------------------------------------------------------------------------
# Copyright (C) 2020 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
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# 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 script shows how to use the OMERO Python API and ImageJ Python.
# We run a simple ImageJ1 macro.

# Imports
import imagej
from omero.gateway import BlitzGateway


# Step 1 - Load-Fiji
def start_fiji():
ij = imagej.init('/srv/conda/vnc/Fiji.app', headless=False)
ij.getVersion()
return ij


# Step 2 - Connect/Disconnect
def connect(hostname, username, password):
"""
Connect to an OMERO server
:param hostname: Host name
:param username: User
:param password: Password
:return: Connected BlitzGateway
"""
conn = BlitzGateway(username, password,
host=hostname, secure=True)
conn.connect()
conn.c.enableKeepAlive(60)
return conn


def disconnect(conn):
"""
Disconnect from an OMERO server
:param conn: The BlitzGateway
"""
conn.close()


# Step 4 - Load plane as 2D numpy array
def load_plane(image):
"""
Load a 2D-plane as a numpy array
:param image: The image
"""
pixels = image.getPrimaryPixels()
return pixels.getPlane(0, 0, 0)


# Step 5 - Wrap it all up
def analyse(ij, conn, image_id):
# Step 3 - Load image
image = conn.getObject("Image", image_id)
# -
plane = load_plane(image)
from jnius import autoclass
autoclass('ij.WindowManager')
ij.ui().show('Image', ij.py.to_java(plane))
macro = """run("8-bit")"""
ij.py.run_macro(macro)


def main():
try:
hostname = input("Host [wss://idr.openmicroscopy.org/omero-ws]: \
") or "wss://idr.openmicroscopy.org/omero-ws"
username = "public"
password = "public"
image_id = int(input("Image ID [1884807]: ") or 1884807)
print("initializing fiji...")
ij = start_fiji()
print("connecting to IDR...")
conn = connect(hostname, username, password)
print("running the macro...")
analyse(ij, conn, image_id)
finally:
if conn:
disconnect(conn)


if __name__ == "__main__":
main()

0 comments on commit 38eba42

Please sign in to comment.