Example usage for org.opencv.core Mat cols

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

Introduction

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

Prototype

public int cols() 

Source Link

Usage

From source file:opencvtesting.OpenCVTesting.java

/**
 * @param args the command line arguments
 */// ww  w.j  a v  a 2 s.c  om
public static void main(String[] args) throws IOException {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(CameraWindow.class.getName()).log(java.util.logging.Level.SEVERE,
                null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(CameraWindow.class.getName()).log(java.util.logging.Level.SEVERE,
                null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(CameraWindow.class.getName()).log(java.util.logging.Level.SEVERE,
                null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(CameraWindow.class.getName()).log(java.util.logging.Level.SEVERE,
                null, ex);
    }
    //</editor-fold>

    /* Create and display the form */

    CameraWindow cWindow = new CameraWindow();
    cWindow.setVisible(true);

    Random gen = new Random();
    JFrame frameF = new JFrame();
    System.loadLibrary("opencv_java248");

    VideoCapture camera = new VideoCapture(0);
    camera.open(0); //Useless

    if (!camera.isOpened()) {
        System.out.println("Camera Error");
    } else {
        System.out.println("Camera OK?");
    }

    frame = new Mat();
    frame_gray = new Mat();
    camera.read(frame);
    showResult(frame, frameF);

    dst = new Mat(frame.size(), frame.type());
    mapX = new Mat(frame.size(), CvType.CV_32FC1);
    mapY = new Mat(frame.size(), CvType.CV_32FC1);
    boolean bEnd = true;
    while (bEnd) {

        camera.read(frame);
        Imgproc.cvtColor(frame, frame_gray, Imgproc.COLOR_BGR2GRAY);
        Imgproc.GaussianBlur(frame_gray, frame_gray, new Size(1, 1), 2);
        Imgproc.equalizeHist(frame_gray, frame_gray);
        Mat circles = new Mat();

        Imgproc.HoughCircles(frame_gray, circles, Imgproc.CV_HOUGH_GRADIENT, cWindow.get_dp(),
                frame_gray.rows() / 8, cWindow.get_param1(), cWindow.get_param2(), 0, 0);
        //System.out.println(circles.rows());

        for (int i = 0; i < circles.cols(); i++) {
            double[] circle = circles.get(0, i);
            Point center = new Point(Math.round(circle[0]), Math.round(circle[1]));
            int radius = (int) Math.round(circle[2]);
            Core.circle(frame, center, 3, new Scalar(gen.nextInt(), gen.nextInt(), gen.nextInt()), -1, 8, 0);
            Core.circle(frame, center, radius, new Scalar(gen.nextInt(), gen.nextInt(), gen.nextInt()), 3, 8,
                    0);
        }
        showResult(frame, frameF);

    }
    //Highgui.imwrite("camera1.jpg", frame);
    //System.out.println("OK");

}

From source file:opencv_java_template.TemplateTestWindow.java

private BufferedImage toBufferedImage(Mat m) {
    int type = BufferedImage.TYPE_BYTE_GRAY;
    if (m.channels() > 1)
        type = BufferedImage.TYPE_3BYTE_BGR;
    int bufferSize = m.channels() * m.cols() * m.rows();
    byte[] b = new byte[bufferSize];
    m.get(0, 0, b); // get all the pixels
    BufferedImage aux_image = new BufferedImage(m.cols(), m.rows(), type);
    final byte[] targetPixels = ((DataBufferByte) aux_image.getRaster().getDataBuffer()).getData();
    System.arraycopy(b, 0, targetPixels, 0, b.length);
    return aux_image;
}

From source file:org.akvo.caddisfly.helper.ImageHelper.java

License:Open Source License

/**
 * Gets the center of the backdrop in the test chamber
 *
 * @param bitmap the photo to analyse//from   ww  w.j av  a 2s. com
 * @return the center point of the found circle
 */
public static Point getCenter(@NonNull Bitmap bitmap) {

    // convert bitmap to mat
    Mat mat = new Mat(bitmap.getWidth(), bitmap.getHeight(), CvType.CV_8UC1);
    Mat grayMat = new Mat(bitmap.getWidth(), bitmap.getHeight(), CvType.CV_8UC1);

    Utils.bitmapToMat(bitmap, mat);

    // convert to grayScale
    int colorChannels = (mat.channels() == 3) ? Imgproc.COLOR_BGR2GRAY
            : ((mat.channels() == 4) ? Imgproc.COLOR_BGRA2GRAY : 1);

    Imgproc.cvtColor(mat, grayMat, colorChannels);

    // reduce the noise so we avoid false circle detection
    //Imgproc.GaussianBlur(grayMat, grayMat, new Size(9, 9), 2, 2);

    // param1 = gradient value used to handle edge detection
    // param2 = Accumulator threshold value for the
    // cv2.CV_HOUGH_GRADIENT method.
    // The smaller the threshold is, the more circles will be
    // detected (including false circles).
    // The larger the threshold is, the more circles will
    // potentially be returned.
    double param1 = 10, param2 = 100;

    // create a Mat object to store the circles detected
    Mat circles = new Mat(bitmap.getWidth(), bitmap.getHeight(), CvType.CV_8UC1);

    // find the circle in the image
    Imgproc.HoughCircles(grayMat, circles, Imgproc.CV_HOUGH_GRADIENT, RESOLUTION_INVERSE_RATIO,
            (double) MIN_CIRCLE_CENTER_DISTANCE, param1, param2, MIN_RADIUS, MAX_RADIUS);

    int numberOfCircles = (circles.rows() == 0) ? 0 : circles.cols();

    // draw the circles found on the image
    if (numberOfCircles > 0) {

        double[] circleCoordinates = circles.get(0, 0);

        int x = (int) circleCoordinates[0], y = (int) circleCoordinates[1];

        org.opencv.core.Point center = new org.opencv.core.Point(x, y);
        int foundRadius = (int) circleCoordinates[2];

        // circle outline
        Imgproc.circle(mat, center, foundRadius, COLOR_GREEN, 4);

        Utils.matToBitmap(mat, bitmap);

        return new Point((int) center.x, (int) center.y);
    }

    return null;
}

From source file:org.akvo.caddisfly.sensor.colorimetry.strip.calibration.CalibrationCard.java

License:Open Source License

@NonNull
public static double[][] createWhitePointArray(@NonNull Mat lab, @NonNull CalibrationData calData) {
    List<CalibrationData.WhiteLine> lines = calData.getWhiteLines();
    int numLines = lines.size() * 10; // on each line, we sample 10 points
    double[][] points = new double[numLines][5];
    int index = 0;

    calData.hSizePixel = lab.cols();
    double hPixels = calData.hSizePixel / calData.hSize; // pixel per mm in the horizontal direction
    calData.vSizePixel = lab.rows();//w w  w .  j a v a 2  s. c  o m
    double vPixels = calData.vSizePixel / calData.vSize; // pixel per mm in the vertical direction

    for (CalibrationData.WhiteLine line : lines) {
        double xStart = line.getPosition()[0];
        double yStart = line.getPosition()[1];
        double xEnd = line.getPosition()[2];
        double yEnd = line.getPosition()[3];
        double xDiff = (xEnd - xStart) * ONE_OVER_NINE;
        double yDiff = (yEnd - yStart) * ONE_OVER_NINE;
        int dp = (int) Math.round(line.getWidth() * hPixels * 0.5);
        if (dp == 0) {
            dp = 1; // minimum of one pixel
        }

        // sample line
        for (int i = 0; i <= 9; i++) {
            int xp = (int) Math.round((xStart + i * xDiff) * hPixels);
            int yp = (int) Math.round((yStart + i * yDiff) * vPixels);

            points[index * 10 + i][0] = xp;
            points[index * 10 + i][1] = yp;
            double[] whiteVal = getWhiteVal(lab, xp, yp, dp);
            points[index * 10 + i][2] = whiteVal[0];
            points[index * 10 + i][3] = whiteVal[1];
            points[index * 10 + i][4] = whiteVal[2];
        }
        index++;
    }
    return points;
}

From source file:org.akvo.caddisfly.sensor.colorimetry.strip.calibration.CalibrationCard.java

License:Open Source License

@NonNull
private static Mat doIlluminationCorrection(@NonNull Mat imgLab, @NonNull CalibrationData calData) {
    // create HLS image for homogeneous illumination calibration
    int pHeight = imgLab.rows();
    int pWidth = imgLab.cols();

    RealMatrix points = createWhitePointMatrix(imgLab, calData);

    // create coefficient matrix for all three variables L,A,B
    // the model for all three is y = ax + bx^2 + cy + dy^2 + exy + f
    // 6th row is the constant 1
    RealMatrix coefficient = new Array2DRowRealMatrix(points.getRowDimension(), 6);
    coefficient.setColumnMatrix(0, points.getColumnMatrix(0));
    coefficient.setColumnMatrix(2, points.getColumnMatrix(1));

    //create constant, x^2, y^2 and xy terms
    for (int i = 0; i < points.getRowDimension(); i++) {
        coefficient.setEntry(i, 1, Math.pow(coefficient.getEntry(i, 0), 2)); // x^2
        coefficient.setEntry(i, 3, Math.pow(coefficient.getEntry(i, 2), 2)); // y^2
        coefficient.setEntry(i, 4, coefficient.getEntry(i, 0) * coefficient.getEntry(i, 2)); // xy
        coefficient.setEntry(i, 5, 1d); // constant = 1
    }// w ww.  jav  a  2s.  c om

    // create vectors
    RealVector L = points.getColumnVector(2);
    RealVector A = points.getColumnVector(3);
    RealVector B = points.getColumnVector(4);

    // solve the least squares problem for all three variables
    DecompositionSolver solver = new SingularValueDecomposition(coefficient).getSolver();
    RealVector solutionL = solver.solve(L);
    RealVector solutionA = solver.solve(A);
    RealVector solutionB = solver.solve(B);

    // get individual coefficients
    float La = (float) solutionL.getEntry(0);
    float Lb = (float) solutionL.getEntry(1);
    float Lc = (float) solutionL.getEntry(2);
    float Ld = (float) solutionL.getEntry(3);
    float Le = (float) solutionL.getEntry(4);
    float Lf = (float) solutionL.getEntry(5);

    float Aa = (float) solutionA.getEntry(0);
    float Ab = (float) solutionA.getEntry(1);
    float Ac = (float) solutionA.getEntry(2);
    float Ad = (float) solutionA.getEntry(3);
    float Ae = (float) solutionA.getEntry(4);
    float Af = (float) solutionA.getEntry(5);

    float Ba = (float) solutionB.getEntry(0);
    float Bb = (float) solutionB.getEntry(1);
    float Bc = (float) solutionB.getEntry(2);
    float Bd = (float) solutionB.getEntry(3);
    float Be = (float) solutionB.getEntry(4);
    float Bf = (float) solutionB.getEntry(5);

    // compute mean (the luminosity value of the plane in the middle of the image)
    float L_mean = (float) (0.5 * La * pWidth + 0.5 * Lc * pHeight + Lb * pWidth * pWidth / 3.0
            + Ld * pHeight * pHeight / 3.0 + Le * 0.25 * pHeight * pWidth + Lf);
    float A_mean = (float) (0.5 * Aa * pWidth + 0.5 * Ac * pHeight + Ab * pWidth * pWidth / 3.0
            + Ad * pHeight * pHeight / 3.0 + Ae * 0.25 * pHeight * pWidth + Af);
    float B_mean = (float) (0.5 * Ba * pWidth + 0.5 * Bc * pHeight + Bb * pWidth * pWidth / 3.0
            + Bd * pHeight * pHeight / 3.0 + Be * 0.25 * pHeight * pWidth + Bf);

    // Correct image
    // we do this per row. We tried to do it in one block, but there is no speed difference.
    byte[] temp = new byte[imgLab.cols() * imgLab.channels()];
    int valL, valA, valB;
    int ii, ii3;
    float iiSq, iSq;
    int imgCols = imgLab.cols();
    int imgRows = imgLab.rows();

    // use lookup tables to speed up computation
    // create lookup tables
    float[] L_aii = new float[imgCols];
    float[] L_biiSq = new float[imgCols];
    float[] A_aii = new float[imgCols];
    float[] A_biiSq = new float[imgCols];
    float[] B_aii = new float[imgCols];
    float[] B_biiSq = new float[imgCols];

    float[] Lci = new float[imgRows];
    float[] LdiSq = new float[imgRows];
    float[] Aci = new float[imgRows];
    float[] AdiSq = new float[imgRows];
    float[] Bci = new float[imgRows];
    float[] BdiSq = new float[imgRows];

    for (ii = 0; ii < imgCols; ii++) {
        iiSq = ii * ii;
        L_aii[ii] = La * ii;
        L_biiSq[ii] = Lb * iiSq;
        A_aii[ii] = Aa * ii;
        A_biiSq[ii] = Ab * iiSq;
        B_aii[ii] = Ba * ii;
        B_biiSq[ii] = Bb * iiSq;
    }

    for (int i = 0; i < imgRows; i++) {
        iSq = i * i;
        Lci[i] = Lc * i;
        LdiSq[i] = Ld * iSq;
        Aci[i] = Ac * i;
        AdiSq[i] = Ad * iSq;
        Bci[i] = Bc * i;
        BdiSq[i] = Bd * iSq;
    }

    // We can also improve the performance of the i,ii term, if we want, but it won't make much difference.
    for (int i = 0; i < imgRows; i++) { // y
        imgLab.get(i, 0, temp);
        ii3 = 0;
        for (ii = 0; ii < imgCols; ii++) { //x
            valL = capValue(
                    Math.round((temp[ii3] & 0xFF)
                            - (L_aii[ii] + L_biiSq[ii] + Lci[i] + LdiSq[i] + Le * i * ii + Lf) + L_mean),
                    0, 255);
            valA = capValue(
                    Math.round((temp[ii3 + 1] & 0xFF)
                            - (A_aii[ii] + A_biiSq[ii] + Aci[i] + AdiSq[i] + Ae * i * ii + Af) + A_mean),
                    0, 255);
            valB = capValue(
                    Math.round((temp[ii3 + 2] & 0xFF)
                            - (B_aii[ii] + B_biiSq[ii] + Bci[i] + BdiSq[i] + Be * i * ii + Bf) + B_mean),
                    0, 255);

            temp[ii3] = (byte) valL;
            temp[ii3 + 1] = (byte) valA;
            temp[ii3 + 2] = (byte) valB;
            ii3 += 3;
        }
        imgLab.put(i, 0, temp);
    }

    return imgLab;
}

From source file:org.akvo.caddisfly.sensor.colorimetry.strip.calibration.CalibrationCard.java

License:Open Source License

@NonNull
private static float[] measurePatch(@NonNull Mat imgMat, double x, double y, @NonNull CalibrationData calData) {
    float[] LAB_result = new float[3];
    float totL = 0;
    float totA = 0;
    float totB = 0;
    int totNum = 0;

    calData.hSizePixel = imgMat.cols();
    double hPixels = calData.hSizePixel / calData.hSize; // pixel per mm
    calData.vSizePixel = imgMat.rows();/*  w w  w .j av a 2 s.c o m*/
    double vPixels = calData.vSizePixel / calData.vSize; // pixel per mm

    int xp = (int) Math.round(x * hPixels);
    int yp = (int) Math.round(y * vPixels);
    int dp = (int) Math.round(calData.getPatchSize() * hPixels * 0.25);
    byte[] temp = new byte[(2 * dp + 1) * imgMat.channels()];
    int ii3;
    for (int i = -dp; i <= dp; i++) {
        imgMat.get(yp - i, xp - dp, temp);
        ii3 = 0;
        for (int ii = 0; ii <= 2 * dp; ii++) {
            totL += temp[ii3] & 0xFF; //imgMat.get(yp + i, xp + ii)[0];
            totA += temp[ii3 + 1] & 0xFF; //imgMat.get(yp + i, xp + ii)[1];
            totB += temp[ii3 + 2] & 0xFF; //imgMat.get(yp + i, xp + ii)[2];
            totNum++;
            ii3 += 3;
        }
    }
    LAB_result[0] = totL / totNum;
    LAB_result[1] = totA / totNum;
    LAB_result[2] = totB / totNum;
    return LAB_result;
}

From source file:org.akvo.caddisfly.sensor.colorimetry.strip.calibration.CalibrationCard.java

License:Open Source License

@NonNull
private static Mat do1D_3DCorrection(@NonNull Mat imgMat, @Nullable CalibrationData calData)
        throws CalibrationException {

    if (calData == null) {
        throw new CalibrationException("no calibration data.");
    }/*from  w w w . j  a  v a  2 s .  c om*/

    final WeightedObservedPoints obsL = new WeightedObservedPoints();
    final WeightedObservedPoints obsA = new WeightedObservedPoints();
    final WeightedObservedPoints obsB = new WeightedObservedPoints();

    Map<String, double[]> calResultIllumination = new HashMap<>();
    // iterate over all patches
    try {
        for (String label : calData.getCalValues().keySet()) {
            CalibrationData.CalValue cal = calData.getCalValues().get(label);
            CalibrationData.Location loc = calData.getLocations().get(label);
            float[] LAB_color = measurePatch(imgMat, loc.x, loc.y, calData); // measure patch color
            obsL.add(LAB_color[0], cal.getL());
            obsA.add(LAB_color[1], cal.getA());
            obsB.add(LAB_color[2], cal.getB());
            calResultIllumination.put(label, new double[] { LAB_color[0], LAB_color[1], LAB_color[2] });
        }
    } catch (Exception e) {
        throw new CalibrationException("1D calibration: error iterating over all patches.", e);
    }

    // Instantiate a second-degree polynomial fitter.
    final PolynomialCurveFitter fitter = PolynomialCurveFitter.create(2);

    // Retrieve fitted parameters (coefficients of the polynomial function).
    // order of coefficients is (c + bx + ax^2), so [c,b,a]
    try {
        final double[] coefficientL = fitter.fit(obsL.toList());
        final double[] coefficientA = fitter.fit(obsA.toList());
        final double[] coefficientB = fitter.fit(obsB.toList());

        double[] valIllumination;
        double L_orig, A_orig, B_orig, L_new, A_new, B_new;

        // transform patch values using the 1d calibration results
        Map<String, double[]> calResult1D = new HashMap<>();
        for (String label : calData.getCalValues().keySet()) {
            valIllumination = calResultIllumination.get(label);

            L_orig = valIllumination[0];
            A_orig = valIllumination[1];
            B_orig = valIllumination[2];

            L_new = coefficientL[2] * L_orig * L_orig + coefficientL[1] * L_orig + coefficientL[0];
            A_new = coefficientA[2] * A_orig * A_orig + coefficientA[1] * A_orig + coefficientA[0];
            B_new = coefficientB[2] * B_orig * B_orig + coefficientB[1] * B_orig + coefficientB[0];

            calResult1D.put(label, new double[] { L_new, A_new, B_new });
        }

        // use the 1D calibration result for the second calibration step
        // Following http://docs.scipy.org/doc/scipy/reference/tutorial/linalg.html#solving-linear-least-squares-problems-and-pseudo-inverses
        // we will solve P = M x
        int total = calData.getLocations().keySet().size();
        RealMatrix coefficient = new Array2DRowRealMatrix(total, 3);
        RealMatrix cal = new Array2DRowRealMatrix(total, 3);
        int index = 0;

        // create coefficient and calibration vectors
        for (String label : calData.getCalValues().keySet()) {
            CalibrationData.CalValue calv = calData.getCalValues().get(label);
            double[] cal1dResult = calResult1D.get(label);
            coefficient.setEntry(index, 0, cal1dResult[0]);
            coefficient.setEntry(index, 1, cal1dResult[1]);
            coefficient.setEntry(index, 2, cal1dResult[2]);

            cal.setEntry(index, 0, calv.getL());
            cal.setEntry(index, 1, calv.getA());
            cal.setEntry(index, 2, calv.getB());
            index++;
        }

        DecompositionSolver solver = new SingularValueDecomposition(coefficient).getSolver();
        RealMatrix sol = solver.solve(cal);

        float a_L, b_L, c_L, a_A, b_A, c_A, a_B, b_B, c_B;
        a_L = (float) sol.getEntry(0, 0);
        b_L = (float) sol.getEntry(1, 0);
        c_L = (float) sol.getEntry(2, 0);
        a_A = (float) sol.getEntry(0, 1);
        b_A = (float) sol.getEntry(1, 1);
        c_A = (float) sol.getEntry(2, 1);
        a_B = (float) sol.getEntry(0, 2);
        b_B = (float) sol.getEntry(1, 2);
        c_B = (float) sol.getEntry(2, 2);

        //use the solution to correct the image
        double L_temp, A_temp, B_temp, L_mid, A_mid, B_mid;
        int L_fin, A_fin, B_fin;
        int ii3;
        byte[] temp = new byte[imgMat.cols() * imgMat.channels()];
        for (int i = 0; i < imgMat.rows(); i++) { // y
            imgMat.get(i, 0, temp);
            ii3 = 0;
            for (int ii = 0; ii < imgMat.cols(); ii++) { //x
                L_temp = temp[ii3] & 0xFF;
                A_temp = temp[ii3 + 1] & 0xFF;
                B_temp = temp[ii3 + 2] & 0xFF;

                L_mid = coefficientL[2] * L_temp * L_temp + coefficientL[1] * L_temp + coefficientL[0];
                A_mid = coefficientA[2] * A_temp * A_temp + coefficientA[1] * A_temp + coefficientA[0];
                B_mid = coefficientB[2] * B_temp * B_temp + coefficientB[1] * B_temp + coefficientB[0];

                L_fin = (int) Math.round(a_L * L_mid + b_L * A_mid + c_L * B_mid);
                A_fin = (int) Math.round(a_A * L_mid + b_A * A_mid + c_A * B_mid);
                B_fin = (int) Math.round(a_B * L_mid + b_B * A_mid + c_B * B_mid);

                // cap values
                L_fin = capValue(L_fin, 0, 255);
                A_fin = capValue(A_fin, 0, 255);
                B_fin = capValue(B_fin, 0, 255);

                temp[ii3] = (byte) L_fin;
                temp[ii3 + 1] = (byte) A_fin;
                temp[ii3 + 2] = (byte) B_fin;

                ii3 += 3;
            }
            imgMat.put(i, 0, temp);
        }

        return imgMat;
    } catch (Exception e) {
        throw new CalibrationException("error while performing calibration: ", e);
    }
}

From source file:org.akvo.caddisfly.sensor.colorimetry.strip.calibration.CalibrationCard.java

License:Open Source License

private static void addPatch(@NonNull Mat imgMat, Double x, Double y, @NonNull CalibrationData calData,
        String label) {//from  w w w .ja  va  2 s  .  c o m

    CalibrationData.CalValue calValue = calData.getCalValues().get(label);
    calData.hSizePixel = imgMat.cols();
    double hPixels = calData.hSizePixel / calData.hSize; // pixel per mm
    calData.vSizePixel = imgMat.rows();
    double vPixels = calData.vSizePixel / calData.vSize; // pixel per mm

    int xp = (int) Math.round(x * hPixels);
    int yp = (int) Math.round(y * vPixels);
    int dp = (int) Math.round(calData.getPatchSize() * hPixels * 0.150);
    for (int i = -dp; i <= dp; i++) {
        for (int ii = -dp; ii <= dp; ii++) {
            byte[] col = new byte[3];
            col[0] = (byte) Math.round(calValue.getL());
            col[1] = (byte) Math.round(calValue.getA());
            col[2] = (byte) Math.round(calValue.getB());
            imgMat.put(yp + i, xp + ii, col);
        }
    }
}

From source file:org.akvo.caddisfly.sensor.colorimetry.strip.detect.DetectStripTask.java

License:Open Source License

@Nullable
@Override//  w w  w .  java  2 s . c om
protected Void doInBackground(Intent... params) {
    Intent intent = params[0];

    if (intent == null) {
        return null;
    }

    String uuid = intent.getStringExtra(Constant.UUID);

    StripTest stripTest = new StripTest();
    int numPatches = stripTest.getPatchCount(uuid);

    format = intent.getIntExtra(Constant.FORMAT, ImageFormat.NV21);
    width = intent.getIntExtra(Constant.WIDTH, 0);
    height = intent.getIntExtra(Constant.HEIGHT, 0);

    if (width == 0 || height == 0) {
        return null;
    }

    JSONArray imagePatchArray = null;
    int imageCount = -1;
    Mat labImg; // Mat for image from NV21 data
    Mat labStrip; // Mat for detected strip

    try {
        String json = FileUtil.readFromInternalStorage(context, Constant.IMAGE_PATCH);
        imagePatchArray = new JSONArray(json);
    } catch (Exception e) {
        Timber.e(e);
    }

    for (int i = 0; i < numPatches; i++) {
        try {
            if (imagePatchArray != null) {
                // sub-array for each patch
                JSONArray array = imagePatchArray.getJSONArray(i);

                // get the image number from the json array
                int imageNo = array.getInt(0);

                if (imageNo > imageCount) {

                    // Set imageCount to current number
                    imageCount = imageNo;

                    byte[] data = FileUtil.readByteArray(context, Constant.DATA + imageNo);
                    if (data == null) {
                        throw new IOException();
                    }

                    //make a L,A,B Mat object from data
                    try {
                        labImg = makeLab(data);
                    } catch (Exception e) {
                        if (context != null) {
                            Timber.e(e);
                        }
                        continue;
                    }

                    //perspectiveTransform
                    try {
                        if (labImg != null) {
                            warp(labImg, imageNo);
                        }
                    } catch (Exception e) {
                        if (context != null) {
                            Timber.e(e);
                        }
                        continue;
                    }

                    //divide into calibration and strip areas
                    try {
                        if (context != null) {
                            divideIntoCalibrationAndStripArea();
                        }
                    } catch (Exception e) {
                        Timber.e(e);
                        continue;
                    }

                    //save warped image to external storage
                    //                        if (DEVELOP_MODE) {
                    //                        Mat rgb = new Mat();
                    //                        Imgproc.cvtColor(warpMat, rgb, Imgproc.COLOR_Lab2RGB);
                    //                        Bitmap bitmap = Bitmap.createBitmap(rgb.width(), rgb.height(), Bitmap.Config.ARGB_8888);
                    //                        Utils.matToBitmap(rgb, bitmap);
                    //
                    //                        //if (FileUtil.isExternalStorageWritable()) {
                    //                        FileUtil.writeBitmapToExternalStorage(bitmap, "/warp", UUID.randomUUID().toString() + ".png");
                    //}
                    //                            //Bitmap.createScaledBitmap(bitmap, BITMAP_SCALED_WIDTH, BITMAP_SCALED_HEIGHT, false);
                    //                        }

                    //calibrate
                    Mat calibrationMat;
                    try {
                        CalibrationResultData calResult = getCalibratedImage(warpMat);
                        if (calResult == null) {
                            return null;
                        } else {
                            calibrationMat = calResult.getCalibratedImage();
                        }

                        //                            Log.d(this.getClass().getSimpleName(), "E94 error mean: " + String.format(Locale.US, "%.2f", calResult.meanE94)
                        //                                    + ", max: " + String.format(Locale.US, "%.2f", calResult.maxE94)
                        //                                    + ", total: " + String.format(Locale.US, "%.2f", calResult.totalE94));

                        //                            if (AppPreferences.isDiagnosticMode()) {
                        //                                listener.showError("E94 mean: " + String.format(Locale.US, "%.2f", calResult.meanE94)
                        //                                        + ", max: " + String.format(Locale.US, "%.2f", calResult.maxE94)
                        //                                        + ", total: " + String.format(Locale.US, "%.2f", calResult.totalE94));
                        //                            }
                    } catch (Exception e) {
                        Timber.e(e);
                        return null;
                    }

                    //show calibrated image
                    //                        if (DEVELOP_MODE) {
                    //                            Mat rgb = new Mat();
                    //                            Imgproc.cvtColor(calibrationMat, rgb, Imgproc.COLOR_Lab2RGB);
                    //                            Bitmap bitmap = Bitmap.createBitmap(rgb.width(), rgb.height(), Bitmap.Config.ARGB_8888);
                    //                            Utils.matToBitmap(rgb, bitmap);
                    //                            if (FileUtil.isExternalStorageWritable()) {
                    //                                FileUtil.writeBitmapToExternalStorage(bitmap, "/warp", UUID.randomUUID().toString() + "_cal.png");
                    //                            }
                    //                            //Bitmap.createScaledBitmap(bitmap, BITMAP_SCALED_WIDTH, BITMAP_SCALED_HEIGHT, false);
                    //                        }

                    // cut out black area that contains the strip
                    Mat stripArea = null;
                    if (roiStripArea != null) {
                        stripArea = calibrationMat.submat(roiStripArea);
                    }

                    if (stripArea != null) {
                        Mat strip = null;
                        try {
                            StripTest.Brand brand = stripTest.getBrand(uuid);
                            strip = OpenCVUtil.detectStrip(stripArea, brand, ratioW, ratioH);
                        } catch (Exception e) {
                            Timber.e(e);
                        }

                        String error = "";
                        if (strip != null) {
                            labStrip = strip.clone();
                        } else {
                            if (context != null) {
                                Timber.e(context.getString(R.string.error_calibrating));
                            }
                            labStrip = stripArea.clone();

                            error = Constant.ERROR;

                            //draw a red cross over the image
                            Scalar red = RED_LAB_COLOR; // Lab color
                            Imgproc.line(labStrip, new Point(0, 0), new Point(labStrip.cols(), labStrip.rows()),
                                    red, 2);
                            Imgproc.line(labStrip, new Point(0, labStrip.rows()), new Point(labStrip.cols(), 0),
                                    red, 2);
                        }

                        try {
                            // create byte[] from Mat and store it in internal storage
                            // In order to restore the byte array, we also need the rows and columns dimensions
                            // these are stored in the last 8 bytes
                            int dataSize = labStrip.cols() * labStrip.rows() * 3;
                            byte[] payload = new byte[dataSize + 8];
                            byte[] matByteArray = new byte[dataSize];

                            labStrip.get(0, 0, matByteArray);

                            // pack cols and rows into byte arrays
                            byte[] rows = FileUtil.leIntToByteArray(labStrip.rows());
                            byte[] cols = FileUtil.leIntToByteArray(labStrip.cols());

                            // append them to the end of the array, in order rows, cols
                            System.arraycopy(matByteArray, 0, payload, 0, dataSize);
                            System.arraycopy(rows, 0, payload, dataSize, 4);
                            System.arraycopy(cols, 0, payload, dataSize + 4, 4);
                            FileUtil.writeByteArray(context, payload, Constant.STRIP + imageNo + error);
                        } catch (Exception e) {
                            Timber.e(e);
                        }
                    }
                }
            }
        } catch (@NonNull JSONException | IOException e) {

            if (context != null) {
                Timber.e(context.getString(R.string.error_cut_out_strip));
            }
        }
    }
    return null;
}

From source file:org.akvo.caddisfly.sensor.colorimetry.strip.ui.ResultActivity.java

License:Open Source License

@Override
public void showResults() {
    resultImageUrl = UUID.randomUUID().toString() + ".png";
    Intent intent = getIntent();/*from  w  ww.jav a  2s .c  o m*/
    String uuid = intent.getStringExtra(Constant.UUID);

    Mat strip;
    StripTest stripTest = new StripTest();

    // get information on the strip test from JSON
    StripTest.Brand brand = stripTest.getBrand(uuid);

    // for display purposes sort the patches by position on the strip
    List<StripTest.Brand.Patch> patches = brand.getPatchesSortedByPosition();

    // get the JSON describing the images of the patches that were stored before
    JSONArray imagePatchArray = null;
    try {
        String json = FileUtil.readFromInternalStorage(this, Constant.IMAGE_PATCH);
        if (json != null) {
            imagePatchArray = new JSONArray(json);
        }

    } catch (JSONException e) {
        Timber.e(e);
    }

    // cycle over the patches and interpret them
    if (imagePatchArray != null) {
        // if this strip is of type 'GROUP', take the first image and use that for all the patches
        AtomicInteger workCounter;
        if (brand.getGroupingType() == StripTest.GroupType.GROUP) {
            workCounter = new AtomicInteger(1);
            // handle grouping case
            boolean isInvalidStrip = FileUtil.fileExists(this, Constant.STRIP + "0" + Constant.ERROR);
            strip = ResultUtil.getMatFromFile(this, patches.get(0).getId());
            if (strip != null) {
                // create empty mat to serve as a template
                resultImage = new Mat(0, strip.cols(), CvType.CV_8UC3,
                        new Scalar(MAX_RGB_INT_VALUE, MAX_RGB_INT_VALUE, MAX_RGB_INT_VALUE));
                new BitmapTask(isInvalidStrip, strip, true, brand, patches, 0, workCounter).execute(strip);
            }
        } else {
            workCounter = new AtomicInteger(patches.size());
            // if this strip is of type 'INDIVIDUAL' handle patch by patch
            for (int i = 0; i < patches.size(); i++) { // handle patch
                // read strip from file
                strip = ResultUtil.getMatFromFile(this, patches.get(i).getId());

                if (strip != null) {
                    if (i == 0) {
                        // create empty mat to serve as a template
                        resultImage = new Mat(0, strip.cols(), CvType.CV_8UC3,
                                new Scalar(MAX_RGB_INT_VALUE, MAX_RGB_INT_VALUE, MAX_RGB_INT_VALUE));
                    }
                    new BitmapTask(false, strip, false, brand, patches, i, workCounter).execute(strip);
                }
            }
        }
    } else {
        TextView textView = new TextView(this);
        textView.setText(R.string.noData);
        LinearLayout layout = (LinearLayout) findViewById(R.id.layout_results);

        layout.addView(textView);
    }

    findViewById(R.id.progressBar).setVisibility(View.GONE);
    findViewById(R.id.testProgress).setVisibility(View.GONE);
}