-
Notifications
You must be signed in to change notification settings - Fork 0
/
ijmpy.py
2120 lines (1757 loc) · 62 KB
/
ijmpy.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'''
ijmpy is a python wrapper of the imagej-macro-language
It allows to move ij-macro code to python (mostly) without modifications (yes, you can keep the ';')
The aim is to facilitate the step of moving from macro to scripting. You can record your
macro, use the familiar macro language and learn how to profit from the better code organization
and data-structures (list, tupels, dictionary, ...) in python.
written 2020 by `Volker Baecker`_, `Montpellier Ressources Imagerie`_, Biocampus Montpellier, UM, INSERM, CNRS
.. _`Volker Baecker`: https://github.com/volker-baecker
.. _`Montpellier Ressources Imagerie`: http://www.mri.cnrs.fr
Have fun!
Unimplemented functions
=======================
abs()
-----
When you call 'abs()' the python 'abs()' function is called. The behaviour should be identical.
getArgument()
-------------
Not implemented, because it exists when called from a macro. Use:
if 'getArgument' in globals():
args = getArgument()
Other differences with the ij-macro language
============================================
output parameter
----------------
Functions that take output parameter in the macro language are implemented without these parameters
and return the results as an n-tupel instead.
For example, use:
min, max, mean, stddev = Array.getStatistics(anArray)
instead of
Array.getStatistics(anArray, min, max, mean, stddev)
Only in the case that the parameter modified in the function is an array, it is modified in place.
For example:
Array.fill(array, 0)
Array.reverse(array)
'''
from __future__ import print_function, division # we will overwrite python's print command
import __builtin__ # to use the python print command: __builtin__.print(<text>)
import math, sys, importlib, java, types, inspect, keyword, tokenize, os, subprocess, shutil, struct, urllib2
from collections import deque
from java.lang import Double, String, Thread
from java.util import Calendar
from java.awt import Font, Color
from ij import IJ, WindowManager, Prefs
from ij.io import SaveDialog, OpenDialog
from ij.process import FloatProcessor, ColorProcessor, ImageProcessor, FloodFiller
from ij.plugin import Colors, Macro_Runner
from ij.plugin.frame import RoiManager, Fitter
from ij.plugin.filter import MaximumFinder, Analyzer
from ij.process import FHT
from ij.util import Tools
from ij.measure import ResultsTable, CurveFitter
from ij.gui import Roi, GenericDialog, NonBlockingGenericDialog, Toolbar, YesNoCancelDialog
NaN = Double.NaN
PI = math.pi
true = 1
false = 0
py_open = open
class Settings(object):
AUTO_UPDATE = True
UPDATE_NEEDED = False
FONT = None
JUSTIFICATION = ImageProcessor.LEFT_JUSTIFY
ANTIALIASED_TEXT = False
GLOBAL_COLOR = None
FILE = None
def acos(n):
'''
Returns the inverse cosine (in radians) of n.
'''
return math.acos(n)
class Array(object):
'''
These functions operate on arrays. Refer to the `ArrayFunctions`_ macro for examples.
.. _`ArrayFunctions`: https://imagej.net/macros/examples/ArrayFunctions.txt
'''
INCLUDE_EDGES = 0
EXLUDE_EDGES = 1
CIRCULAR_ARRAY = 2
NO_WINDOW = "none"
HAMMING = "Hamming"
HANN = "Hann"
FLAT_TOP = "flat-top"
@classmethod
def concat(cls, *args):
'''
Returns a new array created by joining two or more arrays or values (examples_).
.. _`examples`: https://imagej.net/macros/examples/ArrayConcatExamples.txt
'''
result = list()
for arrayOrElement in args:
if isinstance(arrayOrElement, list):
current = arrayOrElement
else:
current = list()
current.append(arrayOrElement)
result = result + current
return result
@classmethod
def copy(cls, aList):
'''
Returns a copy of array.
'''
return list(aList)
@classmethod
def deleteValue(cls, array, value):
'''
Returns a version of array where all numeric or string elements in the array that contain
value have been deleted (examples_).
Requires 1.52o.
.. _`examples`: https://imagej.net/macros/examples/ArrayDeleteDemo.txt
'''
filtered = [x for x in array if x!=value]
return filtered
@classmethod
def deleteIndex(cls, array, index):
'''
Returns a version of array where the element with the specified index has been deleted.
Requires 1.52o.
'''
a1 = array[0:index]
a2 = array[index+1:len(array)]
return a1 + a2
@classmethod
def fill(cls, array, value):
'''
Assigns the specified numeric value to each element of array.
'''
for i in range(0, len(array)):
array[i] = value
return array
@classmethod
def findMaxima(cls, array, tolerance, edgeMode=EXLUDE_EDGES):
'''
Returns an array holding the peak positions (sorted with descending strength).
'Tolerance' is the minimum amplitude difference needed to separate two peaks.
With v1.51n and later, there is an optional 'edgeMode' argument:
0=include edges, 1=exclude edges(default), 2=circular array. `Examples`_.
.. _`Examples`: https://imagej.net/macros/examples/FindMaxima1D.txt
'''
maxima = MaximumFinder.findMaxima(array, tolerance, edgeMode)
return maxima
@classmethod
def findMinima(cls, array, tolerance, edgeMode=EXLUDE_EDGES):
'''
Returns an array holding the minima positions.
'''
minima = MaximumFinder.findMinima(array, tolerance, edgeMode)
return minima
@classmethod
def fourier(cls, array, windowType=NO_WINDOW):
'''
Calculates and returns the Fourier amplitudes of array.
WindowType can be "none", "Hamming", "Hann", or "flat-top",
or may be omitted (meaning "none").
See the `TestArrayFourier`_ macro for an example and more documentation.
.. _`TestArrayFourier`: https://imagej.net/macros/examples/TestArrayFourier.txt
'''
wt = [cls.NO_WINDOW, cls.HAMMING, cls.HANN, cls.FLAT_TOP].index(windowType)
result = FHT().fourier1D(array, wt)
return result
@classmethod
def getSequence(cls, n):
'''
Returns an array containing the numeric sequence 0,1,2...n-1.
'''
return range(n)
@classmethod
def getStatistics(cls, aList):
'''
Returns the min, max, mean, and stdDev of array, which must contain all numbers.
The ij-macro function takes output parameters. The ijmpy version only takes the list as
parameter and returns the tupel of the calculated values (min, max, mean, stdDev). This
means instead of
Array.getStatistics(anArray, min, max, mean, stddev)
you have to write
min, max, mean, stddev = Array.getStatistics(anArray)
It could be implemented as
min, max, mean, stddev = Array.getStatistics(anArray, min, max, mean, stddev)
But then
Array.getStatistics(anArray, min, max, mean, stddev)
would silently fail.
'''
sum = sum2 = 0
min = Double.POSITIVE_INFINITY;
max = Double.NEGATIVE_INFINITY
for value in aList:
sum = sum + value
sum2 = sum2 + (value*value)
if value<min:
min = value
if value>max:
max = value
n = len(aList)
mean = sum / float(n)
stdDev = ((n*sum2)-(sum*sum))/float(n)
stdDev = math.sqrt(stdDev / float(n-1))
return min, max, mean, stdDev
@classmethod
def print(cls, aList):
'''
Prints the array on a single line.
'''
string = str(aList)
string = string.replace('[', '').replace(']', '').replace("'", "")
IJ.log(string)
return string
@classmethod
def rankPositions(cls, array):
'''
Returns, as an array, the rank position indexes of array, starting with the index of the smallest value (`example`_).
.. _`example`: https://imagej.net/macros/examples/ArraySortingDemo.txt
'''
return Tools.rank(array)
@classmethod
def resample(cls, array, len):
'''
Returns an array which is linearly resampled to a different length.
'''
return Tools.resampleArray(array, len)
@classmethod
def reverse(cls, array):
'''
Reverses (inverts) the order of the elements in array.
Note that the method reverses the list passed as a parameter. For convenience it also
returns the refernce to the list.
'''
return array.reverse()
@classmethod
def show(cls, *args):
'''
Displays one or more arrays in a Results window (`examples`_).
If title (optional) is "Results", the window will be the active Results window, otherwise,
it will be a dormant Results window (see also `IJ.renameResults`_). If title ends with "(indexes)",
a 0-based Index column is shown. If title ends with "(row numbers)", the row number column is shown.
.. _`examples`: https://imagej.net/macros/examples/ShowArrayDemo.txt
.. _`IJ.renameResults`: https://imagej.net/developer/macro/functions.html#IJ.renameResults
'''
if len(args)==0 or (len(args)==1 and not isinstance(args[0], list)): #@TODO: refactor!!!
raise Exception('Array show needs at least one array')
title = "Arrays"
if len(args)==1 or (len(args)==2 and isinstance(args[0], str)): # one array with or without title
if isinstance(args[0], str):
title = args[0]
array = args[1]
else:
title = __getNameOfArg(args[0])
array = args[0]
column = "Value"
indexes = False;
rowNumbers = False;
if title.find('(indexes)')>=0:
indexes = True
title = title.replace('(indexes)', '').strip()
if title.find('(row numbers)')>=0:
rowNumbers = True
title = title.replace('(row numbers)', '').strip()
if (indexes):
rt.showRowNumbers(False)
rt.showRowIndexes(True)
if (rowNumbers):
rt.showRowIndexes(False)
rt.showRowNumbers(True)
if (title.lower()=='results'):
rt = Analyzer.getResultsTable()
else:
rt = ResultsTable()
for value in array:
rt.incrementCounter()
rt.addValue(column, value)
rt.show(title)
return rt
indexes = False # More than one array
rowNumbers = False
if (isinstance(args[0], str)):
title = args[0]
if title.find('(indexes)')>=0:
indexes = True
title = title.replace('(indexes)', '').strip()
if title.find('(row numbers)')>=0:
rowNumbers = True
title = title.replace('(row numbers)', '').strip()
if (title.lower()=='results'):
rt = Analyzer.getResultsTable()
else:
rt = ResultsTable()
isFirstColumn = True;
for array in args:
if isinstance(array, str):
continue
row = 0
for value in array:
column = __getNameOfArg(array)
if (isFirstColumn):
rt.incrementCounter()
rt.addValue(column, value)
else:
rt.setValue(column, row, value)
row = row + 1
isFirstColumn = False
if (indexes):
rt.showRowNumbers(False)
rt.showRowIndexes(True)
if (rowNumbers):
rt.showRowIndexes(False)
rt.showRowNumbers(True)
rt.show(title)
return rt
@classmethod
def slice(cls, array, start, stop=None):
'''
Extracts a part of an array and returns it. (`examples`_).
.. _`examples`: https://imagej.net/macros/examples/ArraySliceExamples.txt
'''
if (stop is None):
stop = len(array)
return array[start:stop]
@classmethod
def sort(cls, array):
'''
Sorts array, which must contain all numbers or all strings. String sorts are case-insensitive in v1.44i or later.
'''
if (len(array)==0):
return array
if (isinstance(array[0], str)):
return array.sort(key=lambda y: y.lower())
return array.sort()
@classmethod
def trim(cls, array, n):
'''
Returns an array that contains the first n elements of array.
'''
return array[:n]
@classmethod
def rotate(cls, array, d):
'''
Rotates the array elements by 'd' steps (positive 'd' = rotate right). Requires 1.51n. `Examples`_.
.. _`Examples`: https://imagej.net/macros/examples/RotateArray.txt
'''
if len(array) == 0:
return array
rotated = deque(array)
rotated.rotate(d)
for i in range(0, len(array)):
array[i] = rotated[i]
return array
@classmethod
def getVertexAngles(cls, xArr, yArr, arm):
'''
From a closed contour given by 'xArr', 'yArr', an array is returned holding vertex angles in degrees
(straight=0, convex = positive if contour is clockwise).
Set 'arm'=1 to calculate the angle from the closest vertex points left and right, or use arm>1 for
more distant neighbours and smoother results. Requires 1.51n. `Examples`_.
.. _`Examples`: https://imagej.net/macros/examples/VertexAngles.txt
'''
if len(xArr)!=len(yArr):
raise Exception('Same size expected')
length = len(xArr)
vAngles = [0]*length
x = xArr
y = yArr
for mid in range(0, length):
left = (mid + 10 * length - arm) % length
right = (mid + arm) % length
dotprod = (x[right] - x[mid]) * (x[left] - x[mid]) + (y[right] - y[mid]) * (y[left] - y[mid])
crossprod = (x[right] - x[mid]) * (y[left] - y[mid]) - (y[right] - y[mid]) * (x[left] - x[mid])
phi = 180.0 - 180.0 / math.pi * math.atan2(crossprod, dotprod)
while phi >= 180.0:
phi -= 360.0
vAngles[mid] = phi
return vAngles
def asin(n):
'''
Returns the inverse sine (in radians) of n.
'''
return math.asin(n)
def atan(n):
'''
Calculates the inverse tangent (arctangent) of n.
Returns a value in the range -PI/2 through PI/2.
'''
return math.atan(n)
def atan2(y, x):
'''
Calculates the inverse tangent of y/x and returns an angle in the range -PI to PI,
using the signs of the arguments to determine the quadrant.
Multiply the result by 180/PI to convert to degrees.
'''
return math.atan2(y, x)
def autoUpdate(aBoolean):
'''
If boolean is true, the display is refreshed each time lineTo(), `drawLine()`_, `drawString()`_, etc. are called.
Otherwise, the display is refreshed only when updateDisplay() is called or when the macro terminates.
.. _`drawLine()`: redirect.html#mripy.ijmpy.drawLine
.. _`drawString()`: redirect.html#mripy.ijmpy.drawString
'''
Settings.AUTO_UPDATE = aBoolean
def isAutoUpdate():
'''
Returns true if auto-update is active and false otherwise.
'''
return Settings.AUTO_UPDATE
def beep():
'''
Emits an audible beep.
'''
IJ.beep()
def bitDepth():
'''
Returns the bit depth of the active image: 8, 16, 24 (RGB) or 32 (float).
'''
return IJ.getImage().getBitDepth()
def calibrate(value):
'''
Uses the calibration function of the active image to convert a raw pixel value to a density calibrated value.
The argument must be an integer in the range 0-255 (for 8-bit images) or 0-65535 (for 16-bit images).
Returns the same value if the active image does not have a calibration function.
'''
cValue = IJ.getImage().getCalibration().getCValue(value)
return cValue
def call(classAndMethodName, *args):
'''
Calls a public static method in a Java class, passing an arbitrary number of string arguments, and returning a string.
Refer to the `CallJavaDemo`_ macro and the `ImpProps`_ plugin for examples.
.. _`CallJavaDemo`: https://imagej.net/macros/CallJavaDemo.txt
.. _`ImpProps`: https://imagej.net/plugins/imp-props.html
'''
index = classAndMethodName.rfind('.')
className = classAndMethodName[0:index]
methodName = classAndMethodName[index+1:len(classAndMethodName)]
aClass = importlib.import_module(className)
res = getattr(aClass, methodName)(*args)
return res
def changeValues(low, high, newValue):
'''
Changes pixels in the image or selection that have a value in the range v1-v2 to v3.
For example, changeValues(0,5,5) changes all pixels less than 5 to 5, and changeValues(0x0000ff,0x0000ff,0xff0000)
changes all blue pixels in an RGB image to red.
In ImageJ 1.52d or later, use changeValues(NaN,NaN,value) to replaces NaN values.
'''
image = IJ.getImage()
ip = image.getProcessor()
roi = image.getRoi()
width = image.getWidth()
height = image.getHeight()
isFloat = image.getBitDepth()==32
if image.getBitDepth()==24:
low = int(low&0xffffff)
high = int(high&0xffffff)
if roi is None:
roi = Roi(0,0,width,height)
replaceNaN = False
if Double.isNaN(low) and Double.isNaN(high):
replaceNaN = True
for p in roi:
if isFloat:
value = ip.getPixelValue(p.x,p.y)
else:
value = ip.getPixel(p.x,p.y)&0xffffff;
if (value>=low and value<=high) or replaceNaN:
if isFloat:
ip.putPixelValue(p.x, p.y, newValue)
else:
ip.putPixel(p.x, p.y, int(newValue));
image.updateAndDraw()
def charCodeAt(aString, index):
'''
Returns the Unicode value of the character at the specified index in string.
Index values can range from 0 to lengthOf(string).
Use the fromCharCode() function to convert one or more Unicode characters to a string.
'''
if index<0 or index>len(aString)-1:
raise Exception("Index ("+str(index)+") is outside of the "+str(0)+"-"+str(len(aString)-1)+" range")
uString = aString.decode("utf-8")
ch = uString[index]
return ord(ch)
def close(pattern=""):
'''
Closes the active image.
This function has the advantage of not closing the "Log" or "Results" window when you meant
to close the active image. Use run("Close") to close non-image windows.
close(pattern)
Closes windows whose title matches 'pattern', which can contain the wildcard characters '*' (matches any character sequence)
and '?' (matches single character). For example, close("Histo*") could be used to dispose all histogram windows.
Non-image windows like "Roi Manager" have to be specified without wildcards. For text windows, wildcards are allowed if
'pattern' ends with ".txt", ".ijm", ".js" etc. Use close("*") to close all image windows. Use close(pattern, "keep")
to not close text or image windows with changes. If 'pattern' is "\\Others", all images except the front image are closed.
The most recent macro window is never closed.
close("*")
Closes all image windows.
close("\\Others")
Closes all images except for the front image.
'''
if (pattern==""):
value = IJ.runMacro("close();")
else:
macro = 'close("'+pattern+'")'
value = IJ.runMacro(macro)
return value
def cos(angle):
'''
Returns the cosine of an angle (in radians).
'''
return math.cos(angle)
def d2s(n, decimalPlaces):
'''
Converts the number n into a string using the specified number of decimal places.
Uses scientific notation if 'decimalPlaces is negative. Note that d2s stands for "double to string".
Note: In python 2 the division a/b is an integer division. To use float division make one of the operands a float, or
change the general behaviour with
from __future__ import division
'''
return IJ.d2s(n, decimalPlaces)
def debug(arg):
'''
Start debugging.
We can't use the ij-debugger for python. Call pdb instead, but this will only
work when running from an interactive shell not from the editor.
'''
import pdb; pdb.set_trace()
class Dialog(object):
'''
Dialog.create(title) creates a modal dialog box with the specified title, or use Dialog.createNonBlocking("Title") to create a non-modal dialog.
Call Dialog.addString(), Dialog.addNumber(), etc. to add components to the dialog. Call Dialog.show() to display the dialog
and Dialog.getString(), Dialog.getNumber(), etc. to retrieve the values entered by the user.
Refer to the `DialogDemo`_ macro for an example.
.. _`DialogDemo`: https://imagej.net/macros/DialogDemo.txt
'''
GD = None
@classmethod
def create(cls, title):
'''
Creates a modal dialog box with the specified title.
'''
cls.GD = GenericDialog(title)
return cls.GD
@classmethod
def createNonBlocking(cls, title):
'''
Creates a non-modal dialog box with the specified title.
'''
cls.GD = NonBlockingGenericDialog(title)
return cls.GD
@classmethod
def addMessage(cls, string, fontSize=None, fontColor=None):
'''
Adds a message to the dialog using a specified font size and color (`example`_).
The message can be broken into multiple lines by inserting new line characters ("\\n") into the string.
The 'fontSize' and 'fontColor' arguments are optional. Requires 1.52q.
.. _`example`: https://imagej.net/macros/examples/DialogMessageDemo.txt
'''
if (fontSize is None):
cls.GD.addMessage(string)
return cls.GD
font = Font("SansSerif", Font.PLAIN, int((fontSize*Prefs.getGuiScale())));
if (fontColor is None):
cls.GD.addMessage(string, font)
return cls.GD
color = Colors.decode(fontColor, Color.BLACK)
cls.GD.addMessage(string, font, color)
return cls.GD
@classmethod
def addString(cls, label, initialText, columns=8):
'''
Adds a text field to the dialog, where *columns* specifies the field width in characters.
'''
cls.GD.addStringField(label, initialText, columns)
return cls.GD
@classmethod
def addNumber(cls, label, default, decimalPlaces=None, columns=6, units=""):
'''
Adds a numeric field, using the specified label and default value.
DecimalPlaces specifies the number of digits to right of decimal point, columns specifies
the field width in characters and units is a string that is displayed to the right of the field.
'''
if decimalPlaces is None:
if isinstance(default, int):
decimalPlaces = 0
else:
decimalPlaces = 3
cls.GD.addNumericField(label, default, decimalPlaces, columns, units)
return cls.GD
@classmethod
def addSlider(cls, label, minimum, maximum, default):
'''
Adds a slider controlled numeric field to the dialog, using the specified label, and min, max and default values (`example`_).
Values with decimal points are used when (max-min)<=5 and min, max or default are non-integer.
.. _`example`: https://imagej.net/macros/examples/SliderDemo.txt
'''
stepSize = 0.0
if ((maximum - minimum) <= 5) and (isinstance(minimum, float) or isinstance(maximum, float) or isinstance(default, float)):
stepSize = (maximum - minimum) / 100.0
if stepSize is 0.0:
cls.GD.addSlider(label, minimum, maximum, default)
else:
cls.GD.addSlider(label, minimum, maximum, default, stepSize)
return cls.GD
@classmethod
def addCheckbox(cls, label, default):
'''
Adds a checkbox to the dialog, using the specified label and default state (true or false).
'''
if default:
default = True
else:
default = False
cls.GD.addCheckbox(label, default)
return cls.GD
@classmethod
def addCheckboxGroup(cls, rows, columns, labels, defaults):
'''
Adds a rowsxcolumns grid of checkboxes to the dialog, using the specified labels and default states (`example`_).
.. _`example`: https://imagej.net/macros/AddCheckboxGroupDemo.txt
if not len(labels) is len(defaults):
raise Exception('labels.length!=states.length')
cls.GD.addCheckboxGroup(rows, columns, labels, defaults)
return cls.GD
'''
if not len(labels) is len(defaults):
raise Exception('labels.length!=states.length')
states = [aBool and True for aBool in defaults]
cls.GD.addCheckboxGroup(rows, columns, labels, states)
return cls.GD
@classmethod
def addRadioButtonGroup(cls, label, items, rows, columns, default):
'''
Adds a group of radio buttons to the dialog.
'label' is the group label, 'items' is an array containing the button labels,
'rows' and 'columns' specify the grid size, and 'default' is the label of the default button. (`example`_).
.. _`example`: https://imagej.net/macros/examples/RadioButtonDemo.txt
'''
cls.GD.addRadioButtonGroup(label, items, rows, columns, default)
return cls.GD
@classmethod
def addChoice(cls, label, items, default=None):
'''
Adds a popup menu.
items is a string array containing the choices and default is the default choice.
'''
if default==None:
default = items[0]
cls.GD.addChoice(label, items, default)
return cls.GD
@classmethod
def addHelp(cls, urlOrHTML):
'''
Adds a "Help" button that opens the specified URL in the default browser.
This can be used to supply a help page for this dialog or macro. With v1.46b or later,
displays an HTML formatted message if 'url' starts with "<html>" (`example`_).
.. _`example`: https://imagej.net/macros/examples/DialogWithHelp.txt
'''
cls.GD.addHelp(urlOrHTML)
return cls.GD
@classmethod
def addToSameRow(cls):
'''
Makes the next item added appear on the same row as the previous item.
May be used for addNumericField, addSlider, addChoice, addCheckbox, addString, addMessage,
and before the showDialog() method. In the latter case, the buttons appear to the right of
the previous item.
Note that addMessage (and addString if a width of more than 8 is specified) use the remaining width,
so it must be the last item of a row. Requires 1.51r.
'''
cls.GD.addToSameRow()
return cls.GD
@classmethod
def setInsets(cls, top, left, bottom):
'''
Overrides the default insets (margins) used for the next component added to the dialog.
Default insets:
addMessage: 0,20,0 (empty string) or 10,20,0
addCheckbox: 15,20,0 (first checkbox) or 0,20,0
addCheckboxGroup: 10,0,0
addNumericField: 5,0,3 (first field) or 0,0,3
addStringField: 5,0,5 (first field) or 0,0,5
addChoice: 5,0,5 (first field) or 0,0,5
'''
cls.GD.setInsets(top, left, bottom)
return cls.GD
@classmethod
def setLocation(cls, x, y):
'''
Sets the screen location where this dialog will be displayed.
'''
cls.GD.setLocation(x, y)
return cls.GD
@classmethod
def show(cls):
'''
Displays the dialog and waits until the user clicks "OK" or "Cancel".
In ij the macro terminates if the user clicks "Cancel". This doesn't work in ijmpy.
This means the variables will be set to the default values even if the user cancels
the dialog. To avoid this, use:
if not Dialog.show().wasCanceled():
name = Dialog.getString();
...
'''
cls.GD.showDialog()
return cls.GD
@classmethod
def getString(cls):
'''
Returns a string containing the contents of the next text field.
'''
return cls.GD.getNextString()
@classmethod
def getNumber(cls):
'''
Returns the contents of the next numeric field.
'''
return cls.GD.getNextNumber()
@classmethod
def getCheckbox(cls):
'''
Returns the state (true or false) of the next checkbox.
'''
if cls.GD.getNextBoolean():
return true
else:
return false
@classmethod
def getRadioButton(cls):
'''
Returns the selected item (a string) from the next radio button group.
'''
return cls.GD.getNextRadioButton()
@classmethod
def getChoice(cls):
'''
Returns the selected item (a string) from the next popup menu.
'''
return cls.GD.getNextChoice()
def doCommand(command):
'''
Runs an ImageJ menu command in a separate thread and returns immediately.
As an example, doCommand("Start Animation") starts animating the current stack in a separate thread
and the macro continues to execute. Use run("Start Animation") and the macro hangs until the user stops the animation.
'''
if command == "Start Animation":
command = "Start Animation [\\]"
IJ.doCommand(command)
def doWand(x, y, tolerance=0, mode=None):
'''
Equivalent to clicking on the current image at (x,y) with the wand tool.
Note that some objects, especially one pixel wide lines, may not be reliably traced unless they have been
thresholded (highlighted in red) using setThreshold.
Traces the boundary of the area with pixel values within `tolerance` of the value of the pixel at (x,y).
`mode` can be "4-connected", "8-connected" or "Legacy". "Legacy" is for compatibility with previous versions of ImageJ;
it is ignored if "tolerance > 0". If `mode` contains "smooth", the contour is smoothed by interpolation (`example`_).
.. _`example`: https://imagej.net/macros/examples/SmoothLetters.txt
'''
IJ.doWand(x, y, tolerance, mode)
return IJ.getImage().getRoi()
def drawLine(x1, y1, x2, y2):
'''
Draws a line between (x1, y1) and (x2, y2).
Use setColor() to specify the color of the line and setLineWidth() to vary the line width.
See also:
=========
Overlay.drawLine
'''
imp = IJ.getImage()
imp.getProcessor().drawLine(x1, y1, x2, y2)
__updateAndDraw()
return imp
def drawOval(x, y, width, height):
'''
Draws the outline of an oval using the current color and line width.
See also:
=========
`fillOval`_, setColor, setLineWidth, `autoUpdate`_ and Overlay.drawEllipse.
.. _`fillOval`: redirect.html#mripy.ijmpy.fillOval
.. _`autoUpdate`: redirect.html#mripy.ijmpy.autoUpdate
'''
imp = IJ.getImage()
imp.getProcessor().drawOval(x, y, width, height)
__updateAndDraw()
return imp
def drawRect(x, y, width, height):
'''
Draws the outline of a rectangle using the current color and line width.
See also:
=========
`fillRect`_, setColor, setLineWidth, `autoUpdate`_ and Overlay.drawRect
.. _`fillRect`: redirect.html#mripy.ijmpy.fillRect
.. _`autoUpdate`: redirect.html#mripy.ijmpy.autoUpdate
'''
imp = IJ.getImage()
imp.getProcessor().drawRect(x, y, width, height)
__updateAndDraw()
return imp
def drawString(aText, x, y, background=None):
'''
Draws text at the specified location with a filled background.
The first character is drawn obove and to the right of (x,y). Call setFont() to specify the font.
Call setJustification() to have the text centered or right justified. Call getStringWidth() to get
the width of the text in pixels. Refer to the TextDemo macro for examples and to DrawTextWithBackground
to see how to draw text with a background.
'''
ip = IJ.getImage().getProcessor()
if not Settings.FONT is None:
ip.setFont(Settings.FONT)
ip.setJustification(Settings.JUSTIFICATION);
ip.setAntialiasedText(Settings.ANTIALIASED_TEXT)
if not background is None:
aColor = __getColor(background)
ip.drawString(aText, x, y, aColor)
else:
if not Settings.GLOBAL_COLOR is None:
ip.setColor(Settings.GLOBAL_COLOR)
else:
ip.setColor(Toolbar.getForegroundColor())
ip.drawString(aText, x, y)
__updateAndDraw()
def dump():
'''
Writes the contents of the symbol table, the tokenized script code and the variable stack to the "Log" window.
In ijmpy you need to save the script before creating a dump.
'''
bfuncs = [name for name, function in sorted(vars(__builtin__).items()) if inspect.isbuiltin(function) or inspect.isfunction(function)]
locs = inspect.currentframe().f_back.f_globals
keys = locs.keys()
wantedKeys = []
for key in keys:
if type(locs[key]) in [types.TypeType, types.FunctionType]:
wantedKeys.append(key)