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:OCV_GetAffineTransform.java

License:Open Source License

@Override
public void run(ImageProcessor ip) {
    MatOfPoint2f matPt_src = new MatOfPoint2f();
    MatOfPoint2f matPt_dst = new MatOfPoint2f();
    matPt_src.fromList(lstPt_src);/*from w ww  .  j a va  2 s. c o  m*/
    matPt_dst.fromList(lstPt_dst);

    Mat mat = Imgproc.getAffineTransform(matPt_src, matPt_dst);

    if (mat == null || mat.rows() <= 0 || mat.cols() <= 0) {
        IJ.showMessage("Output is null or error");
        return;
    }

    ResultsTable rt = OCV__LoadLibrary.GetResultsTable(true);

    for (int i = 0; i < 2; i++) {
        rt.incrementCounter();
        rt.addValue("Column01", String.valueOf(mat.get(i, 0)[0]));
        rt.addValue("Column02", String.valueOf(mat.get(i, 1)[0]));
        rt.addValue("Column03", String.valueOf(mat.get(i, 2)[0]));
    }

    rt.show("Results");
}

From source file:KoImgProc.java

License:Open Source License

/**
 * Takes a Mat and performs a series of image analysis and filtering steps
 * to detect stones in the image and filter out false circles.
 * @param color /*from  w w w  .  j av a 2  s  .c o m*/
 *             The input Mat to perform analysis on. Must be a 3-channel,
 *             8-bit BGR color image. 
 * @return An array of KoCircle objects that represent stones that were
 *          detected on the board.
 */
public static ArrayList<KoCircle> detectStones(Mat color) {
    // Create 2 Mats we'll need for image processing
    Mat grey = new Mat();
    Mat blurred = new Mat();
    Imgproc.cvtColor(color, grey, Imgproc.COLOR_BGR2GRAY); // Convert to greyscale
    Imgproc.GaussianBlur(grey, grey, new Size(9, 9), 2, 2);
    Imgproc.GaussianBlur(color, blurred, new Size(9, 9), 2, 2);

    int widthInPixels = color.cols();
    //int heightInPixels = color.cols();

    // widthInPixels will be replaced by dimensions from a camera overlay that aligns with the board
    ArrayList<KoCircle> stones = detectStones(grey, widthInPixels / 50, widthInPixels / 30, widthInPixels / 30,
            CANNY_DETECTOR_THRESHOLD_HIGH);
    double aveRadius = getAverageRadius(stones);

    // Calculate more accurate inputs to HoughCircles given the average radius
    int minCircleRadius = (int) (0.9 * aveRadius);
    int maxCircleRadius = (int) (1.1 * aveRadius);
    int minDist = (int) (aveRadius * 1.75);

    stones = detectStones(grey, minCircleRadius, maxCircleRadius, minDist, CANNY_DETECTOR_THRESHOLD_MED);
    TreeMap<String, Double[]> colorData = getColorData(stones, blurred, grey);

    if (VERBOSE) {
        for (String key : colorData.keySet()) {
            Double[] current = colorData.get(key);
            System.out.println("Data for " + key + ":");
            for (int i = 0; i < current.length; i++) {
                System.out.println(current[i]);
            }
        }
    }

    stones = detectStones(grey, minCircleRadius, maxCircleRadius, minDist, CANNY_DETECTOR_THRESHOLD_LOW);

    return filterStones(stones, colorData, aveRadius, grey, blurred);
}

From source file:KoImgProc.java

License:Open Source License

/**
 * Detects stones in the given image and returns an array list of KoCircle objects.
 * @param grey greyscale Mat of the board.
 * @param threshold threshold value for HoughCircles
 * @return an ArrayList of KoCircle objects.
 *//*ww w. j  a  v  a2  s.  c om*/
private static ArrayList<KoCircle> detectStones(Mat grey, int minRadius, int maxRadius, int minDist,
        int threshold) {
    Mat stones = new Mat();
    ArrayList<KoCircle> highThresholdStones = new ArrayList<KoCircle>();

    Imgproc.HoughCircles(grey, stones, Imgproc.CV_HOUGH_GRADIENT, DP, minDist, threshold, threshold / 2,
            minRadius, maxRadius);
    for (int i = 0; i < stones.cols(); i++) {
        highThresholdStones.add(new KoCircle(stones.get(0, i)));
    }
    System.out.println(highThresholdStones.size() + " stones detected. minRadius: " + minRadius
            + "\tmaxRadius: " + maxRadius + "\tminDist: " + minDist + "\tthreshold: " + threshold);

    return highThresholdStones;
}

From source file:MainPyramids.java

