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:usefull.LoopImageFiles.java

License:LGPL

public static int countP(Mat f) {
    int countAll = 0;
    for (int m = 0; m < f.cols(); m++) {
        for (int n = 0; n < f.rows(); n++) {
            double[] t = f.get(n, m);
            double value2 = t[0];
            if (value2 == 255.0) {
                countAll++;//from w ww .  j av  a 2  s.  c  o m
            }
        }
    }
    return countAll;
}

From source file:utils.PreProcessing.java

public BufferedImage enhance(BufferedImage img) {
    Utils ut = new Utils();

    ut.Img2GrayScale(img);//from ww w .java  2s  .  c  om
    Mat source = ut.bufferedImageToMat(img);

    Mat destination = new Mat(source.rows(), source.cols(), source.type());

    //Melhora constraste
    //Imgproc.equalizeHist(source, destination);
    //Melhora brilho
    source.convertTo(destination, -1, 2, 60);

    //Suavizao
    // Imgproc.GaussianBlur(source, destination, new Size(11, 11), 0);

    //Melhora a definio
    Imgproc.GaussianBlur(source, destination, new Size(0, 0), 10);
    Core.addWeighted(source, 1.8, destination, -0.8, 0, destination);
    //return ut.convertMatToImage(destination);
    BufferedImage imgRetorno = ut.matToBufferedImage(destination);
    return imgRetorno;
}

From source file:ve.ucv.ciens.ccg.nxtar.MainActivity.java

License:Apache License

@Override
public MarkerData findMarkersInFrame(byte[] frame) {
    if (ocvOn) {//from w  w w .  j  av a 2  s. co m
        if (cameraCalibrated) {
            int[] codes = new int[ProjectConstants.MAXIMUM_NUMBER_OF_MARKERS];
            float[] translations = new float[ProjectConstants.MAXIMUM_NUMBER_OF_MARKERS * 3];
            float[] rotations = new float[ProjectConstants.MAXIMUM_NUMBER_OF_MARKERS * 9];
            MarkerData data;
            Bitmap tFrame, mFrame;
            Mat inImg = new Mat();
            Mat outImg = new Mat();

            // Fill the codes array with -1 to indicate markers that were not found;
            for (int i : codes)
                codes[i] = -1;

            // Decode the input image and convert it to an OpenCV matrix.
            tFrame = BitmapFactory.decodeByteArray(frame, 0, frame.length);
            Utils.bitmapToMat(tFrame, inImg);

            // Find the markers in the input image.
            getMarkerCodesAndLocations(inImg.getNativeObjAddr(), outImg.getNativeObjAddr(), codes,
                    cameraMatrix.getNativeObjAddr(), distortionCoeffs.getNativeObjAddr(), translations,
                    rotations);

            // Encode the output image as a JPEG image.
            mFrame = Bitmap.createBitmap(outImg.cols(), outImg.rows(), Bitmap.Config.RGB_565);
            Utils.matToBitmap(outImg, mFrame);
            mFrame.compress(CompressFormat.JPEG, 100, outputStream);

            // Create and fill the output data structure.
            data = new MarkerData();
            data.outFrame = outputStream.toByteArray();
            data.markerCodes = codes;
            data.rotationMatrices = new Matrix3[ProjectConstants.MAXIMUM_NUMBER_OF_MARKERS];
            data.translationVectors = new Vector3[ProjectConstants.MAXIMUM_NUMBER_OF_MARKERS];

            for (int i = 0, p = 0; i < ProjectConstants.MAXIMUM_NUMBER_OF_MARKERS; i++, p += 3) {
                data.translationVectors[i] = new Vector3(translations[p], translations[p + 1],
                        translations[p + 2]);
            }

            for (int k = 0; k < ProjectConstants.MAXIMUM_NUMBER_OF_MARKERS; k++) {
                data.rotationMatrices[k] = new Matrix3();
                for (int row = 0; row < 3; row++) {
                    for (int col = 0; col < 3; col++) {
                        data.rotationMatrices[k].val[col + (row * 3)] = rotations[col + (row * 3) + (9 * k)];
                    }
                }
            }

            // Clean up memory.
            tFrame.recycle();
            mFrame.recycle();
            outputStream.reset();

            return data;
        } else {
            Gdx.app.debug(TAG, CLASS_NAME + ".findMarkersInFrame(): The camera has not been calibrated.");
            return null;
        }
    } else {
        Gdx.app.debug(TAG, CLASS_NAME + ".findMarkersInFrame(): OpenCV is not ready or failed to load.");
        return null;
    }
}

