Search in sources :

Example 61 with ImagePlus

use of ij.ImagePlus in project TrakEM2 by trakem2.

the class DBLoader method importStackAsPatches.

/**
 * Returns the last Patch.
 */
protected Patch importStackAsPatches(final Project project, final Layer first_layer, final double x, final double y, final ImagePlus imp_stack, final boolean as_copy, final String filepath) {
    double pos_x = Double.MAX_VALUE != x ? x : first_layer.getLayerWidth() / 2 - imp_stack.getWidth() / 2;
    double pos_y = Double.MAX_VALUE != y ? y : first_layer.getLayerHeight() / 2 - imp_stack.getHeight() / 2;
    final double thickness = first_layer.getThickness();
    final String title = Utils.removeExtension(imp_stack.getTitle()).replace(' ', '_');
    Utils.showProgress(0);
    Patch previous_patch = null;
    final int n = imp_stack.getStackSize();
    for (int i = 1; i <= n; i++) {
        Layer layer = first_layer;
        double z = first_layer.getZ() + (i - 1) * thickness;
        // will create new layer if not found
        if (i > 1)
            layer = first_layer.getParent().getLayer(z, thickness, true);
        if (null == layer) {
            Utils.log("Display.importStack: could not create new layers.");
            return null;
        }
        ImageProcessor ip = imp_stack.getStack().getProcessor(i);
        if (as_copy)
            ip = ip.duplicate();
        ImagePlus imp_patch_i = new ImagePlus(title + "__slice=" + i, ip);
        String label = imp_stack.getStack().getSliceLabel(i);
        if (null == label)
            label = "";
        Patch patch = new Patch(project, label + " " + title + " " + i, pos_x, pos_y, imp_patch_i);
        layer.add(patch);
        if (null != previous_patch)
            patch.link(previous_patch);
        previous_patch = patch;
        Utils.showProgress(i * (1.0 / n));
    }
    Utils.showProgress(1.0);
    // return the last Patch
    return previous_patch;
}
Also used : ImageProcessor(ij.process.ImageProcessor) Patch(ini.trakem2.display.Patch) Layer(ini.trakem2.display.Layer) ImagePlus(ij.ImagePlus) Point(java.awt.Point) PGpoint(org.postgresql.geometric.PGpoint)

Example 62 with ImagePlus

use of ij.ImagePlus 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 63 with ImagePlus

use of ij.ImagePlus in project TrakEM2 by trakem2.

the class DBLoader method updateInDatabase.

/**
 * The ImagePlus, if updated, is saved in the 'tiff_working' column always.
 */
private void updateInDatabase(Patch patch, String key) throws Exception {
    if (key.equals("tiff_snapshot")) {
        /* // DEPRECATED, now using mipmaps
			InputStream i_stream = null;
			try {
				ImagePlus imp = new ImagePlus("s", snaps.get(patch.getId())); // not calling fetchSnapshot because old code could end in a loop.
				if (null == imp) {
					Utils.log2("DBLoader: snapshot ImagePlus is null!");
					stmt_update_snap.setNull(1, java.sql.Types.BINARY);
				} else {
					i_stream = createZippedStream(imp);
					stmt_update_snap.setBinaryStream(1, i_stream, i_stream.available());
					flush(imp);
				}
				stmt_update_snap.setLong(2, patch.getId());
				stmt_update_snap.executeUpdate();
			} catch (Exception e) {
				IJError.print(e);
			} finally {
				if (null != i_stream) try { i_stream.close(); } catch (Exception e1) { IJError.print(e1); }
			}
			*/
        return;
    }
    StringBuffer sb = new StringBuffer("UPDATE ab_patches SET ");
    boolean update_imp = false;
    if (key.equals("tiff_working")) {
        sb.append("imp_type=").append(patch.getType()).append(", tiff_working=?");
        update_imp = true;
    } else if (key.equals("remove_tiff_working")) {
        sb.append("tiff_working=NULL");
    } else if (key.equals("min_and_max")) {
        sb.append("min=").append(patch.getMin()).append(", max=").append(patch.getMax());
    } else {
        // try the Displayable level
        updateInDatabase((Displayable) patch, key);
        return;
    }
    PreparedStatement st = connection.prepareStatement(sb.append(" WHERE id=").append(patch.getId()).toString());
    int i = 1;
    InputStream i_stream2 = null;
    try {
        if (update_imp) {
            // WARNING if the cache is very small relative to the size of the images, this strategy may fail
            ImagePlus imp = mawts.get(patch.getId());
            i_stream2 = createZippedStream(imp);
            st.setBinaryStream(i, i_stream2, i_stream2.available());
            // defensive programming: if later I add any other ..
            i++;
        }
        st.executeUpdate();
        if (null != i_stream2)
            i_stream2.close();
    } catch (Exception e) {
        IJError.print(e);
        if (null != i_stream2)
            try {
                i_stream2.close();
            } catch (Exception e2) {
                IJError.print(e2);
            }
    }
}
Also used : LoggingInputStream(ini.trakem2.io.LoggingInputStream) InputStream(java.io.InputStream) PreparedStatement(java.sql.PreparedStatement) ImagePlus(ij.ImagePlus) Point(java.awt.Point) PGpoint(org.postgresql.geometric.PGpoint) SQLException(java.sql.SQLException)

