imcflibs.imagej.misc

Miscellaneous ImageJ related functions, mostly convenience wrappers.

  1"""Miscellaneous ImageJ related functions, mostly convenience wrappers."""
  2
  3import sys
  4import time
  5
  6from ij import IJ  # pylint: disable-msg=import-error
  7
  8from . import prefs
  9from ..log import LOG as log
 10
 11
 12def show_status(msg):
 13    """Wrapper to update the ImageJ status bar and the log simultaneously."""
 14    log.info(msg)
 15    IJ.showStatus(msg)
 16
 17
 18def show_progress(cur, final):
 19    """Wrapper to update the progress bar and issue a log message."""
 20    # ij.IJ.showProgress is adding 1 to the value given as first parameter...
 21    log.info("Progress: %s / %s (%s)", cur + 1, final, (1.0 + cur) / final)
 22    IJ.showProgress(cur, final)
 23
 24
 25def error_exit(msg):
 26    """Convenience wrapper to log an error and exit then."""
 27    log.error(msg)
 28    sys.exit(msg)
 29
 30
 31def elapsed_time_since(start, end=None):
 32    """Generate a string with the time elapsed between the two timepoints.
 33
 34    Parameters
 35    ----------
 36    start : time.time
 37        Start time.
 38    end : time.time, optional
 39        End time. If skipped the current time will be used.
 40
 41    Returns
 42    -------
 43    str
 44    """
 45
 46    if not end:
 47        end = time.time()
 48
 49    hours, rem = divmod(end - start, 3600)
 50    minutes, seconds = divmod(rem, 60)
 51    return "{:0>2}:{:0>2}:{:05.2f}".format(int(hours), int(minutes), seconds)
 52
 53
 54def percentage(part, whole):
 55    """Calculate the percentage of a value based on total.
 56
 57    Parameters
 58    ----------
 59    part : float
 60        Part.
 61    whole : float
 62        Complete size.
 63
 64    Returns
 65    -------
 66    float
 67    """
 68    return 100 * float(part) / float(whole)
 69
 70
 71def calculate_mean_and_stdv(float_values):
 72    """Calculate mean and standard deviation from a list of floats.
 73
 74    Parameters
 75    ----------
 76    float_values : list(float)
 77        List containing float numbers.
 78
 79    Returns
 80    -------
 81    [float, float]
 82        Mean (1st item) and standard deviation (2nd item) of the list.
 83    """
 84    mean = sum(float_values) / len(float_values)
 85    tot = 0.0
 86    for x in float_values:
 87        tot = tot + (x - mean) ** 2
 88    return [mean, (tot / (len(float_values))) ** 0.5]
 89
 90
 91def find_focus(imp):
 92    """Find the slice of a stack that seems to bet the best focused one.
 93
 94    NOTE: currently only single-channel stacks are supported.
 95
 96    FIXME: explain what the function is actually doing, i.e. how does it decide
 97    what "the best focused one" is?
 98
 99    Parameters
100    ----------
101    imp : ij.ImagePlus
102        A single-channel ImagePlus.
103
104    Returns
105    -------
106    int
107    """
108
109    imp_dimensions = imp.getDimensions()
110
111    # Check if more than 1 channel
112    # FUTURE Could be improved for multi channel
113    if imp_dimensions[2] != 1:
114        sys.exit("Image has more than one channel, please reduce dimensionality")
115
116    # Loop through each time points
117    for plane in range(1, imp_dimensions[4] + 1):
118        focused_slice = 0
119        norm_var = 0
120        imp.setT(plane)
121        # Loop through each z plane
122        for current_z in range(1, imp_dimensions[3] + 1):
123            imp.setZ(current_z)
124            pix_array = imp.getProcessor().getPixels()
125            mean = (sum(pix_array)) / len(pix_array)
126            pix_array = [(x - mean) * (x - mean) for x in pix_array]
127            # pix_array = pix_array*pix_array
128
129            sumpix_array = sum(pix_array)
130            var = sumpix_array / (imp_dimensions[0] * imp_dimensions[1] * mean)
131
132            if var > norm_var:
133                norm_var = var
134                focused_slice = current_z
135
136    return focused_slice
137
138
139def progressbar(progress, total, line_number, prefix=""):
140    """Progress bar for the IJ log window.
141
142    Show a progress bar in the log window of Fiji at a specific line independent
143    of the main Fiji progress bar.
144
145    Parameters
146    ----------
147    progress : int
148        Current step of the loop.
149    total : int
150        Total number of steps for the loop.
151    line_number : int
152        Number of the line to be updated.
153    prefix : str, optional
154        Text to use before the progress bar, by default ''.
155    """
156
157    size = 20
158    x = int(size * progress / total)
159    IJ.log(
160        "\\Update%i:%s[%s%s] %i/%i\r"
161        % (
162            line_number,
163            timed_log(prefix, True),
164            "#" * x,
165            "." * (size - x),
166            progress,
167            total,
168        )
169    )
170
171
172def timed_log(message, as_string=False):
173    """Print a message to the ImageJ log window with a timestamp added.
174
175    Parameters
176    ----------
177    message : str
178        Message to print
179    """
180    if as_string:
181        return time.strftime("%H:%M:%S", time.localtime()) + ": " + message + " "
182    IJ.log(time.strftime("%H:%M:%S", time.localtime()) + ": " + message + " ")
183
184
185def get_free_memory():
186    """Get the free memory thats available to ImageJ.
187
188    Returns
189    -------
190    free_memory : int
191        The free memory in bytes.
192    """
193    max_memory = int(IJ.maxMemory())
194    used_memory = int(IJ.currentMemory())
195    free_memory = max_memory - used_memory
196
197    return free_memory
198
199
200def setup_clean_ij_environment(rm=None, rt=None):  # pylint: disable-msg=unused-argument
201    """Set up a clean and defined ImageJ environment.
202
203    Clean active results table, roi manager and log, close any open image.
204
205    "Fresh Start" is described in the ImageJ release notes [1] following a
206    suggestion by Robert Haase in the Image.sc Forum [2].
207
208    [1]: https://imagej.nih.gov/ij/notes.html
209    [2]: https://forum.image.sc/t/fresh-start-macro-command-in-imagej-fiji/43102
210
211    Parameters
212    ----------
213    rm : RoiManager, optional
214        Will be ignored (kept for keeping API compatibility).
215    rt : ResultsTable, optional
216        Will be ignored (kept for keeping API compatibility).
217    """
218
219    IJ.run("Fresh Start", "")
220    IJ.log("\\Clear")
221
222    prefs.fix_ij_options()
223
224    return
def show_status(msg):
13def show_status(msg):
14    """Wrapper to update the ImageJ status bar and the log simultaneously."""
15    log.info(msg)
16    IJ.showStatus(msg)