public static void main(String[] args) {

    try {/*from w w w. ja  v a 2 s .  c o  m*/

        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
        System.out.println("Verso OPENCV: " + Core.VERSION);

        //pyramids UP

        Mat source = Highgui.imread("D:\\teste.png", Highgui.CV_LOAD_IMAGE_COLOR);

        Mat destinationUp = new Mat(source.rows() * 2, source.cols() * 2, source.type());

        destinationUp = source;

        Imgproc.pyrUp(source, destinationUp, new Size(source.cols() * 2, source.rows() * 2),
                Imgproc.BORDER_DEFAULT);

        Highgui.imwrite("D://pyrUp.jpg", destinationUp);

        //pyramids DOWN

        source = Highgui.imread("D://teste.png", Highgui.CV_LOAD_IMAGE_COLOR);

        Mat destinationDown = new Mat(source.rows() / 2, source.cols() / 2, source.type());

        destinationDown = source;

        Imgproc.pyrDown(source, destinationDown, new Size(source.cols() / 2, source.rows() / 2));

        Highgui.imwrite("pyrDown.jpg", destinationDown);

    } catch (Exception e) {
        System.out.println("Exception: " + e.getMessage());
    }
}

From source file:airhockeyjava.detection.PS3EyeFrameGrabber.java

License:Open Source License

/**
 * Convert matrix into an image//from  ww w  .  j  a  va  2 s  .co m
 * 
 * @param m
 *            matrix to be converted
 * @return Converted BufferedImage
 */
private static BufferedImage toBufferedImage(Mat m) {
    int type = BufferedImage.TYPE_BYTE_GRAY;
    if (m.channels() > 1) {
        type = BufferedImage.TYPE_3BYTE_BGR;
        // System.out.println("3 Channel BufferedImage");
    }
    int bufferSize = m.channels() * m.cols() * m.rows();
    byte[] b = new byte[bufferSize];
    m.get(0, 0, b); // get all the pixels
    BufferedImage image = new BufferedImage(m.cols(), m.rows(), type);
    final byte[] targetPixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
    System.arraycopy(b, 0, targetPixels, 0, b.length);
    return image;
}

From source file:arlocros.Imshow.java

License:Apache License

/**
 * @param opencvImage// w  ww  .ja  va  2s  .co  m
 */
public static void show(Mat opencvImage) {

    Dimension frameSize = new Dimension(opencvImage.rows(), opencvImage.cols());
    if (frame == null) {
        frame = new Imshow("", frameSize.height, frameSize.width);
        frame.Window.setVisible(true);

        frame.Window.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        if (frame.SizeCustom) {
            Imgproc.resize(opencvImage, opencvImage, new Size(frame.Height, frame.Width));
        }
    }
    BufferedImage bufImage = null;
    try {

        int type = BufferedImage.TYPE_BYTE_GRAY;
        if (opencvImage.channels() > 1) {
            type = BufferedImage.TYPE_3BYTE_BGR;
        }
        int bufferSize = opencvImage.channels() * opencvImage.cols() * opencvImage.rows();
        byte[] b = new byte[bufferSize];
        opencvImage.get(0, 0, b);
        BufferedImage bufferedImage = new BufferedImage(opencvImage.cols(), opencvImage.rows(), type);
        final byte[] targetPixels = ((DataBufferByte) bufferedImage.getRaster().getDataBuffer()).getData();
        System.arraycopy(b, 0, targetPixels, 0, b.length);
        bufImage = bufferedImage;
        frame.image.setImage(bufImage);
        frame.Window.pack();
        frame.label.updateUI();
        //frame.Window.setVisible(true);
    } catch (RuntimeException e) {
        logger.info("Exception while visualizing.", e);
    }
}

From source file:at.ac.tuwien.caa.docscan.camera.CameraPreview.java

License:Open Source License

public boolean isFrameSame(Mat frame1, Mat frame2) {

    Mat tmp1 = new Mat(frame1.rows(), frame1.cols(), CvType.CV_8UC1);
    Imgproc.cvtColor(frame1, tmp1, Imgproc.COLOR_RGB2GRAY);

    Mat tmp2 = new Mat(frame2.rows(), frame2.cols(), CvType.CV_8UC1);
    Imgproc.cvtColor(frame2, tmp2, Imgproc.COLOR_RGB2GRAY);

    Mat subtractResult = new Mat(frame2.rows(), frame2.cols(), CvType.CV_8UC1);
    Core.absdiff(frame1, frame2, subtractResult);
    Imgproc.threshold(subtractResult, subtractResult, 50, 1, Imgproc.THRESH_BINARY);
    Scalar sumDiff = Core.sumElems(subtractResult);
    double diffRatio = sumDiff.val[0] / (frame1.cols() * frame2.rows());

    return diffRatio < .05;

}

From source file:at.entenbaer.utils.TPAUtils.java

License:Open Source License

/**
 * Saves a OpenCV Mat to a path inside the TexturePoemApp-Folder in the pictures directory
 * @param mat Image that should be saved
 * @param path path where the image should be saved inside the TexturePoemApp-Folder
 *//*w  w w. j  ava2 s . c  o  m*/
