Example usage for org.opencv.core Mat rows

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

Introduction

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

Prototype

public int rows() 

Source Link

Usage

From source file:com.trandi.opentld.TLDView.java

License:Apache License

@Override
public Mat onCameraFrame(Mat originalFrame) {
    try {/*from  www  .  j  a v  a 2s  . co  m*/
        // Image is too big and this requires too much CPU for a phone, so scale everything down...
        Imgproc.resize(originalFrame, _workingFrame, WORKING_FRAME_SIZE);
        final Size workingRatio = new Size(originalFrame.width() / WORKING_FRAME_SIZE.width,
                originalFrame.height() / WORKING_FRAME_SIZE.height);
        // usefull to see what we're actually working with...
        _workingFrame.copyTo(originalFrame.submat(originalFrame.rows() - _workingFrame.rows(),
                originalFrame.rows(), 0, _workingFrame.cols()));

        if (_trackedBox != null) {
            if (_tld == null) { // run the 1st time only
                Imgproc.cvtColor(_workingFrame, _lastGray, Imgproc.COLOR_RGB2GRAY);
                _tld = new Tld(_tldProperties);
                final Rect scaledDownTrackedBox = scaleDown(_trackedBox, workingRatio);
                Log.i(Util.TAG, "Working Ration: " + workingRatio + " / Tracking Box: " + _trackedBox
                        + " / Scaled down to: " + scaledDownTrackedBox);
                try {
                    _tld.init(_lastGray, scaledDownTrackedBox);
                } catch (Exception eInit) {
                    // start from scratch, you have to select an init box again !
                    _trackedBox = null;
                    _tld = null;
                    throw eInit; // re-throw it as it will be dealt with later
                }
            } else {
                Imgproc.cvtColor(_workingFrame, _currentGray, Imgproc.COLOR_RGB2GRAY);

                _processFrameStruct = _tld.processFrame(_lastGray, _currentGray);
                drawPoints(originalFrame, _processFrameStruct.lastPoints, workingRatio, new Scalar(255, 0, 0));
                drawPoints(originalFrame, _processFrameStruct.currentPoints, workingRatio,
                        new Scalar(0, 255, 0));
                drawBox(originalFrame, scaleUp(_processFrameStruct.currentBBox, workingRatio),
                        new Scalar(0, 0, 255));

                _currentGray.copyTo(_lastGray);

                // overlay the current positive examples on the real image(needs converting at the same time !)
                //copyTo(_tld.getPPatterns(), originalFrame);
            }
        }
    } catch (Exception e) {
        _errMessage = e.getClass().getSimpleName() + " / " + e.getMessage();
        Log.e(Util.TAG, "TLDView PROBLEM", e);
    }

    if (_errMessage != null) {
        Imgproc.putText(originalFrame, _errMessage, new Point(0, 300), Core.FONT_HERSHEY_PLAIN, 1.3d,
                new Scalar(255, 0, 0), 2);
    }

    return originalFrame;
}

From source file:com.trandi.opentld.TLDView.java

License:Apache License

private static void copyTo(List<Mat> patterns, Mat dest) {
    if (patterns == null || patterns.isEmpty() || dest == null)
        return;/*  ww w.j a  va  2 s  .  c om*/

    final int patternRows = patterns.get(0).rows();
    final int patternCols = patterns.get(0).cols();
    final int vertCount = dest.rows() / patternRows;
    final int horizCount = patterns.size() / vertCount + 1;

    int patchIdx = 0;
    for (int col = dest.cols() - horizCount * patternCols - 1; col < dest.cols()
            && patchIdx < patterns.size(); col += patternCols) {
        for (int row = 0; row < dest.rows() && patchIdx < patterns.size(); row += patternRows) {
            Imgproc.cvtColor(patterns.get(patchIdx),
                    dest.submat(row, row + patternRows, col, col + patternCols), Imgproc.COLOR_GRAY2RGBA);
            patchIdx++;
        }
    }
}

From source file:com.ttolley.pongbot.controller.CvPanel.java