Wrapper to update the ImageJ status bar and the log simultaneously.

def show_progress(cur, final):
19def show_progress(cur, final):
20    """Wrapper to update the progress bar and issue a log message."""
21    # ij.IJ.showProgress is adding 1 to the value given as first parameter...
22    log.info("Progress: %s / %s (%s)", cur + 1, final, (1.0 + cur) / final)
23    IJ.showProgress(cur, final)

Wrapper to update the progress bar and issue a log message.

def error_exit(msg):
26def error_exit(msg):
27    """Convenience wrapper to log an error and exit then."""
28    log.error(msg)
29    sys.exit(msg)

Convenience wrapper to log an error and exit then.

def elapsed_time_since(start, end=None):
32def elapsed_time_since(start, end=None):
33    """Generate a string with the time elapsed between the two timepoints.
34
35    Parameters
36    ----------
37    start : time.time
38        Start time.
39    end : time.time, optional
40        End time. If skipped the current time will be used.
41
42    Returns
43    -------
44    str
45    """
46
47    if not end:
48        end = time.time()
49
50    hours, rem = divmod(end - start, 3600)
51    minutes, seconds = divmod(rem, 60)
52    return "{:0>2}:{:0>2}:{:05.2f}".format(int(hours), int(minutes), seconds)

Generate a string with the time elapsed between the two timepoints.

Parameters
  • start (time.time): Start time.
  • end (time.time, optional): End time. If skipped the current time will be used.
Returns
  • str
def percentage(part, whole):
55def percentage(part, whole):
56    """Calculate the percentage of a value based on total.
57
58    Parameters
59    ----------
60    part : float
61        Part.
62    whole : float
63        Complete size.
64
65    Returns
66    -------
67    float
68    """
69    return 100 * float(part) / float(whole)

Calculate the percentage of a value based on total.

Parameters
  • part (float): Part.
  • whole (float): Complete size.
Returns
  • float
def calculate_mean_and_stdv(float_values):
72def calculate_mean_and_stdv(float_values):
73    """Calculate mean and standard deviation from a list of floats.
74
75    Parameters
76    ----------
77    float_values : list(float)
78        List containing float numbers.
79
80    Returns
81    -------
82    [float, float]
83        Mean (1st item) and standard deviation (2nd item) of the list.
84    """
85    mean = sum(float_values) / len(float_values)
86    tot = 0.0
87    for x in float_values:
88        tot = tot + (x - mean) ** 2
89    return [mean, (tot / (len(float_values))) ** 0.5]

Calculate mean and standard deviation from a list of floats.

Parameters
  • float_values (list(float)): List containing float numbers.
Returns
  • [float, float]: Mean (1st item) and standard deviation (2nd item) of the list.
