    001package visrec.ri.ml.detection;
    002
    003import java.awt.image.BufferedImage;
    004import java.util.HashMap;
    005import java.util.List;
    006import java.util.Map;
    007import javax.visrec.AbstractImageClassifier;
    008import javax.visrec.util.BoundingBox;
    009
    010/**
    011 * A simple object detector
    012 *
    013 * @author Zoran Sevarac
    014 */
    015public class SimpleObjectDetector extends AbstractObjectDetector<BufferedImage> {
    016
    017    private double threshold = 0.5;
    018
    019    /**
    020     * Creates an instance
    021     * @param classifier A {@link AbstractImageClassifier} which may not be null
    022     */
    023    public SimpleObjectDetector(AbstractImageClassifier<BufferedImage, Boolean> classifier) {
    024        super(classifier);
    025    }
    026
    027    /**
    028     * Scan image using brute force sliding window and return positions where
    029     * classifier returns score greater then threshold.
    030     *
    031     * get width and height of the image and scan image with classifier - apply
    032     * classifier to each position This is trivial implementation and should be
    033     * replaced with something better
    034     *
    035     * @param image {@code BufferedImage} to scan
    036     * @return A {@code Map} of {@link BoundingBox} which contain
    037     * the positions of the detected object.
    038     */
    039    @Override
    040    public Map<String, List<BoundingBox>> detectObject(BufferedImage image) {
    041        Map<String, List<BoundingBox>> results = new HashMap<>();
    042
    043        int boxWidth = 64, boxHeight = 64;
    044
    045        for (int y = 0; y < image.getHeight() - boxHeight; y++) {
    046            for (int x = 0; x < image.getWidth() - boxWidth; x++) {
    047
    048                Map<String, Float> results2 = getImageClassifier().classify(image.getSubimage(x, y, boxWidth, boxHeight));
    049                for (Map.Entry<String, Float> keyValPair : results2.entrySet()) {
    050                    if (keyValPair.getValue() > threshold) {
    051                        BoundingBox bbox = new BoundingBox(keyValPair.getKey(), keyValPair.getValue(), x, y, boxWidth, boxHeight);
    052                        // results.add(bbox);
    053                    }
    054                }
    055            }
    056        }
    057
    058        return results;
    059    }
    060
    061    /**
    062     * Get the threshold
    063     * @return theshold as {@code double}
    064     */
    065    public double getThreshold() {
    066        return threshold;
    067    }
    068
    069    /**
    070     * Set the threshold
    071     * @param threshold as {@code double}
    072     */
    073    public void setThreshold(double threshold) {
    074        this.threshold = threshold;
    075    }
    076}