Search in sources :

Example 1 with Stack

use of ini.trakem2.display.Stack in project TrakEM2 by trakem2.

the class DBLoader method fetchImagePlus.

public ImagePlus fetchImagePlus(Patch p) {
    synchronized (db_lock) {
        long id = p.getId();
        // see if the ImagePlus is cached:
        ImagePlus imp = mawts.get(id);
        if (null != imp) {
            if (null != imp.getProcessor() && null != imp.getProcessor().getPixels()) {
                // may have been flushed by ImageJ, for example when making images from a stack
                return imp;
            } else {
                // can't hurt
                flush(imp);
            }
        }
        // connect if disconnected
        if (!connectToDatabase()) {
            return null;
        }
        releaseMemory2();
        InputStream i_stream = null;
        try {
            // StopWatch sw = new StopWatch();
            ResultSet r = connection.prepareStatement("SELECT tiff_working FROM ab_patches WHERE tiff_working IS NOT NULL AND id=" + id).executeQuery();
            boolean found = false;
            if (r.next()) {
                found = true;
                // sw.elapsed();
                i_stream = r.getBinaryStream("tiff_working");
                // sw.elapsed();
                imp = unzipTiff(i_stream, p.getTitle());
                // sw.elapsed();
                i_stream.close();
                mawts.put(id, imp, (int) Math.max(p.getWidth(), p.getHeight()));
            }
            r.close();
            // if the working is not there, fetch the original instead
            if (!found) {
                r = connection.prepareStatement("SELECT tiff_original FROM ab_patches WHERE id=" + id).executeQuery();
                if (r.next()) {
                    // sw.elapsed();
                    i_stream = r.getBinaryStream("tiff_original");
                    // sw.elapsed();
                    // will apply the preprocessor plugin to it as well
                    imp = unzipTiff(i_stream, p.getTitle());
                    // sw.elapsed();
                    i_stream.close();
                    mawts.put(id, imp, (int) Math.max(p.getWidth(), p.getHeight()));
                }
                r.close();
            }
            // non-destructive contrast: min and max
            if (null != imp) {
            // OBSOLETE and wrong -- but then this whole class is obsolete// p.putMinAndMax(imp);
            }
        } catch (Exception e) {
            IJError.print(e);
            if (null != i_stream) {
                try {
                    i_stream.close();
                } catch (Exception ie) {
                    IJError.print(ie);
                }
            }
            return null;
        }
        return imp;
    }
}
Also used : LoggingInputStream(ini.trakem2.io.LoggingInputStream) InputStream(java.io.InputStream) ResultSet(java.sql.ResultSet) ImagePlus(ij.ImagePlus) SQLException(java.sql.SQLException)

Example 2 with Stack

use of ini.trakem2.display.Stack in project TrakEM2 by trakem2.

the class PatchStack method createColor256Copy.

// WARNING This method will fail if the stack has slices of different dimensions
/**
 * Does not respect local transform of the patches, this is intended for confocal stacks.
 */
public ImagePlus createColor256Copy() {
    final Rectangle box = patch[0].getBoundingBox();
    final int width = box.width;
    final int height = box.height;
    Loader loader = patch[0].getProject().getLoader();
    // the montage, in RGB
    patch[0].getProject().getLoader().releaseToFit(4 * patch.length * width * height);
    final ColorProcessor montage = new ColorProcessor(width * patch.length, height);
    for (int i = 0; i < patch.length; i++) {
        montage.insert(this.stack.getProcessor(i + 1), i * width, 0);
    }
    final MedianCut mc = new MedianCut(montage);
    loader.releaseToFit(patch.length * width * height);
    ImageProcessor m2 = mc.convertToByte(256);
    final ImageStack st = new ImageStack(width, height);
    for (int i = 0; i < patch.length; i++) {
        m2.setRoi(i * width, 0, width, height);
        loader.releaseToFit(width * height);
        st.addSlice(null, m2.crop());
    }
    ImagePlus imp = new ImagePlus("color256", st);
    imp.setCalibration(patch[0].getLayer().getParent().getCalibrationCopy());
    // imp.getCalibration().pixelDepth = patch[0].getLayer().getThickness();
    return imp;
}
Also used : ImageProcessor(ij.process.ImageProcessor) ColorProcessor(ij.process.ColorProcessor) ImageStack(ij.ImageStack) Rectangle(java.awt.Rectangle) Loader(ini.trakem2.persistence.Loader) MedianCut(ij.process.MedianCut) ImagePlus(ij.ImagePlus)