def find_focus(imp):
 92def find_focus(imp):
 93    """Find the slice of a stack that seems to bet the best focused one.
 94
 95    NOTE: currently only single-channel stacks are supported.
 96
 97    FIXME: explain what the function is actually doing, i.e. how does it decide
 98    what "the best focused one" is?
 99
100    Parameters
101    ----------
102    imp : ij.ImagePlus
103        A single-channel ImagePlus.
104
105    Returns
106    -------
107    int
108    """
109
110    imp_dimensions = imp.getDimensions()
111
112    # Check if more than 1 channel
113    # FUTURE Could be improved for multi channel
114    if imp_dimensions[2] != 1:
115        sys.exit("Image has more than one channel, please reduce dimensionality")
116
117    # Loop through each time points
118    for plane in range(1, imp_dimensions[4] + 1):
119        focused_slice = 0
120        norm_var = 0
121        imp.setT(plane)
122        # Loop through each z plane
123        for current_z in range(1, imp_dimensions[3] + 1):
124            imp.setZ(current_z)
125            pix_array = imp.getProcessor().getPixels()
126            mean = (sum(pix_array)) / len(pix_array)
127            pix_array = [(x - mean) * (x - mean) for x in pix_array]
128            # pix_array = pix_array*pix_array
129
130            sumpix_array = sum(pix_array)
131            var = sumpix_array / (imp_dimensions[0] * imp_dimensions[1] * mean)
132
133            if var > norm_var:
134                norm_var = var
135                focused_slice = current_z
136
137    return focused_slice

Find the slice of a stack that seems to bet the best focused one.

NOTE: currently only single-channel stacks are supported.

FIXME: explain what the function is actually doing, i.e. how does it decide what "the best focused one" is?

Parameters
  • imp (ij.ImagePlus): A single-channel ImagePlus.
Returns
  • int
def progressbar(progress, total, line_number, prefix=''):
140def progressbar(progress, total, line_number, prefix=""):
141    """Progress bar for the IJ log window.
142
143    Show a progress bar in the log window of Fiji at a specific line independent
144    of the main Fiji progress bar.
145
146    Parameters
147    ----------
148    progress : int
149        Current step of the loop.
150    total : int
151        Total number of steps for the loop.
152    line_number : int
153        Number of the line to be updated.
154    prefix : str, optional
155        Text to use before the progress bar, by default ''.
156    """
157
158    size = 20
159    x = int(size * progress / total)
160    IJ.log(
161        "\\Update%i:%s[%s%s] %i/%i\r"
162        % (
163            line_number,
164            timed_log(prefix, True),
165            "#" * x,
166            "." * (size - x),
167            progress,
168            total,
169        )
170    )

Progress bar for the IJ log window.

Show a progress bar in the log window of Fiji at a specific line independent of the main Fiji progress bar.

Parameters
  • progress (int): Current step of the loop.
  • total (int): Total number of steps for the loop.
  • line_number (int): Number of the line to be updated.
  • prefix (str, optional): Text to use before the progress bar, by default ''.
def timed_log(message, as_string=False):
173def timed_log(message, as_string=False):
174    """Print a message to the ImageJ log window with a timestamp added.
175
176    Parameters
177    ----------
178    message : str
179        Message to print
180    """
181    if as_string:
182        return time.strftime("%H:%M:%S", time.localtime()) + ": " + message + " "
183    IJ.log(time.strftime("%H:%M:%S", time.localtime()) + ": " + message + " ")

Print a message to the ImageJ log window with a timestamp added.

Parameters
  • message (str): Message to print
def get_free_memory():
186def get_free_memory():
187    """Get the free memory thats available to ImageJ.
188
189    Returns
190    -------
191    free_memory : int
192        The free memory in bytes.
193    """
194    max_memory = int(IJ.maxMemory())
195    used_memory = int(IJ.currentMemory())
196    free_memory = max_memory - used_memory
197
198    return free_memory

Get the free memory thats available to ImageJ.

Returns
  • free_memory (int): The free memory in bytes.
def setup_clean_ij_environment(rm=None, rt=None):
201def setup_clean_ij_environment(rm=None, rt=None):  # pylint: disable-msg=unused-argument
202    """Set up a clean and defined ImageJ environment.
203
204    Clean active results table, roi manager and log, close any open image.
205
206    "Fresh Start" is described in the ImageJ release notes [1] following a
207    suggestion by Robert Haase in the Image.sc Forum [2].
208
209    [1]: https://imagej.nih.gov/ij/notes.html
210    [2]: https://forum.image.sc/t/fresh-start-macro-command-in-imagej-fiji/43102
211
212    Parameters
213    ----------
214    rm : RoiManager, optional
215        Will be ignored (kept for keeping API compatibility).
216    rt : ResultsTable, optional
217        Will be ignored (kept for keeping API compatibility).
218    """
219
220    IJ.run("Fresh Start", "")
221    IJ.log("\\Clear")
222
223    prefs.fix_ij_options()
224
225    return

Set up a clean and defined ImageJ environment.

Clean active results table, roi manager and log, close any open image.

"Fresh Start" is described in the ImageJ release notes [1] following a suggestion by Robert Haase in the Image.sc Forum [2].

Parameters
  • rm (RoiManager, optional): Will be ignored (kept for keeping API compatibility).
  • rt (ResultsTable, optional): Will be ignored (kept for keeping API compatibility).