Example usage for org.opencv.core Mat channels

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

Introduction

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

Prototype

public int channels() 

Source Link

Usage

From source file:opencv.fark.ResimSecMainFrame.java

private void jButtonFarkBulActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonFarkBulActionPerformed
    farkli_pixel_say = 0;/*from w  w  w .  j a  va  2 s . c om*/
    Thread t = new Thread() {
        @Override
        public void run() {
            Mat sonuc = new Mat(resim1.rows(), resim1.cols(), CvType.CV_8UC1);
            Mat gray1 = new Mat(resim1.rows(), resim1.cols(), CvType.CV_8UC1);
            Mat gray2 = new Mat(resim1.rows(), resim1.cols(), CvType.CV_8UC1);
            System.out.println(gray1.channels());
            Imgproc.cvtColor(resim1, gray1, Imgproc.COLOR_BGR2GRAY);
            Imgproc.cvtColor(resim2, gray2, Imgproc.COLOR_BGR2GRAY);

            for (int i = 0; i < gray1.rows(); i++) {
                for (int j = 0; j < gray1.cols(); j++) {

                    double[] kresim1 = gray1.get(i, j);
                    double[] kresim2 = gray2.get(i, j);
                    //System.out.println(resim1[0]+" "+resim2[0]);
                    if (kresim1[0] != kresim2[0]) {
                        // System.out.println(kresim1[0]);
                        g1.setFont(new Font("TimesRoman", Font.PLAIN, 2));
                        g1.drawString("*", j, i);

                        //gray2.put(i, j, kresim2[0]*255);
                        jLabelPixelCount.setText(String.valueOf(++farkli_pixel_say));
                    }
                }

                jProgressBar1.setValue(i);
            } //forend
            //          Mat a = new Mat();
            //          Core.compare(resim1, resim2, a, Core.CMP_NE);
            //  Imgproc.blur(gray2, gray2, new Size(10, 10));

            //          MatToBufImg matToBufImage = new MatToBufImg();
            //          matToBufImage.setMatrix(gray2, ".jpg");
            //          g1.drawImage(matToBufImage.getBufferedImage(), 0, 0, null);
        }
    };
    t.start();

}

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 w  w  w. jav a  2  s.c o  m
 * @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
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
    }/*from w  w  w .  j av a  2s  .co  m*/

    // 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();/*from  ww w  .  j a va  2 s . com*/
    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.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 ww  w .  java  2  s .  co m

    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.detect.DetectStripTask.java

License:Open Source License

private Mat makeLab(byte[] data) {
    if (format == ImageFormat.NV21) {
        //convert preview data to Mat object in CIELab format
        Mat rgb = new Mat(height, width, CvType.CV_8UC3);
        Mat labImg = new Mat(height, width, CvType.CV_8UC3);
        Mat previewMat = new Mat(height + height / 2, width, CvType.CV_8UC1);
        previewMat.put(0, 0, data);//from  w  w  w. j a va2s.  co m
        Imgproc.cvtColor(previewMat, rgb, Imgproc.COLOR_YUV2RGB_NV21, rgb.channels());
        Imgproc.cvtColor(rgb, labImg, Imgproc.COLOR_RGB2Lab, rgb.channels());

        return labImg;
    }
    return null;
}

From source file:org.openpnp.vision.FluentCv.java

License:Open Source License

public static double calculatePsnr(Mat I1, Mat I2) {
    Mat s1 = new Mat();
    Core.absdiff(I1, I2, s1); // |I1 - I2|
    s1.convertTo(s1, CvType.CV_32F); // cannot make a square on 8 bits
    s1 = s1.mul(s1); // |I1 - I2|^2

    Scalar s = Core.sumElems(s1); // sum elements per channel

    double sse = s.val[0] + s.val[1] + s.val[2]; // sum channels

    if (sse <= 1e-10) // for small values return zero
        return 0;
    else {/*  w  w  w  . ja v a 2  s . c om*/
        double mse = sse / (double) (I1.channels() * I1.total());
        double psnr = 10.0 * Math.log10((255 * 255) / mse);
        return psnr;
    }
}

From source file:org.openpnp.vision.FluentCv.java

License:Open Source License

/**
 * From FireSight: https://github.com/firepick1/FireSight/wiki/op-Sharpness
 * /*w  w w .  j  a  va2  s.  c om*/
 * @param image
 * @return
 */
public static double calculateSharpnessGRAS(Mat image) {
    int sum = 0;
    Mat matGray = new Mat();

    if (image.channels() == 1) {
        matGray = image;
    } else {
        Imgproc.cvtColor(image, matGray, Imgproc.COLOR_BGR2GRAY);
    }

    byte[] b1 = new byte[1];
    byte[] b2 = new byte[1];
    for (int r = 0; r < matGray.rows(); r++) {
        for (int c = 0; c < matGray.cols() - 1; c++) {
            matGray.get(r, c, b1);
            matGray.get(r, c + 1, b2);
            int df = (int) b1[0] - (int) b2[0];
            sum += df * df;
        }
    }

    return ((double) sum / matGray.rows() / (matGray.cols() - 1));
}

From source file:org.sikuli.script.Finder.java

License:MIT License

private static void printMatI(Mat mat) {
    int[] data = new int[mat.channels()];
    for (int r = 0; r < mat.rows(); r++) {
        for (int c = 0; c < mat.cols(); c++) {
            mat.get(r, c, data);//  w ww  .j  a  va2s . co  m
            log(lvl, "(%d, %d) %s", r, c, Arrays.toString(data));
        }
    }
}