Search in sources :

Example 16 with Filter

use of ini.trakem2.utils.Filter in project modules.playframework.org by playframework.

the class Modules method details.

public static Result details(String moduleKey) {
    Result result;
    final Module module = Module.findByModuleKey(moduleKey);
    if (module == null) {
        result = notFound("Module not found: " + moduleKey);
    } else {
        List<ModuleVersion> moduleVersions = ModuleVersion.findByModule(module);
        User user = currentUser();
        Rate rate = null;
        Vote vote = null;
        if (user != null) {
            rate = CollectionUtils.filterFirst(user.rates, new Filter<Rate>() {

                public boolean isAcceptable(Rate rate) {
                    return rate.playModule.id.equals(module.id);
                }
            });
            vote = CollectionUtils.filterFirst(user.votes, new Filter<Vote>() {

                public boolean isAcceptable(Vote vote) {
                    return vote.playModule.id.equals(module.id);
                }
            });
        }
        Set<PlayVersion.MajorVersion> majorVersions = new HashSet<PlayVersion.MajorVersion>();
        for (ModuleVersion moduleVersion : moduleVersions) {
            majorVersions.addAll(moduleVersion.getMajorVersions());
        }
        Ebean.refresh(module.rating);
        result = ok(moduleDetails.render(user, module, moduleVersions, majorVersions, rate, vote));
    }
    return result;
}
Also used : Vote(models.Vote) CurrentUser.currentUser(actions.CurrentUser.currentUser) CurrentUser(actions.CurrentUser) User(models.User) ModuleVersion(models.ModuleVersion) Filter(utils.Filter) Rate(models.Rate) PlayVersion(models.PlayVersion) Module(models.Module) Result(play.mvc.Result) HashSet(java.util.HashSet)

Example 17 with Filter

use of ini.trakem2.utils.Filter in project modules.playframework.org by playframework.

the class Modules method rate.

// If a user has already rated, then change the rate, don't add a new one
@RoleHolderPresent
public static Result rate(String moduleKey) {
    Result result;
    Form<RatingForm> form = form(RatingForm.class).bindFromRequest();
    if (form.hasErrors()) {
        result = badRequest(form.errorsAsJson());
    } else {
        RatingForm ratingForm = form.get();
        final Module module = Module.findById(ratingForm.id);
        if (module == null) {
            result = badRequest("Module does not exist");
        } else {
            User user = currentUser();
            Rate rate = null;
            if (user != null) {
                // user shouldn't be null because of @RoleHolderPresent
                rate = CollectionUtils.filterFirst(user.rates, new Filter<Rate>() {

                    @Override
                    public boolean isAcceptable(Rate rate) {
                        return rate.playModule.id.equals(module.id);
                    }
                });
                if (rate != null) {
                    module.rating.subtract(rate);
                } else {
                    rate = new Rate();
                    rate.playModule = module;
                    user.rates.add(rate);
                }
                rate.rating = ratingForm.rating;
                module.rating.add(rate);
                module.rating.calculateAverage();
                module.save();
                user.save();
            }
            RatingResponseForm responseForm = new RatingResponseForm();
            responseForm.totalRatings = module.rating.totalRatings();
            responseForm.averageRating = module.rating.averageRating;
            result = ok(Json.toJson(responseForm));
        }
    }
    return result;
}
Also used : RatingResponseForm(forms.modules.RatingResponseForm) CurrentUser.currentUser(actions.CurrentUser.currentUser) CurrentUser(actions.CurrentUser) User(models.User) Filter(utils.Filter) Rate(models.Rate) Module(models.Module) RatingForm(forms.modules.RatingForm) Result(play.mvc.Result) RoleHolderPresent(be.objectify.deadbolt.actions.RoleHolderPresent)

Example 18 with Filter

use of ini.trakem2.utils.Filter 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);
    }
}
Also used : ImageProcessor(ij.process.ImageProcessor) FileInfo(ij.io.FileInfo) IFilter(ini.trakem2.imaging.filters.IFilter) File(java.io.File) ImagePlus(ij.ImagePlus) IOException(java.io.IOException) FormatException(loci.formats.FormatException)

Example 19 with Filter

use of ini.trakem2.utils.Filter in project TrakEM2 by trakem2.

the class Loader method scaleImage.

public static ImageProcessor scaleImage(final ImagePlus imp, final int level, final boolean quality) {
    if (level <= 0)
        return imp.getProcessor();
    // else, make a properly scaled image:
    // - gaussian blurred for best quality when resizing with nearest neighbor
    // - direct nearest neighbor otherwise
    ImageProcessor ip = imp.getProcessor();
    final int w = ip.getWidth();
    final int h = ip.getHeight();
    final double mag = 1 / Math.pow(2, level);
    // TODO releseToFit !
    if (quality) {
        // apply proper gaussian filter
        // sigma = sqrt(level^2 - 0.5^2)
        final double sigma = Math.sqrt(Math.pow(2, level) - 0.25);
        ip = new FloatProcessorT2(w, h, ImageFilter.computeGaussianFastMirror(new FloatArray2D((float[]) ip.convertToFloat().getPixels(), w, h), (float) sigma).data, ip.getDefaultColorModel(), ip.getMin(), ip.getMax());
        // better while float
        ip = ip.resize((int) (w * mag), (int) (h * mag));
        return Utils.convertTo(ip, imp.getType(), false);
    } else {
        return ip.resize((int) (w * mag), (int) (h * mag));
    }
}
Also used : ImageProcessor(ij.process.ImageProcessor) FloatArray2D(mpi.fruitfly.math.datastructures.FloatArray2D) FloatProcessorT2(ini.trakem2.imaging.FloatProcessorT2)

Example 20 with Filter

use of ini.trakem2.utils.Filter 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;
}
Also used : ImageFileFilter(ini.trakem2.io.ImageFileFilter) IOException(java.io.IOException) FormatException(loci.formats.FormatException) GenericDialog(ij.gui.GenericDialog) Montage(ini.trakem2.utils.Montage) Worker(ini.trakem2.utils.Worker) Component(java.awt.Component) File(java.io.File)

Aggregations

Layer (ini.trakem2.display.Layer)18 ArrayList (java.util.ArrayList)15 Patch (ini.trakem2.display.Patch)14 Point (mpicbg.models.Point)13 Rectangle (java.awt.Rectangle)11 HashSet (java.util.HashSet)10 NotEnoughDataPointsException (mpicbg.models.NotEnoughDataPointsException)9 ImagePlus (ij.ImagePlus)8 AffineTransform (java.awt.geom.AffineTransform)7 Future (java.util.concurrent.Future)7 PointMatch (mpicbg.models.PointMatch)7 ExecutorService (java.util.concurrent.ExecutorService)6 AffineModel2D (mpicbg.models.AffineModel2D)6 SimilarityModel2D (mpicbg.models.SimilarityModel2D)6 GenericDialog (ij.gui.GenericDialog)5 Area (java.awt.geom.Area)5 ImageProcessor (ij.process.ImageProcessor)4 Collection (java.util.Collection)4 HashMap (java.util.HashMap)4 Project (ini.trakem2.Project)3