File: CalibrationBar.java

package info (click to toggle)
imagej 1.52j-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 5,604 kB
  • sloc: java: 120,017; sh: 279; xml: 161; makefile: 6
file content (471 lines) | stat: -rw-r--r-- 13,737 bytes parent folder | download
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
package ij.plugin;
import ij.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import java.io.*;
import java.awt.datatransfer.*;
import ij.gui.*;
import ij.process.*;
import ij.measure.Measurements;
import ij.plugin.filter.Analyzer;
import ij.text.TextWindow;
import ij.measure.*;

/** This plugin implements the Analyze/Tools/Calibration Bar command.
	Bob Dougherty, OptiNav, Inc., 4/14/2002
	Based largely on HistogramWindow.java by Wayne Rasband.
	July 2002: Modified by Daniel Marsh and renamed CalibrationBar.
	January 2013: Displays calibration bar as an overlay.
*/

public class CalibrationBar implements PlugIn {
	final static int BAR_LENGTH = 128;
	final static int BAR_THICKNESS = 12;
	final static int XMARGIN = 10;
	final static int YMARGIN = 10;
	final static int WIN_HEIGHT = BAR_LENGTH;
	final static int BOX_PAD = 0;
	final static String CALIBRATION_BAR = "|CB|";
	static int nBins = 256;
	static final String[] colors = {"White","Light Gray","Dark Gray","Black","Red","Green","Blue","Yellow","None"};
	static final String[] locations = {"Upper Right","Lower Right","Lower Left", "Upper Left", "At Selection"};
	static final int UPPER_RIGHT=0, LOWER_RIGHT=1, LOWER_LEFT=2, UPPER_LEFT=3, AT_SELECTION=4;

	private static String sFillColor = colors[0];
	private static String sTextColor = colors[3];
	private static String sLocation = locations[UPPER_RIGHT];
	private static double sZoom = 1;
	private static int sNumLabels = 5;
	private static int sFontSize = 12;
	private static int sDecimalPlaces = 0;
	private static boolean sFlatten;
	
	private String fillColor = sFillColor;
	private String textColor = sTextColor;
	private String location = sLocation;
	private double zoom = sZoom;
	private int numLabels = sNumLabels;
	private int fontSize = sFontSize;
	private int decimalPlaces = sDecimalPlaces;
	private boolean flatten = sFlatten;

	ImagePlus imp;
	LiveDialog gd;

	ImageStatistics stats;
	Calibration cal;
	int[] histogram;
	Image img;
	Button setup, redraw, insert, unInsert;
	Checkbox ne,nw,se,sw;
	CheckboxGroup locGroup;
	Label value, note;
	int newMaxCount;
	boolean logScale;
	int win_width;
	int userPadding = 0;
	int fontHeight = 0;
	boolean boldText;
	boolean showUnit;
	Object backupPixels;
	byte[] byteStorage;
	int[] intStorage;
	short[] shortStorage;
	float[] floatStorage;
	String boxOutlineColor = colors[8];
	String barOutlineColor = colors[3];
	
	ImageProcessor ip;
	String[] fieldNames = null;
	int insetPad;
	boolean decimalPlacesChanged;

	public void run(String arg) {
		imp = IJ.getImage();
		if (imp.getBitDepth()==24 || imp.getCompositeMode()==IJ.COMPOSITE) {
			IJ.error("Calibration Bar", "RGB and composite images are not supported");
			return;
		}
		if (imp.getRoi()!=null && imp.getRoi().isArea())
			location = locations[AT_SELECTION];
		else if (location.equals(locations[AT_SELECTION]))
			location = locations[UPPER_RIGHT];
		ImageCanvas ic = imp.getCanvas();
		double mag = (ic!=null)?ic.getMagnification():1.0;
		if (zoom<=1 && mag<1)
			zoom = (double) 1.0/mag;
		insetPad = (imp.getWidth()+imp.getHeight())/100;
		if (insetPad<4)
			insetPad = 4;
		updateColorBar();
		if (IJ.isMacro()) {
			flatten = true;
			fillColor = colors[0];
			textColor = colors[3];
			location = locations[UPPER_RIGHT];
			zoom = 1;
			numLabels = 5;
			fontSize = 12;
			decimalPlaces = 0;
		}
		if (!showDialog()) {
			Overlay overlay = imp.getOverlay();
			if (overlay!=null) {
				overlay.remove(CALIBRATION_BAR);
				imp.draw();
			}
			return;
		}
		updateColorBar();
		if (flatten) {
			imp.deleteRoi();
			IJ.wait(100);
			ImagePlus imp2 = imp.flatten();
			imp2.setTitle(imp.getTitle()+" with bar");
			Overlay overlay = imp.getOverlay();
			if (overlay!=null) {
				overlay.remove(CALIBRATION_BAR);
				imp.draw();
			}
			imp2.show();
		}
	}

