use of ij.ImagePlus in project TrakEM2 by trakem2.
the class Patch method keyPressed.
@Override
public void keyPressed(final KeyEvent ke) {
final Object source = ke.getSource();
if (!(source instanceof DisplayCanvas))
return;
final DisplayCanvas dc = (DisplayCanvas) source;
final Roi roi = dc.getFakeImagePlus().getRoi();
final int mod = ke.getModifiers();
switch(ke.getKeyCode()) {
case KeyEvent.VK_C:
// Ignoring masks: outside is already black, and ImageJ cannot handle alpha masks.
if (0 == (mod ^ (Event.SHIFT_MASK | Event.ALT_MASK))) {
// Place the source image, untransformed, into clipboard:
final ImagePlus imp = getImagePlus();
if (null != imp)
imp.copy(false);
} else if (0 == mod || (0 == (mod ^ Event.SHIFT_MASK))) {
CoordinateTransformList<CoordinateTransform> list = null;
if (hasCoordinateTransform()) {
list = new CoordinateTransformList<CoordinateTransform>();
list.add(getCoordinateTransform());
}
if (0 == mod) {
// SHIFT is not down
final AffineModel2D am = new AffineModel2D();
am.set(this.at);
if (null == list)
list = new CoordinateTransformList<CoordinateTransform>();
list.add(am);
}
ImageProcessor ip;
if (null != list) {
final TransformMesh mesh = new TransformMesh(list, meshResolution, o_width, o_height);
final TransformMeshMapping mapping = new TransformMeshMapping(mesh);
ip = mapping.createMappedImageInterpolated(getImageProcessor());
} else {
ip = getImageProcessor();
}
new ImagePlus(this.title, ip).copy(false);
}
ke.consume();
break;
case KeyEvent.VK_F:
// fill mask with current ROI using
if (null != roi && M.isAreaROI(roi)) {
Bureaucrat.createAndStart(new Worker.Task("Filling image mask") {
@Override
public void exec() {
getLayerSet().addDataEditStep(Patch.this);
if (0 == mod) {
addAlphaMask(roi, ProjectToolbar.getForegroundColorValue());
} else if (0 == (mod ^ Event.SHIFT_MASK)) {
// shift is down: fill outside
try {
final Area localRoi = M.areaInInts(M.getArea(roi)).createTransformedArea(at.createInverse());
final Area invLocalRoi = new Area(new Rectangle(0, 0, getOWidth(), getOHeight()));
invLocalRoi.subtract(localRoi);
addAlphaMaskLocal(invLocalRoi, ProjectToolbar.getForegroundColorValue());
} catch (final NoninvertibleTransformException e) {
IJError.print(e);
return;
}
}
getLayerSet().addDataEditStep(Patch.this);
// wait
try {
updateMipMaps().get();
} catch (final Throwable t) {
IJError.print(t);
}
Display.repaint();
}
}, project);
}
// capturing:
ke.consume();
break;
default:
super.keyPressed(ke);
break;
}
}
use of ij.ImagePlus in project TrakEM2 by trakem2.
the class Patch method createPatch.
/**
* Create a new Patch and register the associated {@code filepath}
* with the project's loader.
*
* This method is intended for scripting, to avoid having to create a new Patch
* and then call {@link Loader#addedPatchFrom(String, Patch)}, which is easy to forget.
*
* @return the new Patch.
* @throws Exception if the image cannot be loaded from the {@code filepath}, or it's an unsupported type such as a composite image or a hyperstack.
*/
public static final Patch createPatch(final Project project, final String filepath) throws Exception {
final ImagePlus imp = project.getLoader().openImagePlus(filepath);
if (null == imp)
throw new Exception("Cannot create Patch: the image cannot be opened from filepath " + filepath);
if (imp.isComposite())
throw new Exception("Cannot create Patch: composite images are not supported. Convert them to RGB first.");
if (imp.isHyperStack())
throw new Exception("Cannot create Patch: hyperstacks are not supported.");
final Patch p = new Patch(project, new File(filepath).getName(), 0, 0, imp);
project.getLoader().addedPatchFrom(filepath, p);
return p;
}
use of ij.ImagePlus 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.ImagePlus in project TrakEM2 by trakem2.
the class Tree method openImage.
/**
* Open an image in a separate thread and returns the thread. Frees up to 1 Gb for it.
*/
private Future<ImagePlus> openImage(final String path, final Node<T> last) {
return project.getLoader().doLater(new Callable<ImagePlus>() {
@Override
public ImagePlus call() {
try {
if (!new File(path).exists()) {
Utils.log("Could not find file " + path);
return null;
}
// 1 Gb : can't tell for jpegs and tif-jpg, TODO would have to read the header.
project.getLoader().releaseToFit(1000000000L);
final Opener op = new Opener();
op.setSilentMode(true);
// TODO WARNING should go via the Loader
final ImagePlus imp = op.openImage(path);
if (null == imp) {
Utils.log("ERROR: could not open " + path);
} else {
final StackWindow stack = new StackWindow(imp);
final MouseListener[] ml = stack.getCanvas().getMouseListeners();
for (final MouseListener m : ml) stack.getCanvas().removeMouseListener(m);
stack.getCanvas().addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(final MouseEvent me) {
if (2 == me.getClickCount()) {
me.consume();
// Go to the node
// Slices are 1-based: 1<=i<=N
final int slice = imp.getCurrentSlice();
if (slice == imp.getNSlices()) {
Display.centerAt(createCoordinate(last));
} else {
Node<T> parent = last.getParent();
int count = imp.getNSlices() - 1;
while (null != parent) {
if (count == slice) {
Display.centerAt(createCoordinate(parent));
break;
}
// next cycle
count--;
parent = parent.getParent();
}
;
}
}
}
@Override
public void mouseDragged(final MouseEvent me) {
if (2 == me.getClickCount()) {
me.consume();
}
}
@Override
public void mouseReleased(final MouseEvent me) {
if (2 == me.getClickCount()) {
me.consume();
}
}
});
for (final MouseListener m : ml) stack.getCanvas().addMouseListener(m);
}
return imp;
} catch (final Exception e) {
IJError.print(e);
}
return null;
}
});
}
use of ij.ImagePlus 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);
}
}
Aggregations