use of ij.process.ImageStatistics in project TrakEM2 by trakem2.
the class ContrastEnhancerWrapper method apply.
public boolean apply(final Collection<Displayable> patches_) {
if (null == patches_)
return false;
// Create appropriate patch list
ArrayList<Patch> patches = new ArrayList<Patch>();
for (final Displayable d : patches_) {
if (d.getClass() == Patch.class)
patches.add((Patch) d);
}
if (0 == patches.size())
return false;
// Check that all images are of the same size and type
Patch firstp = (Patch) patches.get(0);
final int ptype = firstp.getType();
final double pw = firstp.getOWidth();
final double ph = firstp.getOHeight();
for (final Patch p : patches) {
if (p.getType() != ptype) {
// can't continue
Utils.log("Can't homogenize histograms: images are not all of the same type.\nFirst offending image is: " + p);
return false;
}
if (!equalize && 0 == stats_mode && p.getOWidth() != pw || p.getOHeight() != ph) {
Utils.log("Can't homogenize histograms: images are not all of the same size.\nFirst offending image is: " + p);
return false;
}
}
try {
if (equalize) {
for (final Patch p : patches) {
if (Thread.currentThread().isInterrupted())
return false;
p.appendFilters(new IFilter[] { new EqualizeHistogram() });
/*
p.getProject().getLoader().releaseToFit(p.getOWidth(), p.getOHeight(), p.getType(), 3);
ImageProcessor ip = p.getImageProcessor().duplicate(); // a throw-away copy
if (this.from_existing_min_and_max) {
ip.setMinAndMax(p.getMin(), p.getMax());
}
ce.equalize(ip);
p.setMinAndMax(ip.getMin(), ip.getMax());
*/
// submit for regeneration
p.getProject().getLoader().decacheImagePlus(p.getId());
regenerateMipMaps(p);
}
return true;
}
// Else, call stretchHistogram with an appropriate stats object
final ImageStatistics stats;
if (1 == stats_mode) {
// use each image independent stats
stats = null;
} else if (0 == stats_mode) {
// use stack statistics
final ArrayList<Patch> sub = new ArrayList<Patch>();
if (use_full_stack) {
sub.addAll(patches);
} else {
// build stack statistics, ordered by stdDev
final SortedMap<Stats, Patch> sp = Collections.synchronizedSortedMap(new TreeMap<Stats, Patch>());
Process.progressive(patches, new TaskFactory<Patch, Stats>() {
public Stats process(final Patch p) {
if (Thread.currentThread().isInterrupted())
return null;
ImagePlus imp = p.getImagePlus();
p.getProject().getLoader().releaseToFit(p.getOWidth(), p.getOHeight(), p.getType(), 2);
Stats s = new Stats(imp.getStatistics());
sp.put(s, p);
return s;
}
});
if (Thread.currentThread().isInterrupted())
return false;
final ArrayList<Patch> a = new ArrayList<Patch>(sp.values());
final int count = a.size();
if (count < 3) {
sub.addAll(a);
} else if (3 == count) {
// the middle one
sub.add(a.get(1));
} else if (4 == count) {
sub.addAll(a.subList(1, 3));
} else if (count > 4) {
int first = (int) (count / 4.0 + 0.5);
int last = (int) (count / 4.0 * 3 + 0.5);
sub.addAll(a.subList(first, last));
}
}
stats = new StackStatistics(new PatchStack(sub.toArray(new Patch[sub.size()]), 1));
} else {
stats = reference_stats;
}
final Calibration cal = patches.get(0).getLayer().getParent().getCalibrationCopy();
Process.progressive(patches, new TaskFactory<Patch, Object>() {
public Object process(final Patch p) {
if (Thread.currentThread().isInterrupted())
return null;
p.getProject().getLoader().releaseToFit(p.getOWidth(), p.getOHeight(), p.getType(), 3);
// a throw-away copy
ImageProcessor ip = p.getImageProcessor().duplicate();
if (ContrastEnhancerWrapper.this.from_existing_min_and_max) {
ip.setMinAndMax(p.getMin(), p.getMax());
}
ImageStatistics st = stats;
if (null == stats) {
Utils.log2("Null stats, using image's self");
st = ImageStatistics.getStatistics(ip, Measurements.MIN_MAX, cal);
}
ce.stretchHistogram(ip, saturated, st);
// This is all we care about from stretching the histogram:
p.setMinAndMax(ip.getMin(), ip.getMax());
regenerateMipMaps(p);
return null;
}
});
} catch (Exception e) {
IJError.print(e);
return false;
}
return true;
}
use of ij.process.ImageStatistics in project TrakEM2 by trakem2.
the class FakeImagePlus method getStatistics.
// TODO: use layerset virtualization
public ImageStatistics getStatistics(int mOptions, int nBins, double histMin, double histMax) {
Displayable active = display.getActive();
if (null == active || !(active instanceof Patch)) {
Utils.log("No patch selected.");
// TODO can't return null, but something should be done about it.
return super.getStatistics(mOptions, nBins, histMin, histMax);
}
ImagePlus imp = active.getProject().getLoader().fetchImagePlus((Patch) active);
// don't create a new onw every time // ((Patch)active).getProcessor();
ImageProcessor ip = imp.getProcessor();
Roi roi = super.getRoi();
if (null != roi) {
// translate ROI to be meaningful for the Patch
int patch_x = (int) active.getX();
int patch_y = (int) active.getY();
Rectangle r = roi.getBounds();
roi.setLocation(patch_x - r.x, patch_y - r.y);
}
// even if null, to reset
ip.setRoi(roi);
ip.setHistogramSize(nBins);
Calibration cal = getCalibration();
if (getType() == GRAY16 && !(histMin == 0.0 && histMax == 0.0)) {
histMin = cal.getRawValue(histMin);
histMax = cal.getRawValue(histMax);
}
ip.setHistogramRange(histMin, histMax);
ImageStatistics stats = ImageStatistics.getStatistics(ip, mOptions, cal);
ip.setHistogramSize(256);
ip.setHistogramRange(0.0, 0.0);
return stats;
}
use of ij.process.ImageStatistics in project TrakEM2 by trakem2.
the class Loader method insertGrid.
/**
* Insert grid in layer (with optional stitching)
*
* @param layer The Layer to inser the grid into
* @param dir The base dir of the images to open
* @param first_image_name name of the first image in the list
* @param cols The list of columns, containing each an array of String file names in each column.
* @param bx The top-left X coordinate of the grid to insert
* @param by The top-left Y coordinate of the grid to insert
* @param bt_overlap bottom-top overlap of the images
* @param lr_overlap left-right overlap of the images
* @param link_images Link images to their neighbors
* @param stitch_tiles montage option
* @param cc_percent_overlap tiles overlap
* @param cc_scale tiles scaling previous to stitching (1 = no scaling)
* @param min_R regression threshold (minimum acceptable R)
* @param homogenize_contrast contrast homogenization option
* @param stitching_rule stitching rule (upper left corner or free)
*/
private void insertGrid(final Layer layer, final String dir_, final String first_image_name, final int n_images, final ArrayList<String[]> cols, final double bx, final double by, final double bt_overlap, final double lr_overlap, final boolean link_images, final boolean stitch_tiles, final boolean homogenize_contrast, final StitchingTEM.PhaseCorrelationParam pc_param, final Worker worker) {
// create a Worker, then give it to the Bureaucrat
try {
String dir = dir_;
final ArrayList<Patch> al = new ArrayList<Patch>();
Utils.showProgress(0.0D);
// less repaints on IJ status bar
opener.setSilentMode(true);
int x = 0;
int y = 0;
int largest_y = 0;
ImagePlus img = null;
// open the selected image, to use as reference for width and height
// w1nd0wz safe
dir = dir.replace('\\', '/');
if (!dir.endsWith("/"))
dir += "/";
String path = dir + first_image_name;
// TODO arbitrary x3 factor
releaseToFit(new File(path).length() * 3);
IJ.redirectErrorMessages();
ImagePlus first_img = openImagePlus(path);
if (null == first_img) {
Utils.log("Selected image to open first is null.");
return;
}
if (null == first_img)
return;
final int first_image_width = first_img.getWidth();
final int first_image_height = first_img.getHeight();
final int first_image_type = first_img.getType();
// start
final Patch[][] pall = new Patch[cols.size()][((String[]) cols.get(0)).length];
int width, height;
// counter
int k = 0;
boolean auto_fix_all = false;
boolean ignore_all = false;
boolean resize = false;
if (!ControlWindow.isGUIEnabled()) {
// headless mode: autofix all
auto_fix_all = true;
resize = true;
}
// Accumulate mipmap generation tasks
final ArrayList<Future<?>> fus = new ArrayList<Future<?>>();
startLargeUpdate();
for (int i = 0; i < cols.size(); i++) {
final String[] rows = (String[]) cols.get(i);
if (i > 0) {
x -= lr_overlap;
}
for (int j = 0; j < rows.length; j++) {
if (Thread.currentThread().isInterrupted()) {
Display.repaint(layer);
rollback();
return;
}
if (j > 0) {
y -= bt_overlap;
}
// get file name
final String file_name = (String) rows[j];
path = dir + file_name;
if (null != first_img && file_name.equals(first_image_name)) {
img = first_img;
// release pointer
first_img = null;
} else {
// open image
releaseToFit(first_image_width, first_image_height, first_image_type, 1.5f);
try {
IJ.redirectErrorMessages();
img = openImagePlus(path);
} catch (final OutOfMemoryError oome) {
printMemState();
throw oome;
}
}
if (null == img) {
Utils.log("null image! skipping.");
pall[i][j] = null;
continue;
}
width = img.getWidth();
height = img.getHeight();
int rw = width;
int rh = height;
if (width != first_image_width || height != first_image_height) {
int new_width = first_image_width;
int new_height = first_image_height;
if (!auto_fix_all && !ignore_all) {
final GenericDialog gdr = new GenericDialog("Size mismatch!");
gdr.addMessage("The size of " + file_name + " is " + width + " x " + height);
gdr.addMessage("but the selected image was " + first_image_width + " x " + first_image_height);
gdr.addMessage("Adjust to selected image dimensions?");
gdr.addNumericField("width: ", (double) first_image_width, 0);
// should not be editable ... or at least, explain in some way that the dimensions can be edited just for this image --> done below
gdr.addNumericField("height: ", (double) first_image_height, 0);
gdr.addMessage("[If dimensions are changed they will apply only to this image]");
gdr.addMessage("");
final String[] au = new String[] { "fix all", "ignore all" };
gdr.addChoice("Automate:", au, au[1]);
gdr.addMessage("Cancel == NO OK = YES");
gdr.showDialog();
if (gdr.wasCanceled()) {
resize = false;
// do nothing: don't fix/resize
}
resize = true;
// catch values
new_width = (int) gdr.getNextNumber();
new_height = (int) gdr.getNextNumber();
final int iau = gdr.getNextChoiceIndex();
if (new_width != first_image_width || new_height != first_image_height) {
auto_fix_all = false;
} else {
auto_fix_all = (0 == iau);
}
ignore_all = (1 == iau);
if (ignore_all)
resize = false;
}
if (resize) {
// resize Patch dimensions
rw = first_image_width;
rh = first_image_height;
}
}
// add new Patch at base bx,by plus the x,y of the grid
// will call back and cache the image
final Patch patch = new Patch(layer.getProject(), img.getTitle(), bx + x, by + y, img);
if (width != rw || height != rh)
patch.setDimensions(rw, rh, false);
addedPatchFrom(path, patch);
if (// prevent it
homogenize_contrast)
// prevent it
setMipMapsRegeneration(false);
else
fus.add(regenerateMipMaps(patch));
//
// after the above two lines! Otherwise it will paint fine, but throw exceptions on the way
layer.add(patch, true);
// otherwise when reopening it has to fetch all ImagePlus and scale and zip them all! This method though creates the awt and the snap, thus filling up memory and slowing down, but it's worth it.
patch.updateInDatabase("tiff_snapshot");
pall[i][j] = patch;
al.add(patch);
if (ControlWindow.isGUIEnabled()) {
// northwest to prevent screwing up Patch coordinates.
layer.getParent().enlargeToFit(patch, LayerSet.NORTHWEST);
}
y += img.getHeight();
Utils.showProgress((double) k / n_images);
k++;
}
x += img.getWidth();
if (largest_y < y) {
largest_y = y;
}
// resetting!
y = 0;
}
// build list
final Patch[] pa = new Patch[al.size()];
int f = 0;
// list in row-first order
for (int j = 0; j < pall[0].length; j++) {
// 'j' is row
for (int i = 0; i < pall.length; i++) {
// 'i' is column
pa[f++] = pall[i][j];
}
}
// optimize repaints: all to background image
Display.clearSelection(layer);
// make the first one be top, and the rest under it in left-right and top-bottom order
for (int j = 0; j < pa.length; j++) {
layer.moveBottom(pa[j]);
}
// make picture
// getFlatImage(layer, layer.getMinimalBoundingBox(Patch.class), 0.25, 1, ImagePlus.GRAY8, Patch.class, null, false).show();
// optimize repaints: all to background image
Display.clearSelection(layer);
if (homogenize_contrast) {
if (null != worker)
worker.setTaskName("Enhancing contrast");
// 0 - check that all images are of the same type
int tmp_type = pa[0].getType();
for (int e = 1; e < pa.length; e++) {
if (pa[e].getType() != tmp_type) {
// can't continue
tmp_type = Integer.MAX_VALUE;
Utils.log("Can't homogenize histograms: images are not all of the same type.\nFirst offending image is: " + al.get(e));
break;
}
}
if (Integer.MAX_VALUE != tmp_type) {
// checking on error flag
// Set min and max for all images
// 1 - fetch statistics for each image
final ArrayList<ImageStatistics> al_st = new ArrayList<ImageStatistics>();
// list of Patch ordered by stdDev ASC
final ArrayList<Patch> al_p = new ArrayList<Patch>();
int type = -1;
for (int i = 0; i < pa.length; i++) {
if (Thread.currentThread().isInterrupted()) {
Display.repaint(layer);
rollback();
return;
}
ImagePlus imp = fetchImagePlus(pa[i]);
// speed-up trick: extract data from smaller image
if (imp.getWidth() > 1024) {
releaseToFit(1024, (int) ((imp.getHeight() * 1024) / imp.getWidth()), imp.getType(), 1.1f);
// cheap and fast nearest-point resizing
imp = new ImagePlus(imp.getTitle(), imp.getProcessor().resize(1024));
}
if (-1 == type)
type = imp.getType();
final ImageStatistics i_st = imp.getStatistics();
// order by stdDev, from small to big
int q = 0;
for (final ImageStatistics st : al_st) {
q++;
if (st.stdDev > i_st.stdDev)
break;
}
if (q == al.size()) {
// append at the end. WARNING if importing thousands of images, this is a potential source of out of memory errors. I could just recompute it when I needed it again below
al_st.add(i_st);
al_p.add(pa[i]);
} else {
al_st.add(q, i_st);
al_p.add(q, pa[i]);
}
}
// shallow copy of the ordered list
final ArrayList<Patch> al_p2 = new ArrayList<Patch>(al_p);
// 2 - discard the first and last 25% (TODO: a proper histogram clustering analysis and histogram examination should apply here)
if (pa.length > 3) {
// under 4 images, use them all
int i = 0;
while (i <= pa.length * 0.25) {
al_p.remove(i);
i++;
}
final int count = i;
i = pa.length - 1 - count;
while (i > (pa.length * 0.75) - count) {
al_p.remove(i);
i--;
}
}
// 3 - compute common histogram for the middle 50% images
final Patch[] p50 = new Patch[al_p.size()];
al_p.toArray(p50);
final StackStatistics stats = new StackStatistics(new PatchStack(p50, 1));
// 4 - compute autoAdjust min and max values
// extracting code from ij.plugin.frame.ContrastAdjuster, method autoAdjust
int autoThreshold = 0;
double min = 0;
double max = 0;
// once for 8-bit and color, twice for 16 and 32-bit (thus the 2501 autoThreshold value)
final int limit = stats.pixelCount / 10;
final int[] histogram = stats.histogram;
// else autoThreshold /= 2;
if (ImagePlus.GRAY16 == type || ImagePlus.GRAY32 == type)
autoThreshold = 2500;
else
autoThreshold = 5000;
final int threshold = stats.pixelCount / autoThreshold;
int i = -1;
boolean found = false;
int count;
do {
i++;
count = histogram[i];
if (count > limit)
count = 0;
found = count > threshold;
} while (!found && i < 255);
final int hmin = i;
i = 256;
do {
i--;
count = histogram[i];
if (count > limit)
count = 0;
found = count > threshold;
} while (!found && i > 0);
final int hmax = i;
if (hmax >= hmin) {
min = stats.histMin + hmin * stats.binSize;
max = stats.histMin + hmax * stats.binSize;
if (min == max) {
min = stats.min;
max = stats.max;
}
}
// 5 - compute common mean within min,max range
final double target_mean = getMeanOfRange(stats, min, max);
Utils.log2("Loader min,max: " + min + ", " + max + ", target mean: " + target_mean);
// 6 - apply to all
for (i = al_p2.size() - 1; i > -1; i--) {
// the order is different, thus getting it from the proper list
final Patch p = (Patch) al_p2.get(i);
final double dm = target_mean - getMeanOfRange((ImageStatistics) al_st.get(i), min, max);
// displacing in the opposite direction, makes sense, so that the range is drifted upwards and thus the target 256 range for an awt.Image will be closer to the ideal target_mean
p.setMinAndMax(min - dm, max - dm);
// OBSOLETE and wrong //p.putMinAndMax(fetchImagePlus(p));
}
setMipMapsRegeneration(true);
if (isMipMapsRegenerationEnabled()) {
// recreate files
for (final Patch p : al) fus.add(regenerateMipMaps(p));
}
Display.repaint(layer, new Rectangle(0, 0, (int) layer.getParent().getLayerWidth(), (int) layer.getParent().getLayerHeight()), 0);
// make picture
// getFlatImage(layer, layer.getMinimalBoundingBox(Patch.class), 0.25, 1, ImagePlus.GRAY8, Patch.class, null, false).show();
}
}
if (stitch_tiles) {
// Wait until all mipmaps for the new images have been generated before attempting to register
Utils.wait(fus);
// create undo
layer.getParent().addTransformStep(new HashSet<Displayable>(layer.getDisplayables(Patch.class)));
// wait until repainting operations have finished (otherwise, calling crop on an ImageProcessor fails with out of bounds exception sometimes)
if (null != Display.getFront())
Display.getFront().getCanvas().waitForRepaint();
if (null != worker)
worker.setTaskName("Stitching");
StitchingTEM.stitch(pa, cols.size(), bt_overlap, lr_overlap, true, pc_param).run();
}
// link with images on top, bottom, left and right.
if (link_images) {
if (null != worker)
worker.setTaskName("Linking");
for (int i = 0; i < pall.length; i++) {
// 'i' is column
for (int j = 0; j < pall[0].length; j++) {
// 'j' is row
final Patch p = pall[i][j];
// can happen if a slot is empty
if (null == p)
continue;
if (i > 0 && null != pall[i - 1][j])
p.link(pall[i - 1][j]);
if (i < pall.length - 1 && null != pall[i + 1][j])
p.link(pall[i + 1][j]);
if (j > 0 && null != pall[i][j - 1])
p.link(pall[i][j - 1]);
if (j < pall[0].length - 1 && null != pall[i][j + 1])
p.link(pall[i][j + 1]);
}
}
}
commitLargeUpdate();
// resize LayerSet
// int new_width = x;
// int new_height = largest_y;
// Math.abs(bx) + new_width, Math.abs(by) + new_height);
layer.getParent().setMinimumDimensions();
// update indexes
// so its done once only
layer.updateInDatabase("stack_index");
// create panels in all Displays showing this layer
/* // not needed anymore
Iterator it = al.iterator();
while (it.hasNext()) {
Display.add(layer, (Displayable)it.next(), false); // don't set it active, don't want to reload the ImagePlus!
}
*/
// update Displays
Display.update(layer);
layer.recreateBuckets();
// debug:
} catch (final Throwable t) {
IJError.print(t);
rollback();
setMipMapsRegeneration(true);
}
}
use of ij.process.ImageStatistics in project GDSC-SMLM by aherbert.
the class PulseActivationAnalysis method autoAdjust.
/**
* Auto adjust. Copied from ij.plgin.frame.ContrastAdjuster
* <p>
* Although the ContrastAdjuster records its actions as 'run("Enhance Contrast", "saturated=0.35");' it actually
* does something else which makes the image easier to see than the afore mentioned command.
*
* @param imp
* the imp
* @param ip
* the ip
*/
private void autoAdjust(ImagePlus imp, ImageProcessor ip) {
ij.measure.Calibration cal = imp.getCalibration();
imp.setCalibration(null);
// get uncalibrated stats
ImageStatistics stats = imp.getStatistics();
imp.setCalibration(cal);
int limit = stats.pixelCount / 10;
int[] histogram = stats.histogram;
int autoThreshold = 0;
if (autoThreshold < 10)
autoThreshold = 5000;
else
autoThreshold /= 2;
int threshold = stats.pixelCount / autoThreshold;
int i = -1;
boolean found = false;
int count;
do {
i++;
count = histogram[i];
if (count > limit)
count = 0;
found = count > threshold;
} while (!found && i < 255);
int hmin = i;
i = 256;
do {
i--;
count = histogram[i];
if (count > limit)
count = 0;
found = count > threshold;
} while (!found && i > 0);
int hmax = i;
if (hmax >= hmin) {
double min = stats.histMin + hmin * stats.binSize;
double max = stats.histMin + hmax * stats.binSize;
if (min == max) {
min = stats.min;
max = stats.max;
}
imp.setDisplayRange(min, max);
} else {
reset(imp, ip);
return;
}
}
use of ij.process.ImageStatistics in project GDSC-SMLM by aherbert.
the class GaussianFit method getLimits.
/**
* Calculate the min/max limits for the image. The max is set at the 99th percentile of the data.
*
* @param ip
* @return The limits
*/
private double[] getLimits(ImageProcessor ip) {
ImageStatistics stats = ImageStatistics.getStatistics(ip, ImageStatistics.MIN_MAX, null);
double[] limits = new double[] { stats.min, stats.max };
// Use histogram to cover x% of the data
int[] data = ip.getHistogram();
if (// Float processor
data == null)
return limits;
// 8/16 bit greyscale image. Set upper limit to the height of the 99% percentile.
int limit = (int) (99.0 * ip.getPixelCount() / 100.0);
int count = 0;
int i = 0;
while (i < data.length) {
count += data[i];
if (count > limit)
break;
i++;
}
limits[1] = i;
return limits;
}
Aggregations