	private void updateColorBar() {
		Roi roi = imp.getRoi();
		if (roi!=null &&  location.equals(locations[AT_SELECTION])) {
			Rectangle r = roi.getBounds();
			drawBarAsOverlay(imp, r.x, r.y);
		} else if ( location.equals(locations[UPPER_LEFT]))
			drawBarAsOverlay(imp, insetPad, insetPad);
		else if (location.equals(locations[UPPER_RIGHT])) {
			calculateWidth();
			drawBarAsOverlay(imp, imp.getWidth()-insetPad-win_width, insetPad);
		} else if (location.equals(locations[LOWER_LEFT]) )
			drawBarAsOverlay(imp, insetPad,imp.getHeight() - (int)(WIN_HEIGHT*zoom + 2*(int)(YMARGIN*zoom)) - (int)(insetPad*zoom));
		else if(location.equals(locations[LOWER_RIGHT])) {
			calculateWidth();
			drawBarAsOverlay(imp, imp.getWidth()-win_width-insetPad,
				 imp.getHeight() - (int)(WIN_HEIGHT*zoom + 2*(int)(YMARGIN*zoom)) - insetPad);
		}
		this.imp.updateAndDraw();
	}

	private boolean showDialog() {
		gd = new LiveDialog("Calibration Bar");
		gd.addChoice("Location:", locations, location);
		gd.addChoice("Fill color: ", colors, fillColor);
		gd.addChoice("Label color: ", colors, textColor);
		gd.addNumericField("Number of labels:", numLabels, 0);
		gd.addNumericField("Decimal places:", decimalPlaces, 0);
		gd.addNumericField("Font size:", fontSize, 0);
		gd.addNumericField("Zoom factor:", zoom, 1);
		String[] labels = {"Bold text", "Overlay", "Show unit"};
		boolean[] states = {boldText, !flatten, showUnit};
		gd.setInsets(10, 30, 0);
		gd.addCheckboxGroup(2, 2, labels, states);
		gd.showDialog();
		if (gd.wasCanceled())
			return false;
		location = gd.getNextChoice();
		fillColor = gd.getNextChoice();
		textColor = gd.getNextChoice();
		numLabels = (int)gd.getNextNumber();
		decimalPlaces = (int)gd.getNextNumber();
		fontSize = (int)gd.getNextNumber();
		zoom = (double)gd.getNextNumber();
		boldText = gd.getNextBoolean();
		flatten = !gd.getNextBoolean();
		showUnit = gd.getNextBoolean();
		if (!IJ.isMacro()) {
			sFlatten = flatten;
			sFillColor = fillColor;
			sTextColor = textColor;
			sLocation = location;
			sZoom = zoom;
			sNumLabels = numLabels;
			sFontSize = fontSize;
			sDecimalPlaces = decimalPlaces;
		}
		return true;
	}

	private void drawBarAsOverlay(ImagePlus imp, int x, int y) {
		Roi roi = imp.getRoi();
		if (roi!=null)
			imp.deleteRoi();
		stats = imp.getStatistics(Measurements.MIN_MAX, nBins);
		if (roi!=null)
			imp.setRoi(roi);
		histogram = stats.histogram;
		cal = imp.getCalibration();
		Overlay overlay = imp.getOverlay();
		if (overlay==null)
			overlay = new Overlay();
		else
			overlay.remove(CALIBRATION_BAR);
		int maxTextWidth = addText(null, 0, 0);
		win_width = (int)(XMARGIN*zoom) + 5 + (int)(BAR_THICKNESS*zoom) + maxTextWidth + (int)((XMARGIN/2)*zoom);
		if (x==-1 && y==-1)
			return;	 // return if calculating width
		Color c = getColor(fillColor);
		if (c!=null) {
			Roi r = new Roi(x, y, win_width, (int)(WIN_HEIGHT*zoom + 2*(int)(YMARGIN*zoom)));
			r.setFillColor(c);
			overlay.add(r, CALIBRATION_BAR);
		}
		int xOffset = x;
		int yOffset = y;
		if (decimalPlaces == -1)
			decimalPlaces = Analyzer.getPrecision();
		x = (int)(XMARGIN*zoom) + xOffset;
		y = (int)(YMARGIN*zoom) + yOffset;
		addVerticalColorBar(overlay, x, y, (int)(BAR_THICKNESS*zoom), (int)(BAR_LENGTH*zoom) );
		addText(overlay, x + (int)(BAR_THICKNESS*zoom), y);
		c = getColor(boxOutlineColor);
		overlay.setIsCalibrationBar(true);
		if (imp.getCompositeMode()>0) {
			for (int i=0; i<overlay.size(); i++)
				overlay.get(i).setPosition(imp.getC(), 0, 0);
		}
		imp.setOverlay(overlay);
	}
	