/**
 * Converts/writes a Mat into a BufferedImage.
 *
 * @param matrix Mat of type CV_8UC3 or CV_8UC1
 * @return BufferedImage of type TYPE_3BYTE_BGR or TYPE_BYTE_GRAY
 *//* w w  w  . j av  a  2 s.  c  o m*/
public BufferedImage matToBufferedImage(Mat matrix) {
    int cols = matrix.cols();
    int rows = matrix.rows();
    int elemSize = (int) matrix.elemSize();
    byte[] data = new byte[cols * rows * elemSize];
    int type;
    matrix.get(0, 0, data);
    switch (matrix.channels()) {
    case 1:
        type = BufferedImage.TYPE_BYTE_GRAY;
        break;
    case 3:
        type = BufferedImage.TYPE_3BYTE_BGR;
        // bgr to rgb  
        byte b;
        for (int i = 0; i < data.length; i = i + 3) {
            b = data[i];
            data[i] = data[i + 2];
            data[i + 2] = b;
        }
        break;
    default:
        return null;
    }
    BufferedImage image2 = new BufferedImage(cols, rows, type);
    image2.getRaster().setDataElements(0, 0, cols, rows, data);
    return image2;
}

From source file:com.untref.bordes.HoughCirculos.java

public static BufferedImage implementarCiculos(BufferedImage screen, int acumulador, int radioMin,
        int radioMax) {
    Mat source = new Mat(screen.getHeight(), screen.getWidth(), CvType.CV_8UC3);
    byte[] data = ((DataBufferByte) screen.getRaster().getDataBuffer()).getData();
    source.put(0, 0, data);/*  w ww .ja v a2s .c om*/
    //ImageIO.write(screen, "jpg", "imagen");
    //Mat source = Highgui.imread("test.jpg", Highgui.CV_LOAD_IMAGE_COLOR);
    Mat destination = new Mat(source.rows(), source.cols(), source.type());

    Imgproc.cvtColor(source, destination, Imgproc.COLOR_RGB2GRAY);

    Imgproc.GaussianBlur(destination, destination, new Size(3, 3), 0, 0);

    Mat circles = new Mat();
    Imgproc.HoughCircles(destination, circles, Imgproc.CV_HOUGH_GRADIENT, 1, 30, 10, acumulador, radioMin,
            radioMax);

    int radius;
    org.opencv.core.Point pt;
    for (int x = 0; x < circles.cols(); x++) {
        double vCircle[] = circles.get(0, x);

        if (vCircle == null) {
            break;
        }

        pt = new org.opencv.core.Point(Math.round(vCircle[0]), Math.round(vCircle[1]));
        radius = (int) Math.round(vCircle[2]);

        // draw the found circle
        Core.circle(source, pt, radius, new Scalar(150, 0, 0), 2);
        Core.circle(source, pt, 1, new Scalar(0, 0, 0), 2);
    }
    BufferedImage res = matToBufferedImage(source);

    return res;

}

From source file:com.untref.gui.Editar.java

public static BufferedImage matToBufferedImage(Mat matrix) {
    BufferedImage bimg = new BufferedImage(1, 1, 1);
    if (matrix != null) {
        int cols = matrix.cols();
        int rows = matrix.rows();
        int elemSize = (int) matrix.elemSize();
        byte[] data = new byte[cols * rows * elemSize];
        int type;
        matrix.get(0, 0, data);//from w  ww  . ja v  a 2  s  .  c  om
        switch (matrix.channels()) {
        case 1:
            type = BufferedImage.TYPE_BYTE_GRAY;
            break;
        case 3:
            type = BufferedImage.TYPE_3BYTE_BGR;
            // bgr to rgb  
            byte b;
            for (int i = 0; i < data.length; i = i + 3) {
                b = data[i];
                data[i] = data[i + 2];
                data[i + 2] = b;
            }
            break;
        default:
            return null;
        }

        // Reuse existing BufferedImage if possible
        if (bimg == null || bimg.getWidth() != cols || bimg.getHeight() != rows || bimg.getType() != type) {
            bimg = new BufferedImage(cols, rows, type);
        }
        bimg.getRaster().setDataElements(0, 0, cols, rows, data);
    } else { // mat was null
        bimg = null;
    }
    return bimg;
}