public static void saveMatToBitmap(Mat mat, String path) {
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        String galleryPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
                .toString();
        Log.d("galleryPath", galleryPath);

        Bitmap b = Bitmap.createBitmap(mat.cols(), mat.rows(), Bitmap.Config.ARGB_8888);

        Utils.matToBitmap(mat, b);

        File album = new File(galleryPath + "/TexturePoemApp");

        if (!album.isDirectory()) {
            album.mkdirs();
        }

        File f = new File(galleryPath + "/TexturePoemApp/" + path);
        try {
            FileOutputStream fo = new FileOutputStream(f);

            b.compress(Bitmap.CompressFormat.JPEG, 100, fo);

            fo.flush();
            fo.close();
        } catch (IOException e) {
            Log.e("IOException", "not saved");

            e.printStackTrace();
        }

    } else {
        Log.d("Env", "not mounted");
    }
}

From source file:attendance_system_adder.cv.image.java

public BufferedImage Mat2BufferedImage(Mat m) {
    int type = BufferedImage.TYPE_BYTE_GRAY;
    if (m.channels() > 1) {
        type = BufferedImage.TYPE_3BYTE_BGR;
    }/*from  ww  w  .j a  v a  2  s .c  om*/
    int bufferSize = m.channels() * m.cols() * m.rows();
    byte[] b = new byte[bufferSize];
    m.get(0, 0, b); // get all the pixels
    BufferedImage image = new BufferedImage(m.cols(), m.rows(), type);
    final byte[] targetPixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
    System.arraycopy(b, 0, targetPixels, 0, b.length);
    return image;

}

From source file:balldetection.BallDetection.java

/**
 * @param args the command line arguments
 * @throws java.io.IOException//ww  w.ja va 2s  .  co  m
 */
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 | InstantiationException | IllegalAccessException
            | javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(CameraWindow.class.getName()).log(java.util.logging.Level.SEVERE,
                null, ex);
    }
    //</editor-fold>

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

    int radius = 0;
    System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

    //intialization of matrices
    Mat circles = new Mat();
    gray = new Mat();
    hsv = new Mat();
    filter = new Mat();
    dst = new Mat();

    camera = new VideoCapture(0);
    Mat frame = new Mat();
    Webcam.ImagePanel panel = Webcam.createPanel(camera, "src");
    Webcam.ImagePanel panel2 = Webcam.createPanel(camera, "filter");
    Webcam.ImagePanel panel3 = Webcam.createPanel(camera, "dst");

    while (true) {

        camera.read(frame);
        src = frame;

        GaussianBlur(src, src, new Size(3, 3), 2, 2);
        Imgproc.cvtColor(src, hsv, Imgproc.COLOR_BGR2HSV);
        Imgproc.cvtColor(src, gray, Imgproc.COLOR_BGR2GRAY);

        Core.inRange(gray, new Scalar(20, 100, 100), new Scalar(30, 255, 255), gray);
        Core.inRange(hsv, new Scalar(cWindow.get_hLower(), cWindow.get_sLower(), cWindow.get_vLower()),
                new Scalar(cWindow.get_hUpper(), cWindow.get_sUpper(), cWindow.get_vUpper()), filter);

        Core.inRange(src, new Scalar(cWindow.get_hLower(), cWindow.get_sLower(), cWindow.get_vLower()),
                new Scalar(cWindow.get_hUpper(), cWindow.get_sUpper(), cWindow.get_vUpper()), dst);

        double[] temp = hsv.get(hsv.rows() / 2, hsv.cols() / 2);
        System.out.println(temp[0] + ", " + temp[1] + ", " + temp[2] + ", " + radius);
        //System.out.println("Current Distance from ball: " + ((2.5366*radius) - 123.02));

        Imgproc.HoughCircles(filter, circles, CV_HOUGH_GRADIENT, cWindow.get_dp(), filter.rows() / 2,
                cWindow.get_param1(), cWindow.get_param2(), cWindow.get_minCircleSize(),
                cWindow.get_maxCircleSize());

        for (int i = 0; i < circles.cols(); i++) {
            Point center = new Point(Math.round(circles.get(0, i)[0]), Math.round(circles.get(0, i)[1]));
            radius = (int) Math.round(circles.get(0, i)[2]);
            // draw the circle center
            Core.circle(src, center, 3, new Scalar(0, 255, 0), -1, 8, 0);
            // draw the circle outline
            Core.circle(src, center, radius, new Scalar(0, 0, 255), 3, 8, 0);
            //System.out.println("" + circles.get(0,0)[0] + ", " + circles.get(0,0)[1] + ", " + circles.get(0,0)[2]);
        }

        panel.updateImage(toBufferedImage(src));
        panel2.updateImage(toBufferedImage(filter));
        panel3.updateImage(toBufferedImage(dst));
    }
}