Example 64 with ImagePlus

use of ij.ImagePlus in project TrakEM2 by trakem2.

the class DBLoader method fetchOriginal.

public synchronized ImagePlus fetchOriginal(Patch patch) {
    // connect if disconnected
    if (!connectToDatabase()) {
        return null;
    }
    // assume RGB, thus multiply by 4 (an int has 4 bytes)
    long imp_size = (long) (patch.getWidth() * patch.getHeight() * 4);
    releaseToFit(MIN_FREE_BYTES > imp_size ? MIN_FREE_BYTES : imp_size);
    ImagePlus imp = null;
    InputStream i_stream = null;
    try {
        ResultSet r = connection.prepareStatement("SELECT id, tiff_original FROM ab_patches WHERE id=" + patch.getId()).executeQuery();
        if (r.next()) {
            // fetch stream
            i_stream = r.getBinaryStream("tiff_original");
            imp = unzipTiff(i_stream, patch.getTitle());
            i_stream.close();
        }
        r.close();
    } catch (Exception e) {
        Utils.log("Loader.fetchOriginal: ERROR fetching original ImagePlus for Patch id=" + patch.getId());
        IJError.print(e);
        if (null != i_stream) {
            try {
                i_stream.close();
            } catch (Exception ee) {
                Utils.log("Loader.fetchOriginal: could not close stream.");
            }
        }
        return null;
    }
    if (null == imp)
        Utils.log("WARNING fetching a null original");
    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 65 with ImagePlus

use of ij.ImagePlus in project TrakEM2 by trakem2.

the class AmiraImporter method importAmiraLabels.

/**
 * Returns the array of AreaList or null if the file dialog is canceled. The xo,yo is the pivot of reference.
 */
public static Collection<AreaList> importAmiraLabels(Layer first_layer, double xo, double yo, final String default_dir) {
    // open file
    OpenDialog od = new OpenDialog("Choose Amira Labels File", default_dir, "");
    String filename = od.getFileName();
    if (null == filename || 0 == filename.length())
        return null;
    String dir = od.getDirectory();
    if (IJ.isWindows())
        dir = dir.replace('\\', '/');
    if (!dir.endsWith("/"))
        dir += "/";
    String path = dir + filename;
    AmiraMeshDecoder dec = new AmiraMeshDecoder();
    if (!dec.open(path)) {
        YesNoDialog yn = new YesNoDialog("Error", "File was not an Amira labels file.\nChoose another one?");
        if (yn.yesPressed())
            return importAmiraLabels(first_layer, xo, yo, default_dir);
        return null;
    }
    ImagePlus imp = null;
    if (dec.isTable()) {
        Utils.showMessage("Select the other file (the labels)!");
        return null;
    } else {
        FileInfo fi = new FileInfo();
        fi.fileName = filename;
        fi.directory = dir;
        imp = new ImagePlus("Amira", dec.getStack());
        dec.parameters.setParameters(imp);
    }
    return extractAmiraLabels(imp, dec.parameters, first_layer, xo, yo);
}
Also used : AmiraMeshDecoder(amira.AmiraMeshDecoder) FileInfo(ij.io.FileInfo) YesNoDialog(ini.trakem2.display.YesNoDialog) ImagePlus(ij.ImagePlus) OpenDialog(ij.io.OpenDialog)

Aggregations

ImagePlus (ij.ImagePlus)363 ImageStack (ij.ImageStack)85 ImageProcessor (ij.process.ImageProcessor)74 Rectangle (java.awt.Rectangle)60 ArrayList (java.util.ArrayList)46 IOException (java.io.IOException)40 File (java.io.File)36 Roi (ij.gui.Roi)32 Point (java.awt.Point)32 ByteProcessor (ij.process.ByteProcessor)29 FormatException (loci.formats.FormatException)29 GenericDialog (ij.gui.GenericDialog)27 Calibration (ij.measure.Calibration)26 FloatProcessor (ij.process.FloatProcessor)22 Future (java.util.concurrent.Future)22 ExtendedGenericDialog (uk.ac.sussex.gdsc.core.ij.gui.ExtendedGenericDialog)22 LinkedList (java.util.LinkedList)21 ExecutorService (java.util.concurrent.ExecutorService)19 MemoryPeakResults (uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults)19 PointRoi (ij.gui.PointRoi)17