From source file:com.wallerlab.compcellscope.calcDPCTask.java

License:BSD License

protected Long doInBackground(Mat... matrix_list) {
    //int count = urls.length;
    Mat in1 = matrix_list[0];//from w  w w  . ja  v a2  s  . c o  m
    Mat in2 = matrix_list[1];
    Mat outputMat = matrix_list[2];

    Mat Mat1 = new Mat(in1.width(), in1.height(), in1.type());
    Mat Mat2 = new Mat(in2.width(), in2.height(), in2.type());
    in1.copyTo(Mat1);
    in2.copyTo(Mat2);

    Imgproc.cvtColor(Mat1, Mat1, Imgproc.COLOR_RGBA2GRAY, 1);
    Imgproc.cvtColor(Mat2, Mat2, Imgproc.COLOR_RGBA2GRAY, 1);

    Mat output = new Mat(Mat1.width(), Mat1.height(), CvType.CV_8UC4);
    Mat dpcSum = new Mat(Mat1.width(), Mat1.height(), CvType.CV_32FC1);
    Mat dpcDifference = new Mat(Mat1.width(), Mat1.height(), CvType.CV_32FC1);
    Mat dpcImgF = new Mat(Mat1.width(), Mat1.height(), CvType.CV_32FC1);

    /*
    Log.d(TAG,String.format("Mat1 format is %.1f-%.1f, type: %d",Mat1.size().width,Mat1.size().height,Mat1.type()));
    Log.d(TAG,String.format("Mat2 format is %.1f-%.1f, type: %d",Mat2.size().width,Mat2.size().height,Mat2.type()));
    */

    // Convert to Floats
    Mat1.convertTo(Mat1, CvType.CV_32FC1);
    Mat2.convertTo(Mat2, CvType.CV_32FC1);
    Core.add(Mat1, Mat2, dpcSum);
    Core.subtract(Mat1, Mat2, dpcDifference);
    Core.divide(dpcDifference, dpcSum, dpcImgF);
    Core.add(dpcImgF, new Scalar(1.0), dpcImgF); // Normalize to 0-2.0
    Core.multiply(dpcImgF, new Scalar(110), dpcImgF); // Normalize to 0-255
    dpcImgF.convertTo(output, CvType.CV_8UC1); // Convert back into RGB
    Imgproc.cvtColor(output, output, Imgproc.COLOR_GRAY2RGBA, 4);

    dpcSum.release();
    dpcDifference.release();
    dpcImgF.release();
    Mat1.release();
    Mat2.release();

    Mat maskedImg = Mat.zeros(output.rows(), output.cols(), CvType.CV_8UC4);
    int radius = maskedImg.width() / 2 + 25;
    Core.circle(maskedImg, new Point(maskedImg.width() / 2, maskedImg.height() / 2), radius,
            new Scalar(255, 255, 255), -1, 8, 0);
    output.copyTo(outputMat, maskedImg);
    output.release();
    maskedImg.release();
    return null;
}

From source file:com.wallerlab.compcellscope.MultiModeViewActivity.java

License:BSD License

