12 boolean classicEqualization;
14 static boolean equalize;
15 static boolean normalize;
16 static double saturated = 0.5;
18 public void run(String arg) {
27 stretchHistogram(imp, saturated);
28 if (equalize || normalize)
35 GenericDialog gd =
new GenericDialog(
"Enhance Contrast");
36 gd.addNumericField(
"Saturated Pixels:", saturated, 1, 4,
"%");
38 gd.addCheckbox(
"Normalize", normalize);
39 gd.addCheckbox(
"Equalize Histogram", equalize);
43 saturated = gd.getNextNumber();
45 normalize = gd.getNextBoolean();
48 equalize = gd.getNextBoolean();
49 if (saturated<0.0) saturated = 0.0;
50 if (saturated>100.0) saturated = 100;
54 public void stretchHistogram(
ImagePlus imp,
double saturated) {
58 public void stretchHistogram(ImageProcessor ip,
double saturated) {
59 ImageStatistics stats = ImageStatistics.getStatistics(ip, MIN_MAX, null);
62 int[] histogram = stats.histogram;
64 threshold = (int)(stats.pixelCount*saturated/200.0);
68 boolean found =
false;
72 count += histogram[i];
73 found = count>threshold;
74 }
while (!found && i<255);
81 count += histogram[i];
82 found = count>threshold;
84 }
while (!found && i>0);
89 double min = stats.histMin+hmin*stats.binSize;
90 double max = stats.histMin+hmax*stats.binSize;
92 normalize(ip, min, max);
94 ip.setMinAndMax(min, max);
98 void normalize(ImageProcessor ip,
double min,
double max) {
102 if (ip instanceof ShortProcessor)
103 {max2 = 65535; range=65536;}
104 else if (ip instanceof FloatProcessor)
105 normalizeFloat(ip, min, max);
108 int[] lut =
new int[range];
109 for (
int i=0; i<range; i++) {
115 lut[i] = (int)(((
double)(i-min)/(max-min))*max2);
120 void normalizeFloat(ImageProcessor ip,
double min,
double max) {
121 double scale = max>min?1.0/(max-min):1.0;
122 int size = ip.getWidth()*ip.getHeight();
123 float[] pixels = (
float[])ip.getPixels();
125 for (
int i=0; i<size; i++) {
130 pixels[i] = (float)v;
135 public void equalize(ImagePlus imp) {
136 if (imp.getBitDepth()==32) {
137 IJ.showMessage(
"Contrast Enhancer",
"Equalization of 32-bit images not supported.");
140 classicEqualization = IJ.altKeyDown();
141 equalize(imp.getProcessor());
156 int[] histogram = ip.getHistogram();
158 if (ip instanceof ShortProcessor) {
168 sum = getWeightedValue(histogram, 0);
169 for (
int i=1; i<max; i++)
170 sum += 2 * getWeightedValue(histogram, i);
171 sum += getWeightedValue(histogram, max);
173 double scale = range/sum;
174 int[] lut =
new int[range+1];
177 sum = getWeightedValue(histogram, 0);
178 for (
int i=1; i<max; i++) {
179 double delta = getWeightedValue(histogram, i);
181 lut[i] = (int)Math.round(sum*scale);
189 private double getWeightedValue(
int[] histogram,
int i) {
190 int h = histogram[i];
191 if (h<2 || classicEqualization)
return (
double)h;
192 return Math.sqrt((
double)(h));