	private void addVerticalColorBar(Overlay overlay, int x, int y, int thickness, int length) {
		int width = thickness;
		int height = length;
		byte[] rLUT,gLUT,bLUT;
		int mapSize = 0;
		java.awt.image.ColorModel cm = imp.getProcessor().getCurrentColorModel();
		if (cm instanceof IndexColorModel) {
			IndexColorModel m = (IndexColorModel)cm;
			mapSize = m.getMapSize();
			rLUT = new byte[mapSize];
			gLUT = new byte[mapSize];
			bLUT = new byte[mapSize];
			m.getReds(rLUT);
			m.getGreens(gLUT);
			m.getBlues(bLUT);
		} else {
			mapSize = 256;
			rLUT = new byte[mapSize];
			gLUT = new byte[mapSize];
			bLUT = new byte[mapSize];
			for (int i = 0; i < mapSize; i++) {
				rLUT[i] = (byte)i;
				gLUT[i] = (byte)i;
				bLUT[i] = (byte)i;
			}
		}
		double colors = mapSize;
		int start = 0;
		ImageProcessor ipOrig =imp.getProcessor();
		if (ipOrig instanceof ByteProcessor) {
			int min = (int)ipOrig.getMin();
			if (min<0) min = 0;
			int max = (int)ipOrig.getMax();
			if (max>255) max = 255;
			colors = max-min+1;
			start = min;
		}
		for (int i = 0; i<(int)(BAR_LENGTH*zoom); i++) {
			int iMap = start + (int)Math.round((i*colors)/(BAR_LENGTH*zoom));
			if (iMap>=mapSize)
				iMap =mapSize - 1;
			int j = (int)(BAR_LENGTH*zoom) - i - 1;
			Line line = new Line(x, j+y, thickness+x, j+y);
			line.setStrokeColor(new Color(rLUT[iMap]&0xff, gLUT[iMap]&0xff, bLUT[iMap]&0xff));
			line.setStrokeWidth(1.0001);
			overlay.add(line, CALIBRATION_BAR);
		}

		Color c = getColor(barOutlineColor);
		if (c!=null) {
			Roi r = new Roi(x, y, width, height);
			r.setStrokeColor(c);
			r.setStrokeWidth(1.0);
			overlay.add(r, CALIBRATION_BAR);
		}
	}

	private int addText(Overlay overlay, int x, int y) {

		Color c = getColor(textColor);
		if (c == null)
			return 0;
		double hmin = cal.getCValue(stats.histMin);
		double hmax = cal.getCValue(stats.histMax);
		double barStep = (double)(BAR_LENGTH*zoom) ;
		if (numLabels > 2)
			barStep /= (numLabels - 1);

		int fontType = boldText?Font.BOLD:Font.PLAIN;
		Font font = null;
		if (fontSize<9)
			font = new Font("SansSerif", fontType, 9);
		else
			font = new Font("SansSerif", fontType, (int)( fontSize*zoom));
		int maxLength = 0;

		//Blank offscreen image for font metrics
		Image img = GUI.createBlankImage(128, 64);
		Graphics g = img.getGraphics();
		FontMetrics metrics = g.getFontMetrics(font);
		fontHeight = metrics.getHeight();

		for (int i = 0; i < numLabels; i++) {
			double yLabelD = (int)(YMARGIN*zoom + BAR_LENGTH*zoom - i*barStep - 1);
			int yLabel = (int)(Math.round( y + BAR_LENGTH*zoom - i*barStep - 1));
			Calibration cal = imp.getCalibration();
			String s = "";
			if (showUnit)
				s = cal.getValueUnit();
			ImageProcessor ipOrig = imp.getProcessor();
			double min = ipOrig.getMin();
			double max = ipOrig.getMax();
			if (ipOrig instanceof ByteProcessor) {
				if (min<0) min = 0;
				if (max>255) max = 255;
			}
			double grayLabel = min + (max-min)/(numLabels-1) * i;
			if (cal.calibrated()) {
				grayLabel = cal.getCValue(grayLabel);
				double cmin = cal.getCValue(min);
				double cmax = cal.getCValue(max);
				if (!decimalPlacesChanged && decimalPlaces==0 && ((int)cmax!=cmax||(int)cmin!=cmin))
					decimalPlaces = 2;
			}
			String todisplay = d2s(grayLabel)+" "+s;
			if (overlay!=null) {
				TextRoi label = new TextRoi(todisplay, x + 5, yLabel + fontHeight/2, font);				
				label.setStrokeColor(c);
				overlay.add(label, CALIBRATION_BAR);
			}
			int iLength = metrics.stringWidth(todisplay);
			if (iLength > maxLength)
				maxLength = iLength+5;
		}
		return maxLength;
	}
		
