Source code

Download source archive ↓

upstream/tools/image_processing/imagej2/imagej2_noise_jython_script.py

1import sys
2
3from ij import IJ, ImagePlus
4
5# Fiji Jython interpreter implements Python 2.5 which does not
6# provide support for argparse.
7input_file = sys.argv[-8]
8image_datatype = sys.argv[-7]
9noise = sys.argv[-6]
10standard_deviation = sys.argv[-5]
11radius = sys.argv[-4]
12threshold = sys.argv[-3]
13which_outliers = sys.argv[-2]
14tmp_output_path = sys.argv[-1]
15
16# Open the input image file.
17image_plus = IJ.openImage(input_file)
18image_type = image_plus.getType()
19is32BITS_GREY = image_type == ImagePlus.GRAY32
20# Create an ImagePlus object for the image.
21image_plus_copy = image_plus.duplicate()
22
23# Perform the analysis on the ImagePlus object.
24try:
25    if noise == "add_noise":
26        IJ.run(image_plus_copy, "Add Noise", "")
27    elif noise == "add_specified_noise":
28        IJ.run(image_plus_copy, "Add Specified Noise...", "standard=%s" % standard_deviation)
29    elif noise == "salt_and_pepper":
30        IJ.run(image_plus_copy, "Salt and Pepper", "")
31    elif noise == "despeckle":
32        IJ.run(image_plus_copy, "Despeckle", "")
33    elif noise == "remove_outliers":
34        IJ.run(
35            image_plus_copy,
36            "Remove Outliers...",
37            "radius=%s threshold=%s which=%s" % (radius, threshold, which_outliers)
38        )
39    elif noise == "remove_nans":
40        if is32BITS_GREY:
41            IJ.run(image_plus_copy, "Remove NaNs...", "")
42        else:
43            raise Exception("Remove NaNs can only be applied to 32bits grey images.")
44    elif noise == "rof_denoise":
45        if is32BITS_GREY:
46            IJ.run(image_plus_copy, "ROF Denoise", "")
47        else:
48            raise Exception("ROF Denoise can only be applied to 32bits grey images.")
49except Exception as e:
50    # This is due to some operations like remove_outliers and despeckle which block the script
51    print(e)
52    exit(1)
53# Save the ImagePlus object as a new image.
54IJ.saveAs(image_plus_copy, image_datatype, tmp_output_path)
55# This is due to some operations like remove_outliers and despeckle which block the script
56exit(0)