Example usage for org.opencv.core Core minMaxLoc

List of usage examples for org.opencv.core Core minMaxLoc

Introduction

In this page you can find the example usage for org.opencv.core Core minMaxLoc.

Prototype

public static MinMaxLocResult minMaxLoc(Mat src) 

Source Link

Usage

From source file:by.zuyeu.deyestracker.core.detection.task.DetectPupilsTask.java

@Override
public Point call() throws Exception {
    long startTime = System.nanoTime();

    final Mat imageHSV = new Mat(frame.size(), Core.DEPTH_MASK_8U);
    Imgproc.cvtColor(frame, imageHSV, Imgproc.COLOR_BGR2GRAY);

    Imgproc.erode(imageHSV, imageHSV, Imgproc.getStructuringElement(Imgproc.MORPH_RECT, STRUCT_ELEMENT_SIZE));
    Imgproc.dilate(imageHSV, imageHSV, Imgproc.getStructuringElement(Imgproc.MORPH_RECT, STRUCT_ELEMENT_SIZE));
    Imgproc.GaussianBlur(imageHSV, imageHSV, STRUCT_ELEMENT_SIZE, GAUS_BLUR_DELTA);

    Core.MinMaxLocResult mmG = Core.minMaxLoc(imageHSV);

    long endTime = System.nanoTime();
    LOG.debug("pupil detected = {}", mmG.minLoc);
    LOG.debug("detection time: {} ms", (float) (endTime - startTime) / 1000000);
    return mmG.minLoc;
}

From source file:ch.hslu.pren.t37.camera.BildAuswertungKorb.java

public int bildAuswerten() {

    //Bild in dem gesucht werden soll
    String inFile = "../camera.jpg";
    //das Bild dass im infile gesucht wird
    String templateFile = "../Bilder/korb.jpg";
    //Lsung wird in diesem Bild prsentiert
    String outFile = "../LoesungsBild.jpg";
    //berprfungswert wird gesetzt
    int match_method = Imgproc.TM_CCOEFF_NORMED;

    //das original Bild und das zu suchende werden geladen
    Mat img = Highgui.imread(inFile, Highgui.CV_LOAD_IMAGE_COLOR);
    Mat templ = Highgui.imread(templateFile, Highgui.CV_LOAD_IMAGE_COLOR);

    // Lsungsmatrix generieren
    int result_cols = img.cols() - templ.cols() + 1;
    int result_rows = img.rows() - templ.rows() + 1;
    Mat result = new Mat(result_rows, result_cols, CvType.CV_32FC1);

    // Suchen und normalisieren
    Imgproc.matchTemplate(img, templ, result, match_method);
    Core.normalize(result, result, 0, 1, Core.NORM_MINMAX, -1, new Mat());

    // Mit MinMax Logik wird der beste "Match" gesucht
    Core.MinMaxLocResult mmr = Core.minMaxLoc(result);

    Point matchLoc;//  ww  w .  ja  va 2 s .  c  o m
    if (match_method == Imgproc.TM_SQDIFF || match_method == Imgproc.TM_SQDIFF_NORMED) {
        matchLoc = mmr.minLoc;
    } else {
        matchLoc = mmr.maxLoc;
    }

    // Darstellen
    Core.rectangle(img, matchLoc, new Point(matchLoc.x + templ.cols(), matchLoc.y + templ.rows()),
            new Scalar(0, 255, 0), 10);

    // Alle 4 Eckpunkte speichern
    Point topLeft = new Point(matchLoc.x, matchLoc.y);
    Point topRight = new Point(matchLoc.x + templ.cols(), matchLoc.y);
    Point downLeft = new Point(matchLoc.x, matchLoc.y + templ.rows());
    Point downRight = new Point(matchLoc.x + templ.cols(), matchLoc.y + templ.rows());

    // Lsungsbild speichern
    Highgui.imwrite(outFile, img);

    //Mittelpunkt berechnen
    double mittePicture;
    double mitteKorb;
    double differnez;

    Mat sol = Highgui.imread(outFile, Highgui.CV_LOAD_IMAGE_COLOR);

    mittePicture = sol.width() / 2;
    mitteKorb = (topRight.x - topLeft.x) / 2;
    mitteKorb = topLeft.x + mitteKorb;
    differnez = mitteKorb - mittePicture;

    logger.log(PrenLogger.LogLevel.DEBUG, "Mitte Korb: " + mitteKorb);
    logger.log(PrenLogger.LogLevel.DEBUG, "Mitte Bild: " + mittePicture);
    logger.log(PrenLogger.LogLevel.DEBUG,
            "Differenz: " + differnez + "\nWenn Differnez negativ, nach rechts drehen");

    return (int) differnez;
}

From source file:ch.zhaw.facerecognitionlibrary.PreProcessor.PreProcessor.java

License:Open Source License

public void normalize01(Mat norm) {
    Core.normalize(norm, norm, 0.0, 1.0, Core.NORM_MINMAX, CvType.CV_64FC1);
    Core.MinMaxLocResult minmax = Core.minMaxLoc(norm);
    Scalar min = new Scalar(minmax.minVal);
    Core.subtract(norm, min, norm);/*from w w  w.  j  a v a 2s .c  o m*/
    minmax = Core.minMaxLoc(norm);
    Scalar max = new Scalar(minmax.maxVal);
    Core.divide(norm, max, norm);
}

From source file:com.joravasal.keyface.EigenFacesActivity.java

License:Open Source License

/**
 * Converts a matrix with any values into a matrix with correct values (between 0 and 255, both included) to be shown as an image.
 * @param mat: The matrix to convert//from   w w  w.  j  a v a 2  s  . c o m
 * @return A matrix that can be used as an image
 */
private Mat toGrayscale(Mat mat) {
    Mat res = new Mat(mat.rows(), mat.cols(), CvType.CV_8UC1);
    double min, max;
    MinMaxLocResult minmax = Core.minMaxLoc(mat);
    min = minmax.minVal;
    max = minmax.maxVal;
    for (int row = 0; row < mat.rows(); row++) {
        for (int col = 0; col < mat.cols(); col++) {
            res.put(row, col, 255 * ((mat.get(row, col)[0] - min) / (max - min)));
        }
    }
    return res;
}

From source file:com.raulh82vlc.face_detection_sample.opencv.domain.EyesDetectionInteractorImpl.java

License:Apache License

/**
 * Matches concrete point of the eye by using template with TM_SQDIFF_NORMED
 *///from w  w w  .  j  a  v a  2  s . c o m
private static void matchEye(Rect area, Mat builtTemplate, Mat matrixGray, Mat matrixRGBA) {
    Point matchLoc;
    try {
        // when there is not builtTemplate we skip it
        if (builtTemplate.cols() == 0 || builtTemplate.rows() == 0) {
            return;
        }
        Mat submatGray = matrixGray.submat(area);
        int cols = submatGray.cols() - builtTemplate.cols() + 1;
        int rows = submatGray.rows() - builtTemplate.rows() + 1;
        Mat outputTemplateMat = new Mat(cols, rows, CvType.CV_8U);

        Imgproc.matchTemplate(submatGray, builtTemplate, outputTemplateMat, Imgproc.TM_SQDIFF_NORMED);
        Core.MinMaxLocResult minMaxLocResult = Core.minMaxLoc(outputTemplateMat);
        // when is difference in matching methods, the best match is max / min value
        matchLoc = minMaxLocResult.minLoc;
        Point matchLocTx = new Point(matchLoc.x + area.x, matchLoc.y + area.y);
        Point matchLocTy = new Point(matchLoc.x + builtTemplate.cols() + area.x,
                matchLoc.y + builtTemplate.rows() + area.y);

        FaceDrawerOpenCV.drawMatchedEye(matchLocTx, matchLocTy, matrixRGBA);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.raulh82vlc.face_detection_sample.opencv.domain.EyesDetectionInteractorImpl.java

License:Apache License

/**
 * <p>Build a template from a specific eye area previously substracted
 * uses detectMultiScale for this area, then uses minMaxLoc method to
 * detect iris from the detected eye</p>
 *
 * @param area Preformatted Area/*from w  w  w .ja v a2 s.c om*/
 * @param size minimum iris size
 * @param grayMat image in gray
 * @param rgbaMat image in color
 * @param detectorEye Haar Cascade classifier
 * @return built template
 */
@NonNull
private static Mat buildTemplate(Rect area, final int size, @NonNull Mat grayMat, @NonNull Mat rgbaMat,
        CascadeClassifier detectorEye) {
    Mat template = new Mat();
    Mat graySubMatEye = grayMat.submat(area);
    MatOfRect eyes = new MatOfRect();
    Rect eyeTemplate;
    detectorEye.detectMultiScale(graySubMatEye, eyes, 1.15, 2,
            Objdetect.CASCADE_FIND_BIGGEST_OBJECT | Objdetect.CASCADE_SCALE_IMAGE,
            new Size(EYE_MIN_SIZE, EYE_MIN_SIZE), new Size());

    Rect[] eyesArray = eyes.toArray();
    if (eyesArray.length > 0) {
        Rect e = eyesArray[0];
        e.x = area.x + e.x;
        e.y = area.y + e.y;
        Rect eyeRectangle = getEyeArea((int) e.tl().x, (int) (e.tl().y + e.height * 0.4), e.width,
                (int) (e.height * 0.6));
        graySubMatEye = grayMat.submat(eyeRectangle);
        Mat rgbaMatEye = rgbaMat.submat(eyeRectangle);

        Core.MinMaxLocResult minMaxLoc = Core.minMaxLoc(graySubMatEye);

        FaceDrawerOpenCV.drawIrisCircle(rgbaMatEye, minMaxLoc);
        Point iris = new Point();
        iris.x = minMaxLoc.minLoc.x + eyeRectangle.x;
        iris.y = minMaxLoc.minLoc.y + eyeRectangle.y;
        eyeTemplate = getEyeArea((int) iris.x - size / 2, (int) iris.y - size / 2, size, size);
        FaceDrawerOpenCV.drawEyeRectangle(eyeTemplate, rgbaMat);
        template = (grayMat.submat(eyeTemplate)).clone();
    }
    return template;
}

From source file:com.seleniumtests.util.imaging.ImageDetector.java

License:Apache License

private MinMaxLocResult getBestTemplateMatching(int matchMethod, Mat sceneImageMat, Mat objectImageMat) {

    // / Create the result matrix
    int resultCols = sceneImageMat.cols() - objectImageMat.cols() + 1;
    int resultRows = sceneImageMat.rows() - objectImageMat.rows() + 1;
    Mat result = new Mat(resultRows, resultCols, CvType.CV_32FC1);

    // / Do the Matching and Normalize
    Imgproc.matchTemplate(sceneImageMat, objectImageMat, result, matchMethod);

    // / Localizing the best match with minMaxLoc        
    return Core.minMaxLoc(result);
}

From source file:com.sikulix.core.Finder.java

License:Open Source License

private FindResult doFind(Element elem, FindType findType) {
    if (!elem.isTarget()) {
        return null;
    }//  w  w w .  jav  a  2  s  . c  o m
    log.trace("doFind: start");
    Element target = elem;
    if (target.getWantedScore() < 0) {
        target.setWantedScore(0.8);
    }
    boolean success = false;
    long begin_t = 0;
    Core.MinMaxLocResult mMinMax = null;
    FindResult findResult = null;
    if (FindType.ONE.equals(findType) && !isCheckLastSeen && SX.isOption("CheckLastSeen")
            && target.getLastSeen().isValid()) {
        begin_t = new Date().getTime();
        Finder lastSeenFinder = new Finder(target.getLastSeen());
        lastSeenFinder.isCheckLastSeen = true;
        target = new Target(target, target.getLastSeen().getScore() - 0.01);
        findResult = lastSeenFinder.doFind(target, FindType.ONE);
        if (findResult.hasNext()) {
            log.trace("doFind: checkLastSeen: success %d msec", new Date().getTime() - begin_t);
            return findResult;
        } else {
            log.trace("doFind: checkLastSeen: not found %d msec", new Date().getTime() - begin_t);
        }
    }
    double rfactor = 0;
    boolean downSizeFound = false;
    double downSizeScore = 0;
    double downSizeWantedScore = 0;
    if (FindType.ONE.equals(findType) && target.getResizeFactor() > resizeMinFactor) {
        // ************************************************* search in downsized
        begin_t = new Date().getTime();
        double imgFactor = target.getResizeFactor();
        Size sb, sp;
        Mat mBase = new Mat(), mPattern = new Mat();
        result = null;
        for (double factor : resizeLevels) {
            rfactor = factor * imgFactor;
            sb = new Size(base.cols() / rfactor, base.rows() / rfactor);
            sp = new Size(target.getContent().cols() / rfactor, target.getContent().rows() / rfactor);
            Imgproc.resize(base, mBase, sb, 0, 0, Imgproc.INTER_AREA);
            Imgproc.resize(target.getContent(), mPattern, sp, 0, 0, Imgproc.INTER_AREA);
            result = doFindMatch(target, mBase, mPattern);
            mMinMax = Core.minMaxLoc(result);
            downSizeWantedScore = ((int) ((target.getWantedScore() - downSimDiff) * 100)) / 100.0;
            downSizeScore = mMinMax.maxVal;
            if (downSizeScore > downSizeWantedScore) {
                downSizeFound = true;
                break;
            }
        }
        log.trace("doFind: down: %%%.2f %d msec", 100 * mMinMax.maxVal, new Date().getTime() - begin_t);
    }
    if (FindType.ONE.equals(findType) && downSizeFound) {
        // ************************************* check after downsized success
        if (base.size().equals(target.getContent().size())) {
            // trust downsized result, if images have same size
            return new FindResult(result, target);
        } else {
            int maxLocX = (int) (mMinMax.maxLoc.x * rfactor);
            int maxLocY = (int) (mMinMax.maxLoc.y * rfactor);
            begin_t = new Date().getTime();
            int margin = ((int) target.getResizeFactor()) + 1;
            Rect rectSub = new Rect(Math.max(0, maxLocX - margin), Math.max(0, maxLocY - margin),
                    Math.min(target.w + 2 * margin, base.width()),
                    Math.min(target.h + 2 * margin, base.height()));
            result = doFindMatch(target, base.submat(rectSub), null);
            mMinMax = Core.minMaxLoc(result);
            if (mMinMax.maxVal > target.getWantedScore()) {
                findResult = new FindResult(result, target, new int[] { rectSub.x, rectSub.y });
            }
            if (SX.isNotNull(findResult)) {
                log.trace("doFind: after down: %%%.2f(?%%%.2f) %d msec", mMinMax.maxVal * 100,
                        target.getWantedScore() * 100, new Date().getTime() - begin_t);
            }
        }
    }
    // ************************************** search in original
    if (((int) (100 * downSizeScore)) == 0) {
        begin_t = new Date().getTime();
        result = doFindMatch(target, base, null);
        mMinMax = Core.minMaxLoc(result);
        if (!isCheckLastSeen) {
            log.trace("doFind: search in original: %d msec", new Date().getTime() - begin_t);
        }
        if (mMinMax.maxVal > target.getWantedScore()) {
            findResult = new FindResult(result, target);
        }
    }
    log.trace("doFind: end");
    return findResult;
}

From source file:com.wallerlab.processing.tasks.ComputeRefocusTask.java

License:BSD License

private Bitmap[] computeFocus(float z) {
    int width = mDataset.WIDTH - 2 * mDataset.XCROP;
    int height = mDataset.HEIGHT - 2 * mDataset.YCROP;

    Mat result = new Mat(height, width, CvType.CV_32FC4);
    Mat result8 = new Mat(height, width, CvType.CV_8UC4);

    Mat dpc_result_tb = new Mat(height, width, CvType.CV_32FC4);
    Mat dpc_result_tb8 = new Mat(height, width, CvType.CV_8UC4);

    Mat dpc_result_lr = new Mat(height, width, CvType.CV_32FC4);
    Mat dpc_result_lr8 = new Mat(height, width, CvType.CV_8UC4);

    Mat img;/*www  . ja  v  a 2 s .c o m*/
    Mat img32 = new Mat(height, width, CvType.CV_32FC4);
    Mat shifted;

    for (int idx = 0; idx < mDataset.fileCount; idx++) {
        img = ImageUtils.toMat(BitmapFactory.decodeByteArray(fileByteList[idx], 0, fileByteList[idx].length));
        img = img.submat(mDataset.YCROP, mDataset.HEIGHT - mDataset.YCROP, mDataset.XCROP,
                mDataset.WIDTH - mDataset.XCROP);
        img.convertTo(img32, result.type());

        // Grab actual hole number from filename
        String fName = mDataset.fileList[idx].toString();
        String hNum = fName.substring(fName.indexOf("_scanning_") + 10, fName.indexOf(".jpeg"));
        int holeNum = Integer.parseInt(hNum);
        //Log.d(TAG,String.format("BF Scan Header is: %s", hNum));

        // Calculate these based on array coordinates
        int xShift = (int) Math.round(z * tanh_lit[holeNum]);
        int yShift = (int) Math.round(z * tanv_lit[holeNum]);

        shifted = ImageUtils.circularShift(img32, yShift, xShift);

        if (mDataset.leftList.contains(holeNum)) //add LHS
        {
            Core.add(dpc_result_lr, shifted, dpc_result_lr);
        } else //subtract RHS
        {
            Core.subtract(dpc_result_lr, shifted, dpc_result_lr);
        }

        if (mDataset.topList.contains(holeNum)) //add Top
        {
            Core.add(dpc_result_tb, shifted, dpc_result_tb);
        } else //subtract bottom
        {
            Core.subtract(dpc_result_tb, shifted, dpc_result_tb);
        }

        Core.add(result, shifted, result);

        float progress = ((idx + 1) / (float) mDataset.fileCount);
        onProgressUpdate((int) (progress * 100), -1);
        Log.d(TAG, String.format("progress: %f", progress));
    }

    Core.MinMaxLocResult minMaxLocResult1 = Core.minMaxLoc(result.reshape(1));
    result.convertTo(result8, CvType.CV_8UC4, 255 / minMaxLocResult1.maxVal);

    Core.MinMaxLocResult minMaxLocResult2 = Core.minMaxLoc(dpc_result_lr.reshape(1));
    dpc_result_lr.convertTo(dpc_result_lr8, CvType.CV_8UC4,
            255 / (minMaxLocResult2.maxVal - minMaxLocResult2.minVal),
            -minMaxLocResult2.minVal * 255.0 / (minMaxLocResult2.maxVal - minMaxLocResult2.minVal));

    Core.MinMaxLocResult minMaxLocResult3 = Core.minMaxLoc(dpc_result_tb.reshape(1));
    dpc_result_tb.convertTo(dpc_result_tb8, CvType.CV_8UC4,
            255 / (minMaxLocResult3.maxVal - minMaxLocResult3.minVal),
            -minMaxLocResult3.minVal * 255.0 / (minMaxLocResult3.maxVal - minMaxLocResult3.minVal));

    /*
    Log.d(TAG,String.format("result_min: %f, max: %f",minMaxLocResult1.minVal,minMaxLocResult1.maxVal));
    Log.d(TAG,String.format("lr_min: %f, max: %f",minMaxLocResult2.minVal,minMaxLocResult2.maxVal));
    Log.d(TAG,String.format("tb_min: %f, max: %f",minMaxLocResult3.minVal,minMaxLocResult3.maxVal));
    */

    // remove transparency in DPC images
    Scalar alphaMask = new Scalar(new double[] { 1.0, 1.0, 1.0, 255.0 });

    Core.multiply(dpc_result_lr8, alphaMask, dpc_result_lr8);
    Core.multiply(dpc_result_tb8, alphaMask, dpc_result_tb8);

    if (!mDataset.USE_COLOR_DPC) {
        Imgproc.cvtColor(dpc_result_lr8, dpc_result_lr8, Imgproc.COLOR_BGR2GRAY);
        Imgproc.cvtColor(dpc_result_tb8, dpc_result_tb8, Imgproc.COLOR_BGR2GRAY);
    }

    /*
    // Cut off edges in DPC images
    Point centerPt = new Point();
    centerPt.x = Math.round((float)width/2.0);
    centerPt.y = Math.round((float)height/2.0);
    Mat circleMat = new Mat(dpc_result_lr8.size(), dpc_result_lr8.type());
    Scalar color = new Scalar(255);
    Core.circle(circleMat, centerPt, 200, color);
    //Core.bitwise_and(circleMat, dpc_result_lr8, dpc_result_lr8);
    //Core.bitwise_and(circleMat, dpc_result_tb8, dpc_result_tb8);
    * 
    * 
    */

    Bitmap[] outputBitmaps = new Bitmap[3];
    outputBitmaps[0] = ImageUtils.toBitmap(result8);
    outputBitmaps[1] = ImageUtils.toBitmap(dpc_result_lr8);
    outputBitmaps[2] = ImageUtils.toBitmap(dpc_result_tb8);

    return outputBitmaps;
}

From source file:cx.uni.jk.mms.iaip.filter.GreyAutoContrastBrightness.java

License:Open Source License

@Override
public Mat convert(Mat mat) {
    /** find contrast and brightness to fit into 8 bit */
    MinMaxLocResult mmlr = Core.minMaxLoc(mat);
    double min = mmlr.minVal; // Math.min(mmlr.minVal, 0);
    double max = mmlr.maxVal; // Math.max(mmlr.maxVal, 255);
    double alpha = 256.0d / (max - min);
    double beta = -min * alpha;

    /** conversion to 8 bit Mat */
    Mat byteMat = new MatOfByte();
    mat.convertTo(byteMat, CvType.CV_8U, alpha, beta);

    return byteMat;
}