public Mat calcDPC(Mat in1, Mat in2, Mat out) {
    Mat Mat1 = new Mat(in1.width(), in1.height(), in1.type());
    Mat Mat2 = new Mat(in2.width(), in2.height(), in2.type());
    in1.copyTo(Mat1);//from www .ja  v  a  2  s  .c  om
    in2.copyTo(Mat2);

    Imgproc.cvtColor(Mat1, Mat1, Imgproc.COLOR_RGBA2GRAY, 1);
    Imgproc.cvtColor(Mat2, Mat2, Imgproc.COLOR_RGBA2GRAY, 1);

    Mat output = new Mat(Mat1.width(), Mat1.height(), CvType.CV_8UC4);
    Mat dpcSum = new Mat(Mat1.width(), Mat1.height(), CvType.CV_32FC1);
    Mat dpcDifference = new Mat(Mat1.width(), Mat1.height(), CvType.CV_32FC1);
    Mat dpcImgF = new Mat(Mat1.width(), Mat1.height(), CvType.CV_32FC1);

    /*
    Log.d(TAG,String.format("Mat1 format is %.1f-%.1f, type: %d",Mat1.size().width,Mat1.size().height,Mat1.type()));
    Log.d(TAG,String.format("Mat2 format is %.1f-%.1f, type: %d",Mat2.size().width,Mat2.size().height,Mat2.type()));
    */

    // Convert to Floats
    Mat1.convertTo(Mat1, CvType.CV_32FC1);
    Mat2.convertTo(Mat2, CvType.CV_32FC1);
    Core.add(Mat1, Mat2, dpcSum);
    Core.subtract(Mat1, Mat2, dpcDifference);
    Core.divide(dpcDifference, dpcSum, dpcImgF);
    Core.add(dpcImgF, new Scalar(1.0), dpcImgF); // Normalize to 0-2.0
    Core.multiply(dpcImgF, new Scalar(110), dpcImgF); // Normalize to 0-255
    dpcImgF.convertTo(output, CvType.CV_8UC1); // Convert back into RGB
    Imgproc.cvtColor(output, output, Imgproc.COLOR_GRAY2RGBA, 4);

    dpcSum.release();
    dpcDifference.release();
    dpcImgF.release();
    Mat1.release();
    Mat2.release();

    Mat maskedImg = Mat.zeros(output.rows(), output.cols(), CvType.CV_8UC4);
    int radius = maskedImg.width() / 2 + 25;
    Core.circle(maskedImg, new Point(maskedImg.width() / 2, maskedImg.height() / 2), radius,
            new Scalar(255, 255, 255), -1, 8, 0);
    output.copyTo(out, maskedImg);
    output.release();
    maskedImg.release();
    return out;
}

From source file:com.wallerlab.processing.utilities.ImageUtils.java

License:BSD License

public static Bitmap toBitmap(Mat mat) {
    Bitmap bmp = Bitmap.createBitmap(mat.cols(), mat.rows(), Bitmap.Config.ARGB_8888);
    Utils.matToBitmap(mat, bmp);//from www  .j  a v a2 s . c  o  m
    return bmp;
}

From source file:com.wallerlab.processing.utilities.ImageUtils.java

License:BSD License

public static Mat circularShift(Mat mat, int x, int y) {
    int w = mat.cols();
    int h = mat.rows();
    Mat result = Mat.zeros(h, w, CvType.CV_32FC4);

    int shiftR = x % w;
    int shiftD = y % h;
    //java modulus gives negative results for negative numbers
    if (shiftR < 0)
        shiftR += w;/*from   w  w  w .j av a 2  s .c  o m*/
    if (shiftD < 0)
        shiftD += h;

    /* extract 4 submatrices
              |---| shiftR
     ______________
    |         |   |
    |    1    | 2 |
    |_________|___|  ___ shiftD
    |         |   |   |
    |    3    | 4 |   |
    |         |   |   |
    |_________|___|  _|_
     */
    Mat shift1 = mat.submat(0, h - shiftD, 0, w - shiftR);
    Mat shift2 = mat.submat(0, h - shiftD, w - shiftR, w);
    Mat shift3 = mat.submat(h - shiftD, h, 0, w - shiftR);
    Mat shift4 = mat.submat(h - shiftD, h, w - shiftR, w);

    /* and rearrange
     ______________
    |   |         |
    | 4 |    3    |
    |   |         |
    |___|_________|
    |   |         |
    | 2 |    1    |
    |___|_________|
     */
    shift1.copyTo(new Mat(result, new Rect(shiftR, shiftD, w - shiftR, h - shiftD)));
    shift2.copyTo(new Mat(result, new Rect(0, shiftD, shiftR, h - shiftD)));
    shift3.copyTo(new Mat(result, new Rect(shiftR, 0, w - shiftR, shiftD)));
    shift4.copyTo(new Mat(result, new Rect(0, 0, shiftR, shiftD)));

    return result;
}

From source file:contador_de_moedas.Circulo.java