	String d2s(double d) {
			return IJ.d2s(d,decimalPlaces);
	}

	int getFontHeight() {
		Image img = GUI.createBlankImage(64, 64); //dummy version to get fontHeight
		Graphics g = img.getGraphics();
		int fontType = boldText?Font.BOLD:Font.PLAIN;
		Font font = new Font("SansSerif", fontType, (int) (fontSize*zoom) );
		FontMetrics metrics = g.getFontMetrics(font);
		return	metrics.getHeight();
	}

	Color getColor(String color) {
		Color c = Color.white;
		if (color.equals(colors[1]))
			c = Color.lightGray;
		else if (color.equals(colors[2]))
			c = Color.darkGray;
		else if (color.equals(colors[3]))
			c = Color.black;
		else if (color.equals(colors[4]))
			c = Color.red;
		else if (color.equals(colors[5]))
			c = Color.green;
		else if (color.equals(colors[6]))
			c = Color.blue;
		else if (color.equals(colors[7]))
			c = Color.yellow;
		else if (color.equals(colors[8]))
			c = null;
		return c;
	}	 

	void calculateWidth() {
		drawBarAsOverlay(imp, -1, -1);
	}
		
	class LiveDialog extends GenericDialog {

		LiveDialog(String title) {
			super(title);
		}

		public void textValueChanged(TextEvent e) {

			if (fieldNames == null) {
				fieldNames = new String[4];
				for(int i=0;i<4;i++)
					fieldNames[i] = ((TextField)numberField.elementAt(i)).getName();
			}

			TextField tf = (TextField)e.getSource();
			String name = tf.getName();
			String value = tf.getText();

			if (value.equals(""))
				return;

			int i=0;
			boolean needsRefresh = false;

			if (name.equals(fieldNames[0])) {

				i = getValue( value ).intValue() ;
				if(i<1)
					return;
				else {
					needsRefresh = true;
					numLabels = i;
				}
			} else if (name.equals(fieldNames[1])) {
				i = getValue( value ).intValue() ;
				if (i<0)
					return;
				else {
					needsRefresh = true;
					decimalPlaces = i;
					decimalPlacesChanged = true;
				}

			} else if (name.equals(fieldNames[2])) {
				i = getValue( value ).intValue() ;
				if(i<1)
					return;
				else {
					needsRefresh = true;
					fontSize = i;

				}

			} else if (name.equals(fieldNames[3])) {
				double d = 0;
				d = getValue( "0" + value ).doubleValue() ;
				if(d<=0)
					return;
				else {
					needsRefresh = true;
					zoom = d;
				}
			}

			if (needsRefresh)
				updateColorBar();
			return;
		}

		public void itemStateChanged(ItemEvent e) {
			location = ( (Choice)(choice.elementAt(0)) ).getSelectedItem();
			fillColor = ( (Choice)(choice.elementAt(1)) ).getSelectedItem();
			textColor = ( (Choice)(choice.elementAt(2)) ).getSelectedItem();
			boldText = ( (Checkbox)(checkbox.elementAt(0)) ).getState();
			flatten = !( (Checkbox)(checkbox.elementAt(1)) ).getState();
			showUnit = ( (Checkbox)(checkbox.elementAt(2)) ).getState();
			updateColorBar();
		}

	} //LiveDialog inner class

}