From source file:video.Mat2Image.java

public void getSpace(Mat mat) {
    this.mat = mat;
    Imgproc.cvtColor(mat, mat, Imgproc.COLOR_RGB2BGR);
    int w = mat.cols(), h = mat.rows();
    if (dat == null || dat.length != w * h * 3)
        dat = new byte[w * h * 3];
    if (img == null || img.getWidth() != w || img.getHeight() != h
            || img.getType() != BufferedImage.TYPE_3BYTE_BGR)
        img = new BufferedImage(w, h, BufferedImage.TYPE_3BYTE_BGR);
}

From source file:video.Mat2Image.java

BufferedImage getImage(Mat mat) {
    getSpace(mat);
    mat.get(0, 0, dat);
    img.getRaster().setDataElements(0, 0, mat.cols(), mat.rows(), dat);

    return img;
}

From source file:video.PictureView.java

public static BufferedImage mat2Img(Mat in) {
    BufferedImage out;/*  www .  ja va  2s  .com*/
    int width = in.cols();
    int height = in.height();
    byte[] data = new byte[width * height * (int) in.elemSize()];
    int type;
    in.get(0, 0, data);

    if (in.channels() == 1) {
        type = BufferedImage.TYPE_BYTE_GRAY;
    } else {
        type = BufferedImage.TYPE_3BYTE_BGR;
    }

    out = new BufferedImage(width, height, type);

    out.getRaster().setDataElements(0, 0, width, height, data);
    return out;
}

From source file:videostream.MulticastServer.java

/**
 * Transforms an OpenCV mat to a byte array
 * @param m The mat to transform/*from   w  w w  . j a v  a2 s .  c  om*/
 * @param format The desired format
 * @return The mat transformed to a byte array
 * @throws IOException 
 */
public byte[] matToByteArray(Mat m, String format) throws IOException {
    // Check if image is grayscale or color
    int type = BufferedImage.TYPE_BYTE_GRAY;
    if (m.channels() > 1) {
        type = BufferedImage.TYPE_3BYTE_BGR;
    }
    // Transfer bytes from Mat to 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);

    Iterator iter = ImageIO.getImageWritersByFormatName("jpeg");
    ImageWriter writer = (ImageWriter) iter.next();
    ImageWriteParam iwp = writer.getDefaultWriteParam();

    iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    iwp.setCompressionQuality(quality);

    ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
    ImageOutputStream ios = ImageIO.createImageOutputStream(baos1);
    writer.setOutput(ios);
    IIOImage Iimage = new IIOImage(image, null, null);
    writer.write(null, Iimage, iwp);
    writer.dispose();

    return baos1.toByteArray();

}

From source file:videostream.MyFrame.java