private Mat doCirciloHough(Mat imgIn) {
    int valor = 0;
    baseImageList();/* w w  w. j a va2 s .c om*/
    Reconhecimento _reco;
    Imgproc.cvtColor(imgIn, imgIn, Imgproc.COLOR_BGR2GRAY);
    /*Imgproc.erode(imgIn, imgIn, Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(2, 2)));
     Imgproc.dilate(imgIn, imgIn, Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(2, 2)));*/

    double min_dist_Centro = imgIn.rows() / 8.0;
    /*
     Imgproc.HoughCircles(imageB, circles, method, dp, minDist, param1, param2, minRadius, maxRadius)
     imageB: Imagem de entrada (tons de cinza)
     circles: um vector que armazena conjuntos de 3 valores: Xc, Yc, r para cada crculo detectado.
     method: CV_HOUGH_GRADIENT definir o mtodo de deteco. Atualmente, esse  o nico disponvel em OpenCV
     dp: (1) A razo inversa da resoluo
     min_dist: (imgIn.rows / 8 ) A distncia mnima entre centros detectados
     param1: (200 limite superior para o detector de bordas Canny interna) limite superior para o detector de bordas Canny interna
     param2: (100* Limiar para deteco de centro)Limiar para deteco de centro.
     minRadius: (0) raio minimo a ser detectado. Se for desconhecida, colocar zero como padrao.
     maxRadius: (maxRadius) raio maximo a ser detectado. Se desconhecida, colocar zero como padrao   
     */
    Imgproc.HoughCircles(imgIn, circles, Imgproc.CV_HOUGH_GRADIENT, 1, min_dist_Centro, param1, param2,
            minRadius, maxRadius);

    rowsCols[0] = circles.rows();
    rowsCols[1] = circles.cols();

    for (int i = 0; i < circles.cols(); i++) {
        _reco = new Reconhecimento();
        double data[] = circles.get(0, i);
        Point pt = new Point(Math.round(data[0]), Math.round(data[1]));
        int raio = (int) Math.round(data[2]);

        if (data[2] > 20.0 && data[2] < 28.0) {
            valor = 10;
            setSomatorio(getSomatorio() + valor);
        } else if (data[2] > 27.0 && data[2] < 32.0) {
            valor = 5;
            setSomatorio(getSomatorio() + valor);
        } else if (data[2] > 32.0 && data[2] < 33.0) {
            valor = 50;
            setSomatorio(getSomatorio() + valor);
        } else if (data[2] > 33.5 && data[2] < 36.0) {
            valor = 25;
            setSomatorio(getSomatorio() + valor);
        } else if (data[2] > 35.0 && data[2] < 40.0) {
            valor = 100;
            setSomatorio(getSomatorio() + valor);
        }
        resultados.add(" r:" + (int) raio + "   (X:" + (int) pt.x + "-Y:" + (int) pt.y + ") Val: " + valor);
        vetMat[i] = _reco.CriaMascara(pt, data[2], imgIn);
        output = _reco.CalculaHistograma(vetMat[i], imageA);

        /*  System.out.println("histogram\n"+output.dump());
         for (int j = 0; j < vetMatFile.length - 1; j++) {
         Mat ab = vetMatFile[j];
         System.out.println("histogram\n"+vetMatFile[j].dump());
         double distance = Imgproc.compareHist(output, vetMatFile[j], Imgproc.CV_COMP_CORREL);
                
         System.out.print("ok");
         }*/

        if (criaBase) {
            FileWriter arq = null;
            try {
                String nome = "X" + (int) pt.x + "Y" + (int) pt.y + "R" + (int) raio;
                // Imgcodecs.imwrite("baseConhecimento/" + nome + "M.png", vetMat[i]);
                arq = new FileWriter("baseConhecimento/" + nome + ".txt");
                PrintWriter gravarArq = new PrintWriter(arq);
                gravarArq.print(output.dump());
                arq.close();
                // Imgcodecs.imwrite("baseConhecimento/" + nome + ".yml", output);
            } catch (IOException ex) {
                Logger.getLogger(Circulo.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                try {
                    arq.close();
                } catch (IOException ex) {
                    Logger.getLogger(Circulo.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

        Imgproc.circle(imageA, pt, raio, new Scalar(0, 0, 255), 2);
        Imgproc.circle(imageA, pt, 2, new Scalar(0, 255, 0), 1);
    }
    return imageA;
}