Example 3 with Stack

use of ini.trakem2.display.Stack in project TrakEM2 by trakem2.

the class PatchStack method createGray8Copy.

// WARNING This method will fail if the stack has slices of different dimensions
/**
 * Does not respect local transform of the patches, this is intended for confocal stacks.
 */
public ImagePlus createGray8Copy() {
    final Rectangle box = patch[0].getBoundingBox();
    final int width = box.width;
    final int height = box.height;
    // compute minimum bounding box
    ImageStack st = new ImageStack(width, height);
    Loader loader = patch[0].getProject().getLoader();
    for (int i = 1; i < patch.length; i++) {
        loader.releaseToFit(width * height);
        st.addSlice(Integer.toString(i), this.stack.getProcessor(i).convertToByte(true));
    }
    ImagePlus imp = new ImagePlus("byte", st);
    imp.setCalibration(patch[0].getLayer().getParent().getCalibrationCopy());
    // imp.getCalibration().pixelDepth = patch[0].getLayer().getThickness();
    return imp;
}
Also used : ImageStack(ij.ImageStack) Rectangle(java.awt.Rectangle) Loader(ini.trakem2.persistence.Loader) ImagePlus(ij.ImagePlus)

Example 4 with Stack

use of ini.trakem2.display.Stack 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;
}
Also used : Displayable(ini.trakem2.display.Displayable) ArrayList(java.util.ArrayList) StackStatistics(ij.process.StackStatistics) Calibration(ij.measure.Calibration) TreeMap(java.util.TreeMap) ImagePlus(ij.ImagePlus) ImageProcessor(ij.process.ImageProcessor) ImageStatistics(ij.process.ImageStatistics) SortedMap(java.util.SortedMap) TaskFactory(ini.trakem2.parallel.TaskFactory) EqualizeHistogram(ini.trakem2.imaging.filters.EqualizeHistogram) Patch(ini.trakem2.display.Patch)

Example 5 with Stack

use of ini.trakem2.display.Stack in project TrakEM2 by trakem2.

the class LayerStack method getProcessor.

/**
 * Returns an ImageProcessor for the specified slice,
 *		where {@code 1<=n<=nslices}. Returns null if the stack is empty.
 */
@Override
public ImageProcessor getProcessor(int n) {
    if (n < 1 || n > layers.size())
        return null;
    // Create a flat image on the fly with everything on it, and return its processor.
    final Layer layer = layers.get(n - 1);
    final Loader loader = layer.getProject().getLoader();
    Long cid;
    synchronized (id_cache) {
        cid = id_cache.get(layer.getId());
        if (null == cid) {
            cid = loader.getNextTempId();
            id_cache.put(layer.getId(), cid);
        }
    }
    ImageProcessor ip;
    synchronized (cid) {
        ImagePlus imp = loader.getCachedImagePlus(cid);
        if (null == imp || null == imp.getProcessor() || null == imp.getProcessor().getPixels()) {
            ip = loader.getFlatImage(layer, this.roi, this.scale, this.c_alphas, this.type, this.clazz, null).getProcessor();
            if (invert)
                ip.invert();
            loader.cacheImagePlus(cid, new ImagePlus("", ip));
        } else
            ip = imp.getProcessor();
    }
    return ip;
}
Also used : ImageProcessor(ij.process.ImageProcessor) Loader(ini.trakem2.persistence.Loader) Layer(ini.trakem2.display.Layer) ImagePlus(ij.ImagePlus)

Aggregations

ImagePlus (ij.ImagePlus)21 Layer (ini.trakem2.display.Layer)16 ArrayList (java.util.ArrayList)15 Rectangle (java.awt.Rectangle)13 Patch (ini.trakem2.display.Patch)12 ImageStack (ij.ImageStack)11 AffineTransform (java.awt.geom.AffineTransform)11 ImageProcessor (ij.process.ImageProcessor)8 Area (java.awt.geom.Area)8 File (java.io.File)8 HashMap (java.util.HashMap)8 TreeMap (java.util.TreeMap)8 Point (java.awt.Point)7 HashSet (java.util.HashSet)7 Map (java.util.Map)7 GenericDialog (ij.gui.GenericDialog)6 Calibration (ij.measure.Calibration)6 Displayable (ini.trakem2.display.Displayable)6 Worker (ini.trakem2.utils.Worker)6 DirectoryChooser (ij.io.DirectoryChooser)5