public Image toBufferedImage(Mat m) {
    // Code from http://stackoverflow.com/questions/15670933/opencv-java-load-image-to-gui

    // Check if image is grayscale or color
    int type = BufferedImage.TYPE_BYTE_GRAY;
    if (m.channels() > 1) {
        type = BufferedImage.TYPE_3BYTE_BGR;
    }/*from   w ww  . jav  a  2 s  .  c o m*/
    // Transfer bytes from Mat to 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:View.Signature.java

public static int sift(String routeVal, String route, String n_img1, String n_img2, String extension) {

    String bookObject = routeVal + n_img2 + extension;
    String bookScene = route + n_img1 + extension;

    //System.out.println("Iniciando SIFT");
    //java.lang.System.out.print("Abriendo imagenes | ");
    Mat objectImage = Highgui.imread(bookObject, Highgui.CV_LOAD_IMAGE_COLOR);
    Mat sceneImage = Highgui.imread(bookScene, Highgui.CV_LOAD_IMAGE_COLOR);

    MatOfKeyPoint objectKeyPoints = new MatOfKeyPoint();
    FeatureDetector featureDetector = FeatureDetector.create(FeatureDetector.SIFT);
    //java.lang.System.out.print("Encontrar keypoints con SIFT | ");  
    featureDetector.detect(objectImage, objectKeyPoints);
    KeyPoint[] keypoints = objectKeyPoints.toArray();

    MatOfKeyPoint objectDescriptors = new MatOfKeyPoint();
    DescriptorExtractor descriptorExtractor = DescriptorExtractor.create(DescriptorExtractor.SIFT);
    //java.lang.System.out.print("Computando descriptores | ");  
    descriptorExtractor.compute(objectImage, objectKeyPoints, objectDescriptors);

    // Create the matrix for output image.   
    Mat outputImage = new Mat(objectImage.rows(), objectImage.cols(), Highgui.CV_LOAD_IMAGE_COLOR);
    Scalar newKeypointColor = new Scalar(255, 0, 0);

    //java.lang.System.out.print("Dibujando keypoints en imagen base | ");  
    Features2d.drawKeypoints(objectImage, objectKeyPoints, outputImage, newKeypointColor, 0);

    // Match object image with the scene image  
    MatOfKeyPoint sceneKeyPoints = new MatOfKeyPoint();
    MatOfKeyPoint sceneDescriptors = new MatOfKeyPoint();
    //java.lang.System.out.print("Detectando keypoints en imagen base | ");
    featureDetector.detect(sceneImage, sceneKeyPoints);
    //java.lang.System.out.print("Computando descriptores en imagen base | ");
    descriptorExtractor.compute(sceneImage, sceneKeyPoints, sceneDescriptors);

    Mat matchoutput = new Mat(sceneImage.rows() * 2, sceneImage.cols() * 2, Highgui.CV_LOAD_IMAGE_COLOR);
    Scalar matchestColor = new Scalar(0, 255, 0);

    List<MatOfDMatch> matches = new LinkedList<MatOfDMatch>();
    DescriptorMatcher descriptorMatcher = DescriptorMatcher.create(DescriptorMatcher.FLANNBASED);
    //java.lang.System.out.print("Encontrando matches entre imagenes | ");  
    descriptorMatcher.knnMatch(objectDescriptors, sceneDescriptors, matches, 2);

    //java.lang.System.out.println("Calculando buenos matches");
    LinkedList<DMatch> goodMatchesList = new LinkedList<DMatch>();

    float nndrRatio = 0.7f;
    java.lang.System.out.println(matches.size());
    for (int i = 0; i < matches.size(); i++) {
        MatOfDMatch matofDMatch = matches.get(i);
        DMatch[] dmatcharray = matofDMatch.toArray();
        DMatch m1 = dmatcharray[0];//from w w  w.  j  av  a  2  s . com
        DMatch m2 = dmatcharray[1];

        if (m1.distance <= m2.distance * nndrRatio) {
            goodMatchesList.addLast(m1);

        }
    }

    if (goodMatchesList.size() >= 7) {
        //java.lang.System.out.println("Match enontrado!!! Matches: "+goodMatchesList.size());
        //if(goodMatchesList.size()>max){

        //cambio = 1;
        //}    

        List<KeyPoint> objKeypointlist = objectKeyPoints.toList();
        List<KeyPoint> scnKeypointlist = sceneKeyPoints.toList();

        LinkedList<Point> objectPoints = new LinkedList<>();
        LinkedList<Point> scenePoints = new LinkedList<>();

        for (int i = 0; i < goodMatchesList.size(); i++) {
            objectPoints.addLast(objKeypointlist.get(goodMatchesList.get(i).queryIdx).pt);
            scenePoints.addLast(scnKeypointlist.get(goodMatchesList.get(i).trainIdx).pt);
        }

        MatOfPoint2f objMatOfPoint2f = new MatOfPoint2f();
        objMatOfPoint2f.fromList(objectPoints);
        MatOfPoint2f scnMatOfPoint2f = new MatOfPoint2f();
        scnMatOfPoint2f.fromList(scenePoints);

        Mat homography = Calib3d.findHomography(objMatOfPoint2f, scnMatOfPoint2f, Calib3d.RANSAC, 3);

        Mat obj_corners = new Mat(4, 1, CvType.CV_32FC2);
        Mat scene_corners = new Mat(4, 1, CvType.CV_32FC2);

        obj_corners.put(0, 0, new double[] { 0, 0 });
        obj_corners.put(1, 0, new double[] { objectImage.cols(), 0 });
        obj_corners.put(2, 0, new double[] { objectImage.cols(), objectImage.rows() });
        obj_corners.put(3, 0, new double[] { 0, objectImage.rows() });

        //System.out.println("Transforming object corners to scene corners...");  
        Core.perspectiveTransform(obj_corners, scene_corners, homography);

        Mat img = Highgui.imread(bookScene, Highgui.CV_LOAD_IMAGE_COLOR);

        Core.line(img, new Point(scene_corners.get(0, 0)), new Point(scene_corners.get(1, 0)),
                new Scalar(0, 255, 0), 4);
        Core.line(img, new Point(scene_corners.get(1, 0)), new Point(scene_corners.get(2, 0)),
                new Scalar(0, 255, 0), 4);
        Core.line(img, new Point(scene_corners.get(2, 0)), new Point(scene_corners.get(3, 0)),
                new Scalar(0, 255, 0), 4);
        Core.line(img, new Point(scene_corners.get(3, 0)), new Point(scene_corners.get(0, 0)),
                new Scalar(0, 255, 0), 4);

        //java.lang.System.out.println("Dibujando imagen de coincidencias");
        MatOfDMatch goodMatches = new MatOfDMatch();
        goodMatches.fromList(goodMatchesList);

        Features2d.drawMatches(objectImage, objectKeyPoints, sceneImage, sceneKeyPoints, goodMatches,
                matchoutput, matchestColor, newKeypointColor, new MatOfByte(), 2);
        String n_outputImage = route + "results\\" + n_img2 + "_outputImage_sift" + extension;
        String n_matchoutput = route + "results\\" + n_img2 + "_matchoutput_sift" + extension;
        String n_img = route + "results\\" + n_img2 + "_sift" + extension;
        Highgui.imwrite(n_outputImage, outputImage);
        Highgui.imwrite(n_matchoutput, matchoutput);
        //Highgui.imwrite(n_img, img);  
        java.lang.System.out.println(goodMatches.size().height);
        double result = goodMatches.size().height * 100 / matches.size();

        java.lang.System.out.println((int) result);
        //double result =goodMatches.size().height;
        if (result > 100) {
            return 100;
        } else if (result <= 100 && result > 85) {
            return 85;
        } else if (result <= 85 && result > 50) {
            return 50;
        } else if (result <= 50 && result > 25) {
            return 25;
        } else {
            return 0;
        }
    } else {
        //java.lang.System.out.println("Firma no encontrada");  
    }
    return 0;
    //System.out.println("Terminando SIFT");  
}

From source file:View.SignatureLib.java

public static int sift(String routeRNV, String routeAdherent) {

    String bookObject = routeAdherent;
    String bookScene = routeRNV;//from w  w w .j  ava  2s .c o m

    //System.out.println("Iniciando SIFT");
    //java.lang.System.out.print("Abriendo imagenes | ");
    Mat objectImage = Highgui.imread(bookObject, Highgui.CV_LOAD_IMAGE_COLOR);
    Mat sceneImage = Highgui.imread(bookScene, Highgui.CV_LOAD_IMAGE_COLOR);

    MatOfKeyPoint objectKeyPoints = new MatOfKeyPoint();
    FeatureDetector featureDetector = FeatureDetector.create(FeatureDetector.SIFT);
    //java.lang.System.out.print("Encontrar keypoints con SIFT | ");  
    featureDetector.detect(objectImage, objectKeyPoints);
    KeyPoint[] keypoints = objectKeyPoints.toArray();

    MatOfKeyPoint objectDescriptors = new MatOfKeyPoint();
    DescriptorExtractor descriptorExtractor = DescriptorExtractor.create(DescriptorExtractor.SIFT);
    //java.lang.System.out.print("Computando descriptores | ");  
    descriptorExtractor.compute(objectImage, objectKeyPoints, objectDescriptors);

    // Create the matrix for output image.   
    Mat outputImage = new Mat(objectImage.rows(), objectImage.cols(), Highgui.CV_LOAD_IMAGE_COLOR);
    Scalar newKeypointColor = new Scalar(255, 0, 0);

    //java.lang.System.out.print("Dibujando keypoints en imagen base | ");  
    Features2d.drawKeypoints(objectImage, objectKeyPoints, outputImage, newKeypointColor, 0);

    // Match object image with the scene image  
    MatOfKeyPoint sceneKeyPoints = new MatOfKeyPoint();
    MatOfKeyPoint sceneDescriptors = new MatOfKeyPoint();
    //java.lang.System.out.print("Detectando keypoints en imagen base | ");
    featureDetector.detect(sceneImage, sceneKeyPoints);
    //java.lang.System.out.print("Computando descriptores en imagen base | ");
    descriptorExtractor.compute(sceneImage, sceneKeyPoints, sceneDescriptors);

    Mat matchoutput = new Mat(sceneImage.rows() * 2, sceneImage.cols() * 2, Highgui.CV_LOAD_IMAGE_COLOR);
    Scalar matchestColor = new Scalar(0, 255, 0);

    List<MatOfDMatch> matches = new LinkedList<MatOfDMatch>();
    DescriptorMatcher descriptorMatcher = DescriptorMatcher.create(DescriptorMatcher.FLANNBASED);
    //java.lang.System.out.println(sceneDescriptors);  

    if (sceneDescriptors.empty()) {
        java.lang.System.out.println("Objeto no encontrado");
        return 0;
    }

    descriptorMatcher.knnMatch(objectDescriptors, sceneDescriptors, matches, 2);

    //java.lang.System.out.println("Calculando buenos matches");
    LinkedList<DMatch> goodMatchesList = new LinkedList<DMatch>();

    float nndrRatio = 0.7f;

    for (int i = 0; i < matches.size(); i++) {
        MatOfDMatch matofDMatch = matches.get(i);
        DMatch[] dmatcharray = matofDMatch.toArray();
        DMatch m1 = dmatcharray[0];
        DMatch m2 = dmatcharray[1];

        if (m1.distance <= m2.distance * nndrRatio) {
            goodMatchesList.addLast(m1);

        }
    }

    if (goodMatchesList.size() >= 7) {
        max = goodMatchesList.size();

        List<KeyPoint> objKeypointlist = objectKeyPoints.toList();
        List<KeyPoint> scnKeypointlist = sceneKeyPoints.toList();

        LinkedList<Point> objectPoints = new LinkedList<>();
        LinkedList<Point> scenePoints = new LinkedList<>();

        for (int i = 0; i < goodMatchesList.size(); i++) {
            objectPoints.addLast(objKeypointlist.get(goodMatchesList.get(i).queryIdx).pt);
            scenePoints.addLast(scnKeypointlist.get(goodMatchesList.get(i).trainIdx).pt);
        }

        MatOfPoint2f objMatOfPoint2f = new MatOfPoint2f();
        objMatOfPoint2f.fromList(objectPoints);
        MatOfPoint2f scnMatOfPoint2f = new MatOfPoint2f();
        scnMatOfPoint2f.fromList(scenePoints);

        Mat homography = Calib3d.findHomography(objMatOfPoint2f, scnMatOfPoint2f, Calib3d.RANSAC, 3);

        Mat obj_corners = new Mat(4, 1, CvType.CV_32FC2);
        Mat scene_corners = new Mat(4, 1, CvType.CV_32FC2);

        obj_corners.put(0, 0, new double[] { 0, 0 });
        obj_corners.put(1, 0, new double[] { objectImage.cols(), 0 });
        obj_corners.put(2, 0, new double[] { objectImage.cols(), objectImage.rows() });
        obj_corners.put(3, 0, new double[] { 0, objectImage.rows() });

        //System.out.println("Transforming object corners to scene corners...");  
        Core.perspectiveTransform(obj_corners, scene_corners, homography);

        Mat img = Highgui.imread(bookScene, Highgui.CV_LOAD_IMAGE_COLOR);

        Core.line(img, new Point(scene_corners.get(0, 0)), new Point(scene_corners.get(1, 0)),
                new Scalar(0, 255, 0), 4);
        Core.line(img, new Point(scene_corners.get(1, 0)), new Point(scene_corners.get(2, 0)),
                new Scalar(0, 255, 0), 4);
        Core.line(img, new Point(scene_corners.get(2, 0)), new Point(scene_corners.get(3, 0)),
                new Scalar(0, 255, 0), 4);
        Core.line(img, new Point(scene_corners.get(3, 0)), new Point(scene_corners.get(0, 0)),
                new Scalar(0, 255, 0), 4);

        //java.lang.System.out.println("Dibujando imagen de coincidencias");
        MatOfDMatch goodMatches = new MatOfDMatch();
        goodMatches.fromList(goodMatchesList);

        Features2d.drawMatches(objectImage, objectKeyPoints, sceneImage, sceneKeyPoints, goodMatches,
                matchoutput, matchestColor, newKeypointColor, new MatOfByte(), 2);

        String n_outputImage = "../pre/outputImage_sift.jpg";
        String n_matchoutput = "../pre/matchoutput_sift.jpg";
        String n_img = "../pre/sift.jpg";
        Highgui.imwrite(n_outputImage, outputImage);
        Highgui.imwrite(n_matchoutput, matchoutput);
        Highgui.imwrite(n_img, img);
        java.lang.System.out.println(goodMatches.size().height);
        double result = goodMatches.size().height;//*100/matches.size();
        int score = 0;
        if (result > 26) {
            score = 100;
        } else if (result <= 26 && result > 22) {
            score = 85;
        } else if (result <= 22 && result > 17) {
            score = 50;
        } else if (result <= 17 && result > 11) {
            score = 25;
        } else {
            score = 0;
        }
        java.lang.System.out.println("Score: " + score);
        return score;
    } else {
        java.lang.System.out.println("Objeto no encontrado");
        return 0;
    }
    //System.out.println("Terminando SIFT");  
}