use of ini.trakem2.display.Stack in project TrakEM2 by trakem2.
the class Display method insertStack.
/**
* @param stack_patch is just a Patch of a series of Patch that make a stack of Patches.
*/
private boolean insertStack(final ProjectThing target_landmarks, final Project source, final ProjectThing source_landmarks, final Patch stack_patch) {
final List<Ball> l1 = new ArrayList<Ball>();
final List<Ball> l2 = new ArrayList<Ball>();
// source is the one that has the stack_patch
final Collection<ProjectThing> b1s = source_landmarks.findChildrenOfType("ball");
// target is this
final Collection<ProjectThing> b2s = target_landmarks.findChildrenOfType("ball");
final HashSet<String> seen = new HashSet<String>();
for (final ProjectThing b1 : b1s) {
final Ball ball1 = (Ball) b1.getObject();
if (null == ball1) {
Utils.log("ERROR: there's an empty 'ball' node in target project" + project.toString());
return false;
}
final String title1 = ball1.getTitle();
for (final ProjectThing b2 : b2s) {
final Ball ball2 = (Ball) b2.getObject();
if (null == ball2) {
Utils.log("ERROR: there's an empty 'ball' node in source project" + source.toString());
return false;
}
if (title1.equals(ball2.getTitle())) {
if (seen.contains(title1))
continue;
seen.add(title1);
l1.add(ball1);
l2.add(ball2);
}
}
}
if (l1.size() < 4) {
Utils.log("ERROR: found only " + l1.size() + " common landmarks: needs at least 4!");
return false;
}
// Extract coordinates of source project landmarks, in patch stack coordinate space
final List<double[]> c1 = new ArrayList<double[]>();
for (final Ball ball1 : l1) {
final Map<Layer, double[]> m = ball1.getRawBalls();
if (1 != m.size()) {
Utils.log("ERROR: ball object " + ball1 + " from target project " + project + " has " + m.size() + " balls instead of just 1.");
return false;
}
final Map.Entry<Layer, double[]> e = m.entrySet().iterator().next();
final Layer layer = e.getKey();
final double[] xyr = e.getValue();
final double[] fin = new double[] { xyr[0], xyr[1] };
final AffineTransform affine = ball1.getAffineTransformCopy();
try {
affine.preConcatenate(stack_patch.getAffineTransform().createInverse());
} catch (final Exception nite) {
IJError.print(nite);
return false;
}
final double[] fout = new double[2];
affine.transform(fin, 0, fout, 0, 1);
c1.add(new double[] { fout[0], fout[1], layer.getParent().indexOf(layer) });
}
// Extract coordinates of target (this) project landmarks, in calibrated world space
final List<double[]> c2 = new ArrayList<double[]>();
for (final Ball ball2 : l2) {
final double[][] b = ball2.getBalls();
if (1 != b.length) {
Utils.log("ERROR: ball object " + ball2 + " from source project " + source + " has " + b.length + " balls instead of just 1.");
return false;
}
final double[] fin = new double[] { b[0][0], b[0][1] };
final AffineTransform affine = ball2.getAffineTransformCopy();
final double[] fout = new double[2];
affine.transform(fin, 0, fout, 0, 1);
c2.add(new double[] { fout[0], fout[1], b[0][2] });
}
// Print landmarks:
Utils.log("Landmarks:");
for (Iterator<double[]> it1 = c1.iterator(), it2 = c2.iterator(); it1.hasNext(); ) {
Utils.log(Utils.toString(it1.next()) + " <--> " + Utils.toString(it2.next()));
}
// Create point matches
final List<PointMatch> pm = new ArrayList<PointMatch>();
for (Iterator<double[]> it1 = c1.iterator(), it2 = c2.iterator(); it1.hasNext(); ) {
pm.add(new mpicbg.models.PointMatch(new mpicbg.models.Point(it1.next()), new mpicbg.models.Point(it2.next())));
}
// Estimate AffineModel3D
final AffineModel3D aff3d = new AffineModel3D();
try {
aff3d.fit(pm);
} catch (final Exception e) {
IJError.print(e);
return false;
}
// Create and add the Stack
final String path = stack_patch.getImageFilePath();
final Stack st = new Stack(project, new File(path).getName(), 0, 0, getLayerSet().getLayers().get(0), path);
st.setInvertibleCoordinateTransform(aff3d);
getLayerSet().add(st);
return true;
}
use of ini.trakem2.display.Stack in project TrakEM2 by trakem2.
the class ImageJCommandListener method commandExecuting.
// I know, I could create a hashtable and then map methods of this class to each command key ... this is just easier, and performance-wise nobody cares
// Or even a hastable with String command keys and then a number as value, and use a gigantic switch block. So much pain to write. WHAT I REALLY WANT is a switch that takes a String and is fast because it has its own hash setup.
public String commandExecuting(final String command) {
// Utils.log2("Command: " + command);
// 1 - check source
ImagePlus current = WindowManager.getCurrentImage();
// not a trakem2 display: continue happily
if (!(current instanceof FakeImagePlus))
return command;
// 2 - identify project
final FakeImagePlus fimp = (FakeImagePlus) current;
final Display display = fimp.getDisplay();
final LayerSet layer_set = display.getLayer().getParent();
final Project project = display.getProject();
final ProjectTree ptree = project.getProjectTree();
final Displayable active = display.getActive();
final Selection selection = display.getSelection();
// FILE menu
if (command.equals("Save")) {
project.save();
return null;
} else // EDIT menu
if (command.equals("Undo")) {
// TODO forward to the active image, if any
niy(command);
return null;
} else if (command.equals("Cut")) {
// TODO forward to the active image, if any
niy(command);
return null;
} else if (command.equals("Copy")) {
// TODO forward to the active image, if any
niy(command);
return null;
} else if (command.equals("Copy to System")) {
// TODO forward to the active image, if any
niy(command);
return null;
} else if (command.equals("Paste")) {
// TODO forward to the active image, if any
niy(command);
return null;
} else if (command.equals("Clear")) {
// TODO forward to the active image, if any
niy(command);
return null;
} else if (command.equals("Clear Outside")) {
// TODO forward to the active image, if any
niy(command);
return null;
} else if (command.equals("Fill")) {
// TODO forward to the active image, if any
niy(command);
return null;
} else if (command.equals("Draw")) {
// TODO forward to the active image, if any
niy(command);
return null;
} else if (command.equals("Invert")) {
// TODO forward to the active image, if any
niy(command);
return null;
} else // EDIT - SELECTION menu
if (command.equals("Select All")) {
if (ProjectToolbar.SELECT == Toolbar.getToolId()) {
selection.selectAll();
return null;
}
return command;
} else if (command.equals("Select None")) {
if (ProjectToolbar.SELECT == Toolbar.getToolId()) {
display.select(null);
return null;
}
return command;
} else if (command.equals("Restore Selection")) {
if (ProjectToolbar.SELECT == Toolbar.getToolId()) {
selection.restore();
return null;
}
return command;
} else // IMAGE - TYPE menu
if (command.equals("8-bit")) {
// TODO forward to the active image, if any
niy(command);
return null;
} else if (command.equals("16-bit")) {
// TODO forward to the active image, if any
niy(command);
return null;
} else if (command.equals("32-bit")) {
// TODO forward to the active image, if any
niy(command);
return null;
} else if (command.equals("8-bit Color")) {
// TODO forward to the active image, if any
niy(command);
return null;
} else if (command.equals("RGB Color")) {
// TODO forward to the active image, if any
niy(command);
return null;
} else if (command.equals("RGB Stack") || command.equals("HSB Stack")) {
Utils.showMessage("Can't convert to " + command);
return null;
} else // IMAGE - ADJUST menu
if (command.equals("Brightness/Contrast...")) {
// TODO forward to the active image, if any
niy(command);
return null;
} else if (command.equals("Window/Level...")) {
// TODO forward to the active image, if any
niy(command);
return null;
} else if (command.equals("Color Balance...")) {
// TODO forward to the active image, if any
niy(command);
return null;
} else if (command.equals("Threshold...")) {
// TODO forward to the active image, if any
niy(command);
return null;
} else if (command.equals("Size...")) {
if (null != active)
selection.specify();
return null;
} else if (command.equals("Canvas Size...")) {
display.resizeCanvas();
return null;
} else // IMAGE menu
if (command.equals("Show Info...")) {
// TODO perhaps it should show only for images ...
if (null == active) {
ptree.showInfo(project.getRootProjectThing());
} else {
ProjectThing pt = project.findProjectThing(active);
if (null != pt)
ptree.showInfo(pt);
}
return null;
} else // IMAGE - COLOR menu
if (in(command, new String[] { "RGB Split", "RGB Merge...", "Stack to RGB", "Make Composite" })) {
notAvailable(command);
return null;
} else if (command.equals("Show LUT")) {
return setTempCurrentImage(command, active);
} else if (command.equals("Edit LUT...")) {
// TODO forward to the active image, if any
niy(command);
return null;
} else if (command.equals("Average Color")) {
// TODO forward to the active image, if any
niy(command);
return null;
} else if (command.equals("RGB to CIELAB")) {
// TODO forward to the active image, if any
niy(command);
return null;
} else if (command.equals("RGB to Luminance")) {
// TODO forward to the active image, if any
niy(command);
return null;
} else // IMAGE STACK menu
if (in(command, new String[] { "Add Slice", "Delete Slice" })) {
Utils.showMessage("Go to the Layer Tree and right-click to add/delete a layer.");
return null;
} else if (command.equals("Next Slice [>]")) {
display.nextLayer(IJ.shiftKeyDown() ? Event.SHIFT_MASK : 0);
return null;
} else if (command.equals("Previous Slice [<]")) {
display.previousLayer(IJ.shiftKeyDown() ? Event.SHIFT_MASK : 0);
return null;
} else if (in(command, new String[] { "Set Slice", "Images to Stack", "Stack to Images", "Make Montage..." })) {
notAvailable(command);
return null;
} else if (command.equals("Reslice [/]...")) {
// TODO
niy(command);
return null;
} else if (command.equals("Z Project...")) {
// TODO
niy(command);
return null;
} else if (command.equals("3D Project...")) {
// TODO
niy(command);
return null;
} else if (command.equals("Plot Z-axis Profile")) {
// TODO
niy(command);
return null;
} else if (command.equals("Start Animation [\\]")) {
// TODO
niy(command);
return null;
} else if (command.equals("Stop Animation")) {
// TODO
niy(command);
return null;
} else // IMAGE menu again
if (command.equals("Crop")) {
notAvailable(command);
return null;
} else if (in(command, new String[] { "Translate...", "Scale..." })) {
if (null != active)
selection.specify();
return null;
} else if (command.equals("Duplicate...")) {
if (null != active && active.getClass().equals(Patch.class)) {
// TODO stacks?
// 2.5 security factor: for awt in non-1.6.0 machines
project.getLoader().releaseToFit((long) (project.getLoader().estimateImageFileSize((Patch) active, 0) * 2.5));
new ImagePlus(active.getTitle(), ((Patch) active).getImageProcessor().duplicate()).show();
}
return null;
} else if (command.equals("Rename...")) {
if (null != active) {
active.adjustProperties();
Display.updateSelection();
}
return null;
} else // IMAGE ROTATE menu
if (command.equals("Flip Horizontally")) {
selection.apply(2, new double[] { -1, 1 });
return null;
} else if (command.equals("Flip Vertically")) {
selection.apply(2, new double[] { 1, -1 });
return null;
} else if (command.equals("Rotate 90 Degrees Right")) {
selection.apply(1, new double[] { 90 });
return null;
} else if (command.equals("Rotate 90 Degrees Left")) {
selection.apply(1, new double[] { -90 });
return null;
} else if (command.equals("Arbitrarily...")) {
if (null != active)
selection.specify();
return null;
} else // IMAGE ZOOM menu
if (command.equals("To Selection")) {
Roi roi = fimp.getRoi();
if (null != roi) {
Rectangle b = roi.getBounds();
b.x -= b.width / 2;
b.y -= b.height / 2;
b.width *= 2;
b.height *= 2;
display.getCanvas().showCentered(b);
}
return null;
} else if (command.equals("View 100%")) {
// TODO
niy(command);
return null;
} else // ANALYZE menu
if (command.equals("Measure")) {
// Minimal measurement: area of closed ROIs, length of unclosed ROIs, calibrated.
Roi roi = fimp.getRoi();
if (null != roi) {
Calibration cal = fimp.getCalibration();
AffineTransform caff = new AffineTransform();
caff.scale(cal.pixelWidth, cal.pixelHeight);
if (M.isAreaROI(roi)) {
Area area = M.getArea(roi);
area = area.createTransformedArea(caff);
ResultsTable rt = Utils.createResultsTable("ROI area", new String[] { "area", "perimeter" });
rt.incrementCounter();
rt.addLabel("units", cal.getUnit());
rt.addValue(0, Math.abs(AreaCalculations.area(area.getPathIterator(null))));
rt.addValue(1, roi.getLength());
rt.show("ROI area");
} else {
ResultsTable rt = Utils.createResultsTable("ROI length", new String[] { "length" });
rt.incrementCounter();
rt.addLabel("units", cal.getUnit());
rt.addValue(0, roi.getLength());
rt.show("ROI length");
}
return null;
} else if (null != active) {
// Measure the active displayable
if (active.getClass() == Patch.class) {
// measure like 'm' would in ImageJ for an image
ImagePlus imp = ((Patch) active).getImagePlus();
imp.setCalibration(active.getLayer().getParent().getCalibrationCopy());
IJ.run(imp, "Measure", "");
} else {
// Call measure like ProjectThing does
ProjectThing pt = active.getProject().findProjectThing(active);
if (active instanceof Profile)
((ProjectThing) pt.getParent()).measure();
else
pt.measure();
}
return null;
}
Utils.log("Draw a ROI or select an object!");
return null;
} else if (in(command, new String[] { "Analyze Particles...", "Histogram", "Plot Profile", "Surface Plot...", "Color Inspector 3D", "3D Surface Plot", "Color Histogram" })) {
return setTempCurrentImage(command, active);
} else if (command.equals("Label")) {
notAvailable(command);
return null;
} else // PLUGINS menu
if (command.equals("Volume Viewer")) {
return runOnVirtualLayerSet(command, layer_set, display);
} else if (command.equals("3D Viewer")) {
// it's virtual and non-caching, will appear as a regular ImageJ stack
layer_set.createLayerStack(Displayable.class, ImagePlus.COLOR_RGB, display.getDisplayChannelAlphas()).getImagePlus().show();
return command;
} else // PROCESS menu and submenus
if (in(command, new String[] { "FFT", "Fast FFT (2D/3D)" })) {
return setTempCurrentImage(command, active);
} else if (in(command, new String[] { "Bandpass Filter...", "Custom Filter...", "FD Math...", "Swap Quadrants", "Convolve...", "Gaussian Blur...", "Median...", "Mean...", "Minimum...", "Maximum...", "Unsharp Mask...", "Variance...", "Show Circular Masks...", "Subtract Background..." })) {
return duplicate(command, active);
} else if (in(command, new String[] { "Smooth", "Sharpen", "Find Edges", "Enhance Contrast", "Add Noise", "Add Specified Noise...", "Salt and Pepper", "Despeckle", "Remove Outliers...", "North", "Northeast", "East", "Southeast", "South", "Southwest", "West", "Northwest", "Make Binary", "Convert to Mask", "Find Maxima...", "Erode", "Dilate", "Open ", "Close-", "Outline", "Fill Holes", "Skeletonize", "Distance Map", "Ultimate Points", "Watershed", "Add...", "Subtract...", "Multiply...", "Divide...", "AND...", "OR...", "XOR...", "Min...", "Max...", "Gamma...", "Log", "Exp", "Square", "Square Root", "Reciprocal", "NaN Background", "Abs" })) {
return duplicate(command, active);
}
/*else {
// continue happily
//Utils.log2("Skipping " + command);
}*/
// If it's part of "Save As", ignore it
Menu menu = Menus.getSaveAsMenu();
for (int i = menu.getItemCount() - 1; i > -1; i--) {
if (command.equals(menu.getItem(i).getActionCommand())) {
notAvailable(command);
return null;
}
}
// Give it back to ImageJ
return command;
}
use of ini.trakem2.display.Stack in project TrakEM2 by trakem2.
the class Loader method importStack.
/**
* Imports an image stack from a multitiff file and places each slice in the proper layer, creating new layers as it goes. If the given stack is null, popup a file dialog to choose one
*/
public Bureaucrat importStack(final Layer first_layer, final double x, final double y, final ImagePlus imp_stack_, final boolean ask_for_data, final String filepath_, final boolean one_patch_per_layer_) {
Utils.log2("Loader.importStack filepath: " + filepath_);
if (null == first_layer)
return null;
final Worker worker = new Worker("import stack") {
@Override
public void run() {
startedWorking();
try {
String filepath = filepath_;
boolean one_patch_per_layer = one_patch_per_layer_;
/* On drag and drop the stack is not null! */
// Utils.log2("imp_stack_ is " + imp_stack_);
ImagePlus[] stks = null;
boolean choose = false;
if (null == imp_stack_) {
stks = Utils.findOpenStacks();
choose = null == stks || stks.length > 0;
} else {
stks = new ImagePlus[] { imp_stack_ };
}
ImagePlus imp_stack = null;
// ask to open a stack if it's null
if (null == stks) {
// choose one
imp_stack = openStack();
} else if (choose) {
// choose one from the list
final GenericDialog gd = new GenericDialog("Choose one");
gd.addMessage("Choose a stack from the list or 'open...' to bring up a file chooser dialog:");
final String[] list = new String[stks.length + 1];
for (int i = 0; i < list.length - 1; i++) {
list[i] = stks[i].getTitle();
}
list[list.length - 1] = "[ Open stack... ]";
gd.addChoice("choose stack: ", list, list[0]);
gd.showDialog();
if (gd.wasCanceled()) {
finishedWorking();
return;
}
final int i_choice = gd.getNextChoiceIndex();
if (list.length - 1 == i_choice) {
// the open... command
imp_stack = first_layer.getProject().getLoader().openStack();
} else {
imp_stack = stks[i_choice];
}
} else {
imp_stack = imp_stack_;
}
// check:
if (null == imp_stack) {
finishedWorking();
return;
}
final String props = (String) imp_stack.getProperty("Info");
// check if it's amira labels stack to prevent missimports
if (null != props && -1 != props.indexOf("Materials {")) {
final YesNoDialog yn = new YesNoDialog(IJ.getInstance(), "Warning", "You are importing a stack of Amira labels as a regular image stack. Continue anyway?");
if (!yn.yesPressed()) {
finishedWorking();
return;
}
}
// String dir = imp_stack.getFileInfo().directory;
final double layer_width = first_layer.getLayerWidth();
final double layer_height = first_layer.getLayerHeight();
final double current_thickness = first_layer.getThickness();
double thickness = current_thickness;
boolean expand_layer_set = false;
boolean lock_stack = false;
// int anchor = LayerSet.NORTHWEST; //default
if (ask_for_data) {
// ask for slice separation in pixels
final GenericDialog gd = new GenericDialog("Slice separation?");
gd.addMessage("Please enter the slice thickness, in pixels");
// assuming pixelWidth == pixelHeight
gd.addNumericField("slice_thickness: ", Math.abs(imp_stack.getCalibration().pixelDepth / imp_stack.getCalibration().pixelHeight), 3);
if (layer_width != imp_stack.getWidth() || layer_height != imp_stack.getHeight()) {
gd.addCheckbox("Resize canvas to fit stack", true);
// gd.addChoice("Anchor: ", LayerSet.ANCHORS, LayerSet.ANCHORS[0]);
}
gd.addCheckbox("Lock stack", false);
final String[] importStackTypes = { "One slice per layer (Patches)", "Image volume (Stack)" };
if (imp_stack.getStack().isVirtual()) {
one_patch_per_layer = true;
}
gd.addChoice("Import stack as:", importStackTypes, importStackTypes[0]);
((Component) gd.getChoices().get(0)).setEnabled(!imp_stack.getStack().isVirtual());
gd.showDialog();
if (gd.wasCanceled()) {
if (null == stks) {
// flush only if it was not open before
flush(imp_stack);
}
finishedWorking();
return;
}
if (layer_width != imp_stack.getWidth() || layer_height != imp_stack.getHeight()) {
expand_layer_set = gd.getNextBoolean();
// anchor = gd.getNextChoiceIndex();
}
lock_stack = gd.getNextBoolean();
thickness = gd.getNextNumber();
// check provided thickness with that of the first layer:
if (thickness != current_thickness) {
if (1 == first_layer.getParent().size() && first_layer.isEmpty()) {
final YesNoCancelDialog yn = new YesNoCancelDialog(IJ.getInstance(), "Mismatch!", "The current layer's thickness is " + current_thickness + "\nwhich is " + (thickness < current_thickness ? "larger" : "smaller") + " than\nthe desired " + thickness + " for each stack slice.\nAdjust current layer's thickness to " + thickness + " ?");
if (yn.cancelPressed()) {
// was opened new
if (null != imp_stack_)
flush(imp_stack);
finishedWorking();
return;
} else if (yn.yesPressed()) {
first_layer.setThickness(thickness);
// The rest of layers, created new, will inherit the same thickness
}
} else {
final YesNoDialog yn = new YesNoDialog(IJ.getInstance(), "WARNING", "There's more than one layer or the current layer is not empty\nso the thickness cannot be adjusted. Proceed anyway?");
if (!yn.yesPressed()) {
finishedWorking();
return;
}
}
}
one_patch_per_layer = imp_stack.getStack().isVirtual() || 0 == gd.getNextChoiceIndex();
}
if (null == imp_stack.getStack()) {
Utils.showMessage("Not a stack.");
finishedWorking();
return;
}
// WARNING: there are fundamental issues with calibration, because the Layer thickness is disconnected from the Calibration pixelDepth
// set LayerSet calibration if there is no calibration
boolean calibrate = true;
if (ask_for_data && first_layer.getParent().isCalibrated()) {
if (!ControlWindow.isGUIEnabled()) {
Utils.log2("Loader.importStack: overriding LayerSet calibration with that of the imported stack.");
} else {
final YesNoDialog yn = new YesNoDialog("Calibration", "The layer set is already calibrated. Override with the stack calibration values?");
if (!yn.yesPressed()) {
calibrate = false;
}
}
}
if (calibrate) {
first_layer.getParent().setCalibration(imp_stack.getCalibration());
}
if (layer_width < imp_stack.getWidth() || layer_height < imp_stack.getHeight()) {
expand_layer_set = true;
}
if (imp_stack.getStack().isVirtual()) {
// do nothing
} else if (null == filepath) {
// try to get it from the original FileInfo
final FileInfo fi = imp_stack.getOriginalFileInfo();
if (null != fi && null != fi.directory && null != fi.fileName) {
filepath = fi.directory.replace('\\', '/');
if (!filepath.endsWith("/"))
filepath += '/';
filepath += fi.fileName;
}
Utils.log2("Getting filepath from FileInfo: " + filepath);
// check that file exists, otherwise save a copy in the storage folder
if (null == filepath || (!filepath.startsWith("http://") && !new File(filepath).exists())) {
filepath = handlePathlessImage(imp_stack);
}
} else {
filepath = filepath.replace('\\', '/');
}
// Import as Stack ZDisplayable object:
if (!one_patch_per_layer) {
final Stack st = new Stack(first_layer.getProject(), new File(filepath).getName(), x, y, first_layer, filepath);
first_layer.getParent().add(st);
finishedWorking();
return;
}
// Place the first slice in the current layer, and then query the parent LayerSet for subsequent layers, and create them if not present.
final Patch last_patch = Loader.this.importStackAsPatches(first_layer.getProject(), first_layer, x, y, imp_stack, null != imp_stack_ && null != imp_stack_.getCanvas(), filepath);
if (null != last_patch) {
last_patch.setLocked(lock_stack);
Display.updateCheckboxes(last_patch.getLinkedGroup(null), DisplayablePanel.LOCK_STATE, true);
}
if (expand_layer_set) {
last_patch.getLayer().getParent().setMinimumDimensions();
}
Utils.log2("props: " + props);
// check if it's an amira stack, then ask to import labels
if (null != props && -1 == props.indexOf("Materials {") && -1 != props.indexOf("CoordType")) {
final YesNoDialog yn = new YesNoDialog(IJ.getInstance(), "Amira Importer", "Import labels as well?");
if (yn.yesPressed()) {
// select labels
final Collection<AreaList> alis = AmiraImporter.importAmiraLabels(first_layer, last_patch.getX(), last_patch.getY(), imp_stack.getOriginalFileInfo().directory);
if (null != alis) {
// import all created AreaList as nodes in the ProjectTree under a new imported_segmentations node
first_layer.getProject().getProjectTree().insertSegmentations(alis);
// link them to the images
for (final AreaList ali : alis) {
ali.linkPatches();
}
}
}
}
// it is safe not to flush the imp_stack, because all its resources are being used anyway (all the ImageProcessor), and it has no awt.Image. Unless it's being shown in ImageJ, and then it will be flushed on its own when the user closes its window.
} catch (final Exception e) {
IJError.print(e);
}
finishedWorking();
}
};
return Bureaucrat.createAndStart(worker, first_layer.getProject());
}
use of ini.trakem2.display.Stack in project TrakEM2 by trakem2.
the class Loader method importLabelsAsAreaLists.
/**
* If base_x or base_y are Double.MAX_VALUE, then those values are asked for in a GenericDialog.
*/
public Bureaucrat importLabelsAsAreaLists(final Layer first_layer, final String path_, final double base_x_, final double base_y_, final float alpha_, final boolean add_background_) {
final Worker worker = new Worker("Import labels as arealists") {
@Override
public void run() {
startedWorking();
try {
String path = path_;
if (null == path) {
final OpenDialog od = new OpenDialog("Select stack", "");
final String name = od.getFileName();
if (null == name || 0 == name.length()) {
return;
}
String dir = od.getDirectory().replace('\\', '/');
if (!dir.endsWith("/"))
dir += "/";
path = dir + name;
}
if (path.toLowerCase().endsWith(".xml")) {
Utils.log("Avoided opening a TrakEM2 project.");
return;
}
double base_x = base_x_;
double base_y = base_y_;
float alpha = alpha_;
boolean add_background = add_background_;
Layer layer = first_layer;
if (Double.MAX_VALUE == base_x || Double.MAX_VALUE == base_y || alpha < 0 || alpha > 1) {
final GenericDialog gd = new GenericDialog("Base x, y");
Utils.addLayerChoice("First layer:", first_layer, gd);
gd.addNumericField("Base_X:", 0, 0);
gd.addNumericField("Base_Y:", 0, 0);
gd.addSlider("Alpha:", 0, 100, 40);
gd.addCheckbox("Add background (zero)", false);
gd.showDialog();
if (gd.wasCanceled()) {
return;
}
layer = first_layer.getParent().getLayer(gd.getNextChoiceIndex());
base_x = gd.getNextNumber();
base_y = gd.getNextNumber();
if (Double.isNaN(base_x) || Double.isNaN(base_y)) {
Utils.log("Base x or y is NaN!");
return;
}
alpha = (float) (gd.getNextNumber() / 100);
add_background = gd.getNextBoolean();
}
releaseToFit(new File(path).length() * 3);
final ImagePlus imp;
if (path.toLowerCase().endsWith(".am")) {
final AmiraMeshDecoder decoder = new AmiraMeshDecoder();
if (decoder.open(path))
imp = new ImagePlus(path, decoder.getStack());
else
imp = null;
} else {
imp = openImagePlus(path);
}
if (null == imp) {
Utils.log("Could not open image at " + path);
return;
}
final Map<Float, AreaList> alis = AmiraImporter.extractAreaLists(imp, layer, base_x, base_y, alpha, add_background);
if (!hasQuitted() && alis.size() > 0) {
layer.getProject().getProjectTree().insertSegmentations(alis.values());
}
} catch (final Exception e) {
IJError.print(e);
} finally {
finishedWorking();
}
}
};
return Bureaucrat.createAndStart(worker, first_layer.getProject());
}
use of ini.trakem2.display.Stack in project TrakEM2 by trakem2.
the class Loader method makeFlatImage.
/**
* If the srcRect is null, makes a flat 8-bit or RGB image of the entire layer. Otherwise just of the srcRect. Checks first for enough memory and frees some if feasible.
*/
public Bureaucrat makeFlatImage(final Layer[] layer, final Rectangle srcRect, final double scale, final int c_alphas, final int type, final boolean force_to_file, final String format, final boolean quality, final Color background) {
if (null == layer || 0 == layer.length) {
Utils.log2("makeFlatImage: null or empty list of layers to process.");
return null;
}
final Worker worker = new Worker("making flat images") {
@Override
public void run() {
try {
//
startedWorking();
Rectangle srcRect_ = srcRect;
if (null == srcRect_)
srcRect_ = layer[0].getParent().get2DBounds();
ImagePlus imp = null;
String target_dir = null;
boolean choose_dir = force_to_file;
// if not saving to a file:
if (!force_to_file) {
final long size = (long) Math.ceil((srcRect_.width * scale) * (srcRect_.height * scale) * (ImagePlus.GRAY8 == type ? 1 : 4) * layer.length);
if (size > IJ.maxMemory() * 0.9) {
final YesNoCancelDialog yn = new YesNoCancelDialog(IJ.getInstance(), "WARNING", "The resulting stack of flat images is too large to fit in memory.\nChoose a directory to save the slices as an image sequence?");
if (yn.yesPressed()) {
choose_dir = true;
} else if (yn.cancelPressed()) {
finishedWorking();
return;
} else {
// your own risk
choose_dir = false;
}
}
}
if (choose_dir) {
final DirectoryChooser dc = new DirectoryChooser("Target directory");
target_dir = dc.getDirectory();
if (null == target_dir || target_dir.toLowerCase().startsWith("null")) {
finishedWorking();
return;
}
if (IJ.isWindows())
target_dir = target_dir.replace('\\', '/');
if (!target_dir.endsWith("/"))
target_dir += "/";
}
if (layer.length > 1) {
// Get all slices
ImageStack stack = null;
Utils.showProgress(0);
for (int i = 0; i < layer.length; i++) {
if (Thread.currentThread().isInterrupted())
return;
/* free memory */
releaseAll();
Utils.showProgress(i / (float) layer.length);
final ImagePlus slice = getFlatImage(layer[i], srcRect_, scale, c_alphas, type, Displayable.class, null, quality, background);
if (null == slice) {
Utils.log("Could not retrieve flat image for " + layer[i].toString());
continue;
}
if (null != target_dir) {
saveToPath(slice, target_dir, layer[i].getPrintableTitle(), ".tif");
} else {
if (null == stack)
stack = new ImageStack(slice.getWidth(), slice.getHeight());
stack.addSlice(layer[i].getProject().findLayerThing(layer[i]).toString(), slice.getProcessor());
}
}
Utils.showProgress(1);
if (null != stack) {
imp = new ImagePlus("z=" + layer[0].getZ() + " to z=" + layer[layer.length - 1].getZ(), stack);
final Calibration impCalibration = layer[0].getParent().getCalibrationCopy();
impCalibration.pixelWidth /= scale;
impCalibration.pixelHeight /= scale;
imp.setCalibration(impCalibration);
}
} else {
imp = getFlatImage(layer[0], srcRect_, scale, c_alphas, type, Displayable.class, null, quality, background);
if (null != target_dir) {
saveToPath(imp, target_dir, layer[0].getPrintableTitle(), format);
// to prevent showing it
imp = null;
}
}
if (null != imp)
imp.show();
} catch (final Throwable e) {
IJError.print(e);
}
finishedWorking();
}
};
// I miss my lisp macros, you have no idea
return Bureaucrat.createAndStart(worker, layer[0].getProject());
}
Aggregations