Example usage for org.opencv.core Mat Mat

List of usage examples for org.opencv.core Mat Mat

Introduction

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

Prototype

public Mat() 

Source Link

Usage

From source file:de.hftl_projekt.ict.MainActivity.java

/**
 * method to reduce the color (quantize) the given matrix (image)
 * @param image input matrix/*from   w ww. j  a va2s  .com*/
 * @return modified input matrix
 */
public Mat reduceColors(Mat image) {
    if (channels.size() == 0) {
        for (int i = 0; i < image.channels(); i++) {
            Mat channel = new Mat(); // fill array with a matrix for each channel
            channels.add(channel);
        }

    }
    int i = 0;
    // process each channel individually
    for (Mat c : channels) {
        Core.extractChannel(image, c, i);
        // binary quantization (set threshold so each color (R, G, B) can have the value (0 or 255) )
        // and using the Otsu algorithm to optimize the quantization
        Imgproc.threshold(c, c, 0, 255, Imgproc.THRESH_BINARY_INV + Imgproc.THRESH_OTSU);
        i++;
    }
    Core.merge(channels, image); // put the channel back together
    return image;
}

From source file:de.hhn.android.licenseplatedecoder.decoder.CountryExtractor.java

/**
 * Constructor//  w  w w.  j  a  v  a 2 s. c  o m
 * @param nativeAddress input image pointer address
 * @param withoutStripInputAddr image pointer address in order to store the cropped image without the blue strip
 */
public CountryExtractor(long nativeAddress, long withoutStripInputAddr) {
    this.nativeInputAddr = nativeAddress;
    this.withoutStripInputAddr = withoutStripInputAddr;
    this.withoutBlueStrip = new Mat();

    /** OCR ENGINE INIT */
    this.baseApi = new TessBaseAPI();
    this.baseApi.setDebug(true);
    this.baseApi.init("/sdcard/", "blueBand"); // myDir + "/tessdata/eng.traineddata" must be present
    this.baseApi.setVariable("tessedit_char_whitelist", "ABCDFGHIKLOPRSTZ");
    this.baseApi.setPageSegMode(TessBaseAPI.PageSegMode.PSM_SINGLE_CHAR);

    ArrayList<Mat> countryCode = getCharacters();

    StringBuffer strb = new StringBuffer();
    for (Mat elem : countryCode) {

        Bitmap pass = Bitmap.createBitmap(elem.cols(), elem.rows(), Bitmap.Config.ARGB_8888);
        Utils.matToBitmap(elem, pass, true);

        baseApi.setImage(pass);
        String recognizedText = baseApi.getUTF8Text();
        strb.append(recognizedText);
        baseApi.clear();
        pass.recycle();
    }
    this.result = strb.toString();
    baseApi.end();
    baseApi = null;
    countryCode = null;
}

From source file:de.hhn.android.licenseplatedecoder.decoder.DecodingEngine.java

/**
 * Get the country code using CountryExtractor
 * @return the country code/*from  ww w . j  av  a  2s . c  o  m*/
 */
public String getCountryCode() {
    Mat nativeOpencv = new Mat();
    org.opencv.android.Utils.bitmapToMat(inputImg, nativeOpencv);
    Mat res = new Mat(nativeOpencv.rows(), nativeOpencv.cols(), nativeOpencv.type());
    org.opencv.imgproc.Imgproc.cvtColor(nativeOpencv, res, Imgproc.COLOR_RGBA2BGR);
    nativeOpencv = null;
    Mat withoutStrip = new Mat();

    CountryExtractor ce = new CountryExtractor(res.nativeObj, withoutStrip.nativeObj);
    return ce.getResult();
}

From source file:de.hhn.android.licenseplatedecoder.decoder.DecodingEngine.java

/**
 * Get the license plate using LPSegmenter
 * @return the license plate//  www  .  j  a  v  a2 s .c  o m
 */
public String getLicensePlate() {
    Mat nativeOpencv = new Mat();
    org.opencv.android.Utils.bitmapToMat(inputImg, nativeOpencv);
    Mat res = new Mat(nativeOpencv.rows(), nativeOpencv.cols(), nativeOpencv.type());
    org.opencv.imgproc.Imgproc.cvtColor(nativeOpencv, res, Imgproc.COLOR_RGBA2BGR);
    nativeOpencv = null;

    LPSegmenter lp = new LPSegmenter(res.nativeObj, this.countryCodeNonAutomatic);
    return lp.getResult();
}

From source file:de.hu_berlin.informatik.spws2014.mapever.entzerrung.CornerDetector.java

License:Open Source License

/**
 * Guesses the most likly corners of a distorted map within an image.
 * Expects OpenCV to be initialized.//from   ww w.j a va  2  s. c  o m
 * The results are already pretty good but could propably be improved
 * via tweaking the parameters or adding some additional line filtering
 * criteria(like them being kind of parallel for instance...)
 * 
 * @param gray_img A grayscale image in OpenCVs Mat format.
 * @return An array of propable corner points in the following form: {x0,y0,x1,y1,x2,y2,x3,y3} or null on error.
 **/
public static Point[] guess_corners(Mat gray_img) {
    Mat lines = new Mat();
    Imgproc.Canny(gray_img, gray_img, THRESHOLD0, THRESHOLD1, APERTURE_SIZE, false);
    Imgproc.HoughLinesP(gray_img, lines, RHO, THETA, HOUGH_THRESHOLD,
            Math.min(gray_img.cols(), gray_img.rows()) / MIN_LINE_LENGTH_FRACTION, MAX_LINE_GAP);

    double[][] edge_lines = filter_lines(lines, gray_img.size());

    Point[] ret_val = new Point[4];
    ret_val[0] = find_intercept_point(edge_lines[0], edge_lines[2]);
    ret_val[1] = find_intercept_point(edge_lines[0], edge_lines[3]);
    ret_val[2] = find_intercept_point(edge_lines[1], edge_lines[3]);
    ret_val[3] = find_intercept_point(edge_lines[1], edge_lines[2]);

    // do sanity checks and return null on invalid coordinates
    for (int i = 0; i < 4; i++) {
        // check if coordinates are outside image boundaries
        if (ret_val[i].x < 0 || ret_val[i].y < 0 || ret_val[i].x > gray_img.width()
                || ret_val[i].y > gray_img.height()) {
            return null;
        }

        // check if point equal to other point
        for (int j = i + 1; j < 4; j++) {
            if (ret_val[j].x == ret_val[i].x && ret_val[j].y == ret_val[i].y) {
                return null;
            }
        }
    }

    return ret_val;
}

From source file:de.hu_berlin.informatik.spws2014.mapever.entzerrung.EntzerrungsView.java

License:Open Source License

/**
 * Use corner detection algorithm to find and set corners automatically.
 *///from  w w  w.j  a v a 2 s. c o  m
public void calcCornersWithDetector() {
    // Bitmap berechnen, die fr CD-Algorithmus runterskaliert wurde
    Bitmap bmp32 = getCDScaledBitmap();

    if (bmp32 == null || getImageWidth() <= 0) {
        Log.e("EntzerrungsView/calcCornersWithDetector",
                bmp32 == null ? "getCDScaledBitmap() returned null!" : "getImageWidth() is nonpositive!");
        calcCornerDefaults();
        return;
    }

    float sampleSize = getImageWidth() / bmp32.getWidth();

    org.opencv.core.Point[] corner_points;

    try {
        Mat imgMat = new Mat();
        Utils.bitmapToMat(bmp32, imgMat);
        Mat greyMat = new Mat();
        Imgproc.cvtColor(imgMat, greyMat, Imgproc.COLOR_RGB2GRAY);

        corner_points = CornerDetector.guess_corners(greyMat);
    } catch (CvException e) {
        Log.w("EntzerrungsView/calcCornersWithDetector", "Corner detection failed with CvException");
        e.printStackTrace();

        // it seems that the image type is not supported by the corner detection algorithm (GIF?)
        // it won't be deskewable either, so deactivate that feature
        showCorners(false);
        imageTypeSupportsDeskew = false;

        calcCornerDefaults();
        return;
    } catch (UnsatisfiedLinkError e) {
        Log.w("EntzerrungsView/calcCornersWithDetector", "OpenCV not available");
        openCVLoadError = true;
        calcCornerDefaults();
        return;
    }

    // Im Fehlerfall Standardecken verwenden
    if (corner_points == null) {
        Log.w("EntzerrungsView/calcCornersWithDetector", "Corner detection returned null");
        calcCornerDefaults();
        return;
    }

    // Koordinaten auf ursprngliche Bildgre hochrechnen
    for (int i = 0; i < corner_points.length; i++) {
        corner_points[i].x *= sampleSize;
        corner_points[i].y *= sampleSize;
    }

    Log.d("Corner points", "0: " + corner_points[0] + " 1: " + corner_points[1] + " 2: " + corner_points[2]
            + " 3: " + corner_points[3]);

    // Algorithmusergebnis als Eckpunkte verwenden
    corners[0].setPosition(corner_points[0]);
    corners[1].setPosition(corner_points[1]);
    corners[2].setPosition(corner_points[2]);
    corners[3].setPosition(corner_points[3]);

    // Sortieren (obwohl sie eigentlich sortiert sein sollten...?)
    sortCorners();

    punkte_gesetzt = true;
}

From source file:de.vion.eyetracking.cameracalib.calibration.opencv.CameraCalibrator.java

public void calibrate() {
    ArrayList<Mat> rvecs = new ArrayList<Mat>();
    ArrayList<Mat> tvecs = new ArrayList<Mat>();
    Mat reprojectionErrors = new Mat();
    ArrayList<Mat> objectPoints = new ArrayList<Mat>();
    objectPoints.add(Mat.zeros(this.mCornersSize, 1, CvType.CV_32FC3));
    calcBoardCornerPositions(objectPoints.get(0));
    for (int i = 1; i < this.mCornersBuffer.size(); i++) {
        objectPoints.add(objectPoints.get(0));
    }//from  ww  w  .j  a v  a2  s . com

    Calib3d.calibrateCamera(objectPoints, this.mCornersBuffer, this.mImageSize, this.mCameraMatrix,
            this.mDistortionCoefficients, rvecs, tvecs, this.mFlags);

    this.mIsCalibrated = Core.checkRange(this.mCameraMatrix) && Core.checkRange(this.mDistortionCoefficients);

    this.mRms = computeReprojectionErrors(objectPoints, rvecs, tvecs, reprojectionErrors);
}

From source file:detectiontest.ParticleDetector.java

/**
 * Particle detection algorithm./* w w w  . ja va 2  s.  c  o m*/
 * 
 * @param image an image where we want to detect
 * @return list of detected particles
 */
public static List<Particle> detect(Mat image) {

    // blur the image to denoise
    Imgproc.blur(image, image, new Size(3, 3));

    // thresholds the image
    Mat thresholded = new Mat();
    Imgproc.threshold(image, thresholded, THRESHOLD, MAX, Imgproc.THRESH_TOZERO_INV);

    // detect contours
    List<MatOfPoint> contours = new ArrayList<>();
    Imgproc.findContours(thresholded, contours, new Mat(), Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE,
            ORIGIN);

    // create particle from each contour
    List<Particle> particles = new ArrayList<>();
    for (MatOfPoint contour : contours) {
        particles.add(new Particle(contour));
    }

    return particles;
}

From source file:detectors.CCdetection.java

/**
 * Method to scan image with x classifier
 *//*from   ww  w. j av a2 s  . c  o m*/
public void scanImage(String path) {
    CascadeClassifier faceCC = new CascadeClassifier();
    faceCC.load("res/haarcascade_frontalface_alt.xml");

    //Matrix to hold image to be scanned
    Mat image = new Mat();
    image = Highgui.imread(path, IMREAD_COLOR);

    Mat rgb = new Mat();
    Mat gray = new Mat();
    image.copyTo(rgb);
    image.copyTo(gray);

    //Create integral image from the grayscale version of frame 
    Imgproc.cvtColor(rgb, gray, Imgproc.COLOR_BGR2GRAY);
    Imgproc.equalizeHist(gray, gray);

    //MatOfRect detection window initialized
    MatOfRect detects = new MatOfRect();
    faceCC.detectMultiScale(gray, detects);

    //Print out number of detected rect objects detected
    if (detects.toArray().length != 0) {
        System.out.printf("Detected %s\n", detects.toArray().length);
    }
}

From source file:detectors.CCdetection.java

/**
 * Method to scan video with x classifier
 * NOT COMPLETE/* w  w w  .j a  v a2  s.c om*/
 */
public void scanVideo() {
    //Initialize video capture object to 0(default camera device)
    VideoCapture vc = new VideoCapture(0);

    //String path = "";

    //Initialize and load in classifier
    CascadeClassifier faceCC = new CascadeClassifier();
    faceCC.load("res/haarcascade_frontalface_default.xml");

    //Matrix(opencv core image object) to hold the image frame coming from the capture stream
    Mat image = new Mat();

    boolean isFound = false;
    while (!isFound) {
        //VideoCapture read combines grab and retrieve methods to decode and return the frame
        vc.read(image);
        if (image != null) {

            //Initialize new Mats to hold the original colored frame and the grayscaled frame
            Mat rgb = new Mat();
            Mat gray = new Mat();
            image.copyTo(rgb);
            image.copyTo(gray);

            //Create integral image from the grayscale version of frame 
            Imgproc.cvtColor(rgb, gray, Imgproc.COLOR_BGR2GRAY);
            Imgproc.equalizeHist(gray, gray);

            //MatOfRect detection window initialized
            MatOfRect detects = new MatOfRect();
            faceCC.detectMultiScale(gray, detects);

            //Print out number of detected rect objects detected
            if (detects.toArray().length != 0) {
                System.out.printf("Detected %s\n", detects.toArray().length);
                //prodFound(UPC,"T");
                isFound = true;
            }

        } else {
            break;
        }
    }
}