use of ini.trakem2.display.Tag in project TrakEM2 by trakem2.
the class Loader method preProcess.
protected final void preProcess(final Patch p, ImagePlus imp, final long image_n_bytes) {
if (null == p)
return;
try {
final String path = preprocessors.get(p);
boolean update = false;
if (null != path) {
final File f = new File(path);
if (!f.exists()) {
Utils.log("ERROR: preprocessor script file does NOT exist: " + path);
return;
} else if (!f.canRead()) {
Utils.log("ERROR: can NOT read preprocessor script file at: " + path);
return;
}
if (null == imp) {
// uninitialized: the script may generate its data
imp = new ImagePlus();
} else {
// Prepare image for pre-processing
// for 8-bit and RGB images, your problem: setting min and max will expand the range.
imp.getProcessor().setMinAndMax(p.getMin(), p.getMax());
}
// Free 10 times the memory taken by the image, as a gross estimate of memory consumption by the script
releaseToFit(Math.min(10 * image_n_bytes, MAX_MEMORY / 4));
// Run the script
ini.trakem2.scripting.PatchScript.run(p, imp, path);
// Update Patch image properties:
if (null != imp.getProcessor() && null != imp.getProcessor().getPixels() && imp.getWidth() > 0 && imp.getHeight() > 0) {
update = true;
} else {
Utils.log("ERROR: preprocessor script failed to create a valid image:" + "\n ImageProcessor: " + imp.getProcessor() + "\n pixel array: " + (null == imp.getProcessor() ? null : imp.getProcessor().getPixels()) + "\n width: " + imp.getWidth() + "\n height: " + imp.getHeight());
}
}
// Now apply the Patch filters, if any
final IFilter[] fs = p.getFilters();
if (null != fs && fs.length > 0) {
ImageProcessor ip = imp.getProcessor();
for (final IFilter filter : fs) {
ip = filter.process(ip);
}
if (ip != imp.getProcessor()) {
imp.setProcessor(ip);
}
update = true;
}
// Now apply intensity correction if available
update |= mapIntensities(p, imp);
if (update) {
// 1: Tag the ImagePlus as altered (misuses fileFormat field, which is unused in any case)
final FileInfo fi = imp.getOriginalFileInfo();
// otherwise, the null original FileInfo is a valid tag by itself in the persistence.Cache
if (null != fi)
fi.fileFormat = Loader.PREPROCESSED;
// 2: cache
cache(p, imp);
// 3: update properties of the Patch
p.updatePixelProperties(imp);
}
} catch (final Exception e) {
IJError.print(e);
}
}
use of ini.trakem2.display.Tag in project TrakEM2 by trakem2.
the class Loader method importGrid.
/**
* Import a grid of images and put them in the layer. If the directory (@param dir) is null, it'll be asked for.
*/
public Bureaucrat importGrid(final Layer layer, String dir) {
try {
String file = null;
if (null == dir) {
final String[] dn = Utils.selectFile("Select first image");
if (null == dn)
return null;
dir = dn[0];
file = dn[1];
}
// char digit digit
String convention = "cdd";
boolean chars_are_columns = true;
// examine file name
/*
if (file.matches("\\A[a-zA-Z]\\d\\d.*")) { // one letter, 2 numbers
//means:
// \A - beggining of input
// [a-zA-Z] - any letter upper or lower case
// \d\d - two consecutive digits
// .* - any row of chars
ini_grid_convention = true;
}
*/
// ask for chars->rows, numbers->columns or viceversa
final GenericDialog gd = new GenericDialog("Conventions");
gd.addStringField("file_name_contains:", "");
gd.addNumericField("base_x: ", 0, 3);
gd.addNumericField("base_y: ", 0, 3);
gd.addMessage("Use: x(any), c(haracter), d(igit)");
gd.addStringField("convention: ", convention);
final String[] cr = new String[] { "columns", "rows" };
gd.addChoice("characters are: ", cr, cr[0]);
gd.addMessage("[File extension ignored]");
// as asked by Joachim Walter
gd.addNumericField("bottom-top overlap: ", 0, 3);
gd.addNumericField("left-right overlap: ", 0, 3);
gd.addCheckbox("link_images", false);
gd.addCheckbox("montage with phase correlation", false);
gd.addCheckbox("homogenize_contrast", true);
final Component[] c = { (Component) gd.getSliders().get(gd.getSliders().size() - 2), (Component) gd.getNumericFields().get(gd.getNumericFields().size() - 2), (Component) gd.getSliders().get(gd.getSliders().size() - 1), (Component) gd.getNumericFields().get(gd.getNumericFields().size() - 1), (Component) gd.getChoices().get(gd.getChoices().size() - 1) };
// enable the checkbox to control the slider and its associated numeric field:
Utils.addEnablerListener((Checkbox) gd.getCheckboxes().get(gd.getCheckboxes().size() - 1), c, null);
// gd.addCheckbox("Apply non-linear deformation", false);
gd.showDialog();
if (gd.wasCanceled()) {
return null;
}
// collect data
// filter away files not containing this tag
final String regex = gd.getNextString();
// the base x,y of the whole grid
final double bx = gd.getNextNumber();
final double by = gd.getNextNumber();
// if (!ini_grid_convention) {
convention = gd.getNextString().toLowerCase();
// }
if (/*!ini_grid_convention && */
(null == convention || convention.equals("") || -1 == convention.indexOf('c') || -1 == convention.indexOf('d'))) {
// TODO check that the convention has only 'cdx' chars and also that there is an island of 'c's and of 'd's only.
Utils.showMessage("Convention '" + convention + "' needs both c(haracters) and d(igits), optionally 'x', and nothing else!");
return null;
}
chars_are_columns = (0 == gd.getNextChoiceIndex());
final double bt_overlap = gd.getNextNumber();
final double lr_overlap = gd.getNextNumber();
final boolean link_images = gd.getNextBoolean();
final boolean stitch_tiles = gd.getNextBoolean();
final boolean homogenize_contrast = gd.getNextBoolean();
// start magic
// get ImageJ-openable files that comply with the convention
final File images_dir = new File(dir);
if (!(images_dir.exists() && images_dir.isDirectory())) {
Utils.showMessage("Something went wrong:\n\tCan't find directory " + dir);
return null;
}
final String[] file_names = images_dir.list(new ImageFileFilter(regex, convention));
if (null == file && file_names.length > 0) {
// the 'selected' file
file = file_names[0];
}
Utils.showStatus("Adding " + file_names.length + " patches.", false);
if (0 == file_names.length) {
Utils.log("Zero files match the convention '" + convention + "'");
return null;
}
// How to: select all files, and order their names in a double array as they should be placed in the Display. Then place them, displacing by offset, and resizing if necessary.
// gather image files:
final Montage montage = new Montage(convention, chars_are_columns);
montage.addAll(file_names);
// an array of Object[] arrays, of unequal length maybe, each containing a column of image file names
final ArrayList<String[]> cols = montage.getCols();
// !@#$%^&*
final String dir_ = dir;
final double bt_overlap_ = bt_overlap;
final double lr_overlap_ = lr_overlap;
final String file_ = file;
return Bureaucrat.createAndStart(new Worker.Task("Insert grid", true) {
@Override
public void exec() {
StitchingTEM.PhaseCorrelationParam pc_param = null;
if (stitch_tiles) {
pc_param = new StitchingTEM.PhaseCorrelationParam();
pc_param.setup(layer);
}
insertGrid(layer, dir_, file_, file_names.length, cols, bx, by, bt_overlap_, lr_overlap_, link_images, stitch_tiles, homogenize_contrast, pc_param, this);
}
}, layer.getProject());
} catch (final Exception e) {
IJError.print(e);
}
return null;
}
use of ini.trakem2.display.Tag in project TrakEM2 by trakem2.
the class TMLHandler method makeLayerThing.
private LayerThing makeLayerThing(String type, final HashMap<String, String> ht_attributes) {
try {
type = type.toLowerCase();
if (0 == type.indexOf("t2_")) {
type = type.substring(3);
}
// long id = -1;
// final String sid = ht_attributes.get("id");
// if (null != sid) id = Long.parseLong(sid);
long oid = -1;
final String soid = ht_attributes.get("oid");
if (null != soid)
oid = Long.parseLong(soid);
if (type.equals("node")) {
if (null == last_tree) {
throw new NullPointerException("Can't create a node for null last_tree!");
}
final Node<?> node = last_tree.newNode(ht_attributes);
taggables.add(node);
// Put node into the list of nodes with that layer id, to update to proper Layer pointer later
final long ndlid = Long.parseLong(ht_attributes.get("lid"));
List<Node<?>> list = node_layer_table.get(ndlid);
if (null == list) {
list = new ArrayList<Node<?>>();
node_layer_table.put(ndlid, list);
}
list.add(node);
// Set node as root node or add as child to last node in the stack
if (null == last_root_node) {
last_root_node = node;
} else {
final String sconf = ht_attributes.get("c");
nodes.getLast().add((Node) node, null == sconf ? Node.MAX_EDGE_CONFIDENCE : Byte.parseByte(sconf));
}
// color?
final String scolor = ht_attributes.get("color");
if (null != scolor) {
final Color color = Utils.getRGBColorFromHex(scolor);
Collection<Node<?>> nodes = node_colors.get(color);
if (null == nodes) {
nodes = new ArrayList<Node<?>>();
node_colors.put(color, nodes);
}
nodes.add(node);
}
// Put node into stack of nodes (to be removed on closing the tag)
nodes.add(node);
} else if (type.equals("profile")) {
Profile profile = new Profile(this.project, oid, ht_attributes, ht_links);
profile.addToDatabase();
ht_displayables.put(oid, profile);
addToLastOpenLayer(profile);
last_displayable = profile;
return null;
} else if (type.equals("pipe")) {
Pipe pipe = new Pipe(this.project, oid, ht_attributes, ht_links);
pipe.addToDatabase();
ht_displayables.put(new Long(oid), pipe);
ht_zdispl.put(new Long(oid), pipe);
last_displayable = pipe;
addToLastOpenLayerSet(pipe);
return null;
} else if (type.equals("polyline")) {
Polyline pline = new Polyline(this.project, oid, ht_attributes, ht_links);
pline.addToDatabase();
last_displayable = pline;
ht_displayables.put(new Long(oid), pline);
ht_zdispl.put(new Long(oid), pline);
addToLastOpenLayerSet(pline);
return null;
} else if (type.equals("connector")) {
final Connector con = new Connector(this.project, oid, ht_attributes, ht_links);
if (ht_attributes.containsKey("origin")) {
legacy.add(new Runnable() {
public void run() {
con.readLegacyXML(al_layer_sets.get(al_layer_sets.size() - 1), ht_attributes, ht_links);
}
});
}
con.addToDatabase();
last_connector = con;
last_tree = con;
last_displayable = con;
ht_displayables.put(new Long(oid), con);
ht_zdispl.put(new Long(oid), con);
addToLastOpenLayerSet(con);
return null;
} else if (type.equals("path")) {
if (null != reca) {
reca.add(ht_attributes.get("d"));
return null;
}
return null;
} else if (type.equals("area")) {
reca = new ReconstructArea();
if (null != last_area_list) {
last_area_list_layer_id = Long.parseLong(ht_attributes.get("layer_id"));
}
return null;
} else if (type.equals("area_list")) {
AreaList area = new AreaList(this.project, oid, ht_attributes, ht_links);
// why? This looks like an onion
area.addToDatabase();
last_area_list = area;
last_displayable = area;
ht_displayables.put(new Long(oid), area);
ht_zdispl.put(new Long(oid), area);
addToLastOpenLayerSet(area);
return null;
} else if (type.equals("tag")) {
Taggable t = taggables.getLast();
if (null != t) {
Object ob = ht_attributes.get("key");
// defaults to 't'
int keyCode = KeyEvent.VK_T;
// KeyEvent.VK_U is char U, not u
if (null != ob)
keyCode = (int) ((String) ob).toUpperCase().charAt(0);
Tag tag = al_layer_sets.get(al_layer_sets.size() - 1).putTag(ht_attributes.get("name"), keyCode);
// could be null if name is not found
if (null != tag)
t.addTag(tag);
}
} else if (type.equals("ball_ob")) {
// add a ball to the last open Ball
if (null != last_ball) {
last_ball.addBall(Double.parseDouble(ht_attributes.get("x")), Double.parseDouble(ht_attributes.get("y")), Double.parseDouble(ht_attributes.get("r")), Long.parseLong(ht_attributes.get("layer_id")));
}
return null;
} else if (type.equals("ball")) {
Ball ball = new Ball(this.project, oid, ht_attributes, ht_links);
ball.addToDatabase();
last_ball = ball;
last_displayable = ball;
ht_displayables.put(new Long(oid), ball);
ht_zdispl.put(new Long(oid), ball);
addToLastOpenLayerSet(ball);
return null;
} else if (type.equals("stack")) {
Stack stack = new Stack(this.project, oid, ht_attributes, ht_links);
stack.addToDatabase();
last_stack = stack;
last_displayable = stack;
ht_displayables.put(new Long(oid), stack);
ht_zdispl.put(new Long(oid), stack);
addToLastOpenLayerSet(stack);
} else if (type.equals("treeline")) {
Treeline tline = new Treeline(this.project, oid, ht_attributes, ht_links);
tline.addToDatabase();
last_treeline = tline;
last_tree = tline;
last_treeline_data = new StringBuilder();
last_displayable = tline;
ht_displayables.put(oid, tline);
ht_zdispl.put(oid, tline);
addToLastOpenLayerSet(tline);
} else if (type.equals("areatree")) {
AreaTree art = new AreaTree(this.project, oid, ht_attributes, ht_links);
art.addToDatabase();
last_areatree = art;
last_tree = art;
last_displayable = art;
ht_displayables.put(oid, art);
ht_zdispl.put(oid, art);
addToLastOpenLayerSet(art);
} else if (type.equals("dd_item")) {
if (null != last_dissector) {
last_dissector.addItem(Integer.parseInt(ht_attributes.get("tag")), Integer.parseInt(ht_attributes.get("radius")), ht_attributes.get("points"));
}
} else if (type.equals("label")) {
DLabel label = new DLabel(project, oid, ht_attributes, ht_links);
label.addToDatabase();
ht_displayables.put(new Long(oid), label);
addToLastOpenLayer(label);
last_displayable = label;
return null;
} else if (type.equals("annot")) {
last_annotation = new StringBuilder();
return null;
} else if (type.equals("patch")) {
Patch patch = new Patch(project, oid, ht_attributes, ht_links);
patch.addToDatabase();
ht_displayables.put(new Long(oid), patch);
addToLastOpenLayer(patch);
last_patch = patch;
last_displayable = patch;
checkAlphaMasks(patch);
return null;
} else if (type.equals("filter")) {
last_patch_filters.add(newFilter(ht_attributes));
} else if (type.equals("dissector")) {
Dissector dissector = new Dissector(this.project, oid, ht_attributes, ht_links);
dissector.addToDatabase();
last_dissector = dissector;
last_displayable = dissector;
ht_displayables.put(new Long(oid), dissector);
ht_zdispl.put(new Long(oid), dissector);
addToLastOpenLayerSet(dissector);
} else if (type.equals("layer")) {
// find last open LayerSet, if any
for (int i = al_layer_sets.size() - 1; i > -1; ) {
LayerSet set = al_layer_sets.get(i);
Layer layer = new Layer(project, oid, ht_attributes);
layer.addToDatabase();
set.addSilently(layer);
al_layers.add(layer);
Object ot = ht_attributes.get("title");
return new LayerThing(template_layer_thing, project, -1, (null == ot ? null : (String) ot), layer, null);
}
} else if (type.equals("layer_set")) {
LayerSet set = new LayerSet(project, oid, ht_attributes, ht_links);
last_displayable = set;
set.addToDatabase();
ht_displayables.put(new Long(oid), set);
al_layer_sets.add(set);
addToLastOpenLayer(set);
Object ot = ht_attributes.get("title");
return new LayerThing(template_layer_set_thing, project, -1, (null == ot ? null : (String) ot), set, null);
} else if (type.equals("calibration")) {
// find last open LayerSet if any
for (int i = al_layer_sets.size() - 1; i > -1; ) {
LayerSet set = al_layer_sets.get(i);
set.restoreCalibration(ht_attributes);
return null;
}
} else if (type.equals("prop")) {
// Add property to last created Displayable
if (null != last_displayable) {
last_displayable.setProperty(ht_attributes.get("key"), ht_attributes.get("value"));
}
} else if (type.equals("linked_prop")) {
// Add linked property to last created Displayable. Has to wait until the Displayable ids have been resolved to instances.
if (null != last_displayable) {
putLinkedProperty(last_displayable, ht_attributes);
}
} else {
Utils.log2("TMLHandler Unknown type: " + type);
}
} catch (Exception e) {
IJError.print(e);
}
// default:
return null;
}
use of ini.trakem2.display.Tag in project TrakEM2 by trakem2.
the class Search method executeSearch.
private void executeSearch() {
final Project project = Project.getProjects().get(projects.getSelectedIndex());
if (null == project) {
// Should not happen
return;
}
Bureaucrat.createAndStart(new Worker.Task("Searching") {
public void exec() {
String pattern = search_field.getText();
if (null == pattern || 0 == pattern.length()) {
return;
}
// fix pattern
final String typed_pattern = pattern;
// I hate java
final StringBuilder sb = new StringBuilder();
if (!pattern.startsWith("^"))
sb.append("^.*");
for (int i = 0; i < pattern.length(); i++) {
sb.append(pattern.charAt(i));
}
if (!pattern.endsWith("$"))
sb.append(".*$");
pattern = sb.toString();
final Pattern pat = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
// Utils.log2("pattern after: " + pattern);
final ArrayList<DBObject> al = new ArrayList<DBObject>();
// Utils.log("types[pulldown] = " +
// types[pulldown.getSelectedIndex()]);
find(project.getRootLayerSet(), al, types[pulldown.getSelectedIndex()]);
// Utils.log2("found labels: " + al.size());
if (0 == al.size())
return;
final Vector<DBObject> v_obs = new Vector<DBObject>();
final Vector<String> v_txt = new Vector<String>();
final Vector<Coordinate<?>> v_co = new Vector<Coordinate<?>>();
Coordinate<?> co = null;
for (final DBObject dbo : al) {
if (Thread.currentThread().isInterrupted()) {
return;
}
boolean matched = false;
// Search in its title
Displayable d = null;
if (dbo instanceof Displayable) {
d = (Displayable) dbo;
}
String txt;
String meaningful_title = null;
if (null == d || Patch.class == d.getClass())
txt = dbo.getTitle();
else {
txt = meaningful_title = dbo.getProject().getMeaningfulTitle(d);
}
if (null == txt || 0 == txt.trim().length())
continue;
matched = pat.matcher(txt).matches();
if (!matched && null != d) {
// Search also in its annotation
txt = d.getAnnotation();
if (null != txt)
matched = pat.matcher(txt).matches();
}
if (!matched) {
// Search also in its toString()
txt = dbo.toString();
matched = pat.matcher(txt).matches();
}
if (!matched) {
// Search also in its id
txt = Long.toString(dbo.getId());
matched = pat.matcher(txt).matches();
if (matched)
txt = "id: #" + txt;
}
if (!matched && null != d) {
// Search also in its properties
Map<String, String> props = d.getProperties();
if (null != props) {
for (final Map.Entry<String, String> e : props.entrySet()) {
if (pat.matcher(e.getKey()).matches() || pat.matcher(e.getValue()).matches()) {
matched = true;
txt = e.getKey() + " => " + e.getValue() + " [property]";
break;
}
}
}
if (!matched) {
Map<Displayable, Map<String, String>> linked_props = ((Displayable) dbo).getLinkedProperties();
if (null != linked_props) {
for (final Map.Entry<Displayable, Map<String, String>> e : linked_props.entrySet()) {
for (final Map.Entry<String, String> ee : e.getValue().entrySet()) {
if (pat.matcher(ee.getKey()).matches() || pat.matcher(ee.getValue()).matches()) {
matched = true;
txt = ee.getKey() + " => " + e.getValue() + " [linked property]";
break;
}
}
}
}
}
}
if (!matched && dbo instanceof Tree<?>) {
// search Node tags
Node<?> root = ((Tree<?>) dbo).getRoot();
if (null == root)
continue;
for (final Node<?> nd : root.getSubtreeNodes()) {
Set<Tag> tags = nd.getTags();
if (null == tags)
continue;
for (final Tag tag : tags) {
if (pat.matcher(tag.toString()).matches()) {
v_obs.add(dbo);
v_txt.add(new StringBuilder(tag.toString()).append(" (").append(null == meaningful_title ? dbo.toString() : meaningful_title).append(')').toString());
v_co.add(createCoordinate((Tree<?>) dbo, nd));
}
}
}
// all added if any
continue;
}
if (!matched)
continue;
// txt = txt.length() > 30 ? txt.substring(0, 27) + "..." :
// txt;
v_obs.add(dbo);
v_txt.add(txt);
v_co.add(co);
}
if (0 == v_obs.size()) {
Utils.showMessage("Nothing found.");
return;
}
final JPanel result = new JPanel();
GridBagLayout gb = new GridBagLayout();
result.setLayout(gb);
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.NORTHWEST;
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(5, 10, 5, 10);
String xml = "";
if (project.getLoader() instanceof FSLoader) {
String path = ((FSLoader) project.getLoader()).getProjectXMLPath();
if (null != path) {
xml = " [" + new File(path).getName() + "]";
}
}
JLabel projectTitle = new JLabel(project.getTitle() + xml);
gb.setConstraints(projectTitle, c);
result.add(projectTitle);
c.insets = new Insets(0, 0, 0, 0);
JPanel padding = new JPanel();
c.weightx = 1;
gb.setConstraints(padding, c);
result.add(padding);
c.gridy = 1;
c.gridwidth = 2;
c.fill = GridBagConstraints.BOTH;
c.weighty = 1;
JScrollPane jsp = makeTable(new DisplayableTableModel(v_obs, v_txt, v_co), project);
gb.setConstraints(jsp, c);
result.add(jsp);
search_tabs.addTab(typed_pattern, result);
search_tabs.setSelectedComponent(result);
synchronized (tabMap) {
List<JPanel> cs = tabMap.get(project);
if (null == cs) {
cs = new ArrayList<JPanel>();
tabMap.put(project, cs);
}
cs.add(result);
}
}
}, project);
}
Aggregations