Example usage for org.opencv.core Mat Mat

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

Introduction

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

Prototype

public Mat(Mat m, Rect roi) 

Source Link

Usage

From source file:PlateSegment.java

public void findPossibleCharacters() {
    // Is is assumed that the plate has been normalized?
    // If it is then we can skip this...SEGMENTATION_THRESHOLD

    // --- Threshold the plate :)
    Image image = this.getLicensePlate();
    int width = image.getImageWidth(), height = image.getImageHeight();
    Mat threshold = image.generateThresholdImage(image.equalizeHistogram(), image.SEGMENTATION_THRESHOLD);

    // --- Normalize the plate
    // step 1) adjust the plate... (streching) 

    // step 2) readjust the plate such that the external dirt is cleaned... 
    //         of course, we crop it :)

    int newWidth = (int) (width * 0.85), newHeight = (int) (height * 0.60); //By 90%;
    int newX = Math.round((width - newWidth) / 2);
    int newY = (int) (height * 0.13); //Math.round((height-newHeight)/2);
    Rect roi = new Rect(newX, newY, newWidth, newHeight);
    Mat newImage = new Mat(threshold, roi);
    /*   // w  ww.  j a v  a2  s.  c o  m
    //Generate threshold values for canny :)
    //Histogram h = new Histogram(image); int mean = h.getHistogramMean();
            
    //int low = 100;
    //Mat canny = image.generateCannyEdgeImage(newImage, low, low*3);
    //Imgproc.dilate(canny, canny, new Mat(), new Point(-1, -1), 1);
    */
    //List<MatOfPoint> list = image.getContourMap(newImage);
    //List<Rect> rectangles = contourToBoundingBoxes(list);

    Mat orig = image.getImage();
    Mat testImage = new Mat(orig, roi);
    //Imgproc.drawContours(testImage, list, -1, image.COLOR_RED);

    int i = 1;
    /*
    String platePatha = "/media/902A1D4D2A1D31A8/thesis/images/test/local/carrots/";
    for(Rect rectangle:rectangles){
       //Point pt1 = new Point(rectangle.x, rectangle.y),
       //     pt2 = new Point(rectangle.x+rectangle.width, rectangle.y+rectangle.height);
       //Core.rectangle(testImage, pt1, pt2, image.COLOR_GREEN, 1);
               
       String name = platePatha+"rectangle"+i+".JPG";
       Mat subimage = new Mat(testImage, rectangle);
       image.writeImageToFile(name, subimage);
               
       i++;
    }
    */
    String platePath = "/media/902A1D4D2A1D31A8/thesis/images/test/local/carrots/croppped.JPG";
    image.writeImageToFile(platePath, newImage);

}

From source file:Questao2.java

void ruidoGaussiano() {
    System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

    Mat original_Bgr = image.clone();/*  w w w. ja v  a2 s .  com*/

    // cria uma imagem e inicializa com valores aleatorios
    Mat mGaussian_noise = new Mat(original_Bgr.size(), original_Bgr.type());
    System.out.print("Valor Principal: ");
    int mean = in.nextInt();
    System.out.print("Desvio Padro: ");
    int desv = in.nextInt();
    // randn(matriz destino, mean value, desvio padrao)
    randn(mGaussian_noise, mean, desv);

    // aplicacao do ruido: original(clone) + mGaussian_noise
    for (int m = 0; m < original_Bgr.rows(); m++) {
        for (int n = 0; n < original_Bgr.cols(); n++) {
            double[] val = new double[3];
            for (int i = 0; i < original_Bgr.get(m, n).length; i++) {
                val[i] = original_Bgr.get(m, n)[i] + mGaussian_noise.get(m, n)[i];
            }
            original_Bgr.put(m, n, val);
        }
    }

    // normalize(matriz entrada, matriz saida, valor minimo, valor maximo, tipo de normalizacao, tipo da imagem de saida)
    normalize(original_Bgr, original_Bgr, 0, 255, Core.NORM_MINMAX, CvType.CV_8UC3);

    // salva resultado do ruido gaussiano na imagem "gaussian.jpg"
    Imgcodecs.imwrite("gaussian.jpg", original_Bgr);
    showResult("gaussian.jpg");
}

From source file:Questao2.java

void ruidoSalPimenta() {
    System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

    // obtem clone da matriz original
    Mat saltPepper_img = image.clone();/*  w w  w. j a  v  a  2 s  .c  o m*/
    // cria matriz para o ruido e inicializa com valor aleatorios
    Mat mSaltPepper_noise = new Mat(saltPepper_img.size(), saltPepper_img.type());
    // randn(matriz destino, valor principal (espectativa), desvio padrao)
    randn(mSaltPepper_noise, 0, 255);
    System.out.print("Valor Mnimo: ");
    int min = in.nextInt();
    System.out.print("Valor Mximo: ");
    int max = in.nextInt();
    // utilizando da matriz de numeros aleatorios, verifica valores
    // muito baixos e os substituem por zero na matriz resultante (copia da original)
    // e os valores muito altos sao substituidos por 255
    for (int m = 0; m < saltPepper_img.rows(); m++) {
        for (int n = 0; n < saltPepper_img.cols(); n++) {
            double[] val = new double[3];
            if (mSaltPepper_noise.get(m, n)[0] < min && mSaltPepper_noise.get(m, n)[1] < min
                    && mSaltPepper_noise.get(m, n)[2] < min) {
                for (int i = 0; i < saltPepper_img.get(m, n).length; i++) {
                    val[i] = 0;
                }
                saltPepper_img.put(m, n, val);
            }
            if (mSaltPepper_noise.get(m, n)[0] > max && mSaltPepper_noise.get(m, n)[1] > max
                    && mSaltPepper_noise.get(m, n)[2] > max) {
                for (int i = 0; i < saltPepper_img.get(m, n).length; i++) {
                    val[i] = 255;
                }
                saltPepper_img.put(m, n, val);
            }
        }
    }

    // normalize(matriz entrada, matriz saida, valor minimo, valor maximo, tipo de normalizacao, tipo da imagem de saida)
    normalize(saltPepper_img, saltPepper_img, 0, 255, Core.NORM_MINMAX, CvType.CV_8UC3);

    /**
     * Salva imagem resultante em saltapepper.jpg
     */
    Imgcodecs.imwrite("saltpepper.jpg", saltPepper_img);
    showResult("saltpepper.jpg");
}

From source file:Questao3.java

void desvioPadrao() {
    System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

    /**//  w w w .ja v a2  s .  co  m
     * Array temporario que ir armazenar os valores de um pixel
     * para todas as imagens de entrada.
     */
    double[] tmp = new double[arquivos.length];

    /**
     * Tranforma imagens em matrizes em escala de cinza
     */
    for (String s : arquivos) {
        images.add(Imgcodecs.imread(s, Imgcodecs.CV_LOAD_IMAGE_GRAYSCALE));
    }

    /**
     * Matriz que ir armazenar os valores de desvio padro
     */
    double[][] stdDev = new double[images.get(0).rows()][images.get(0).cols()];

    /**
     * Calculo do desvio padro para cada pixel de todas as imagens.
     */
    for (int i = 0; i < images.get(0).rows(); i++) {
        for (int j = 0; j < images.get(0).cols(); j++) {
            for (int k = 0; k < arquivos.length; k++) {
                tmp[k] = images.get(k).get(i, j)[0];
            }
            double tmpDev = Math.sqrt(somatorio(tmp) / arquivos.length);
            stdDev[i][j] = tmpDev;

        }
    }

    /**
     * Cria uma matriz opencv do tipo escala de cinza
     */
    ruido = new Mat(new Size((int) images.get(0).cols(), (int) images.get(0).rows()), CvType.CV_8UC1);
    /**
     * Matriz que ira receber a matriz de desvio padro normalizada
     * Maior rudo = 255
     * Ausncia de rudo = 0
     */
    double[][] d = normalizacao(stdDev);
    /**
     * Salva o resultado na imagem ruido.jpg
     */
    Imgcodecs.imwrite("ruido.jpg", ruido);
    showResult("ruido.jpg");
}

From source file:arlocros.CameraParams.java

License:Apache License

public static Mat getCameraMatrix(CameraParams cameraParams) {
    final Mat cameraMatrix = new Mat(new Size(3, 3), CvType.CV_32FC1);
    cameraMatrix.put(0, 0, cameraParams.fx());
    cameraMatrix.put(0, 1, 0);/*from   ww  w.j av a 2  s . co m*/
    cameraMatrix.put(0, 2, cameraParams.cx());
    cameraMatrix.put(1, 0, 0);
    cameraMatrix.put(1, 1, cameraParams.fy());
    cameraMatrix.put(1, 2, cameraParams.cy());
    cameraMatrix.put(2, 0, 0);
    cameraMatrix.put(2, 1, 0);
    cameraMatrix.put(2, 2, 1);

    return cameraMatrix;
}

From source file:attendance_system_adder.cv.image.java

public Mat getFaceDetec(Mat image) {
    Mat face = null;/* w w  w.j a  v a2 s . co  m*/

    System.out.println("\nRunning DetectFaceDemo");

    CascadeClassifier faceDetector = new CascadeClassifier(".\\resource\\haarcascade_frontalface_default.xml");

    // Detect faces in the image.
    // MatOfRect is a special container class for Rect.
    MatOfRect faceDetections = new MatOfRect();
    faceDetector.detectMultiScale(image, faceDetections);

    //    System.out.println(String.format("Detected %s faces", faceDetections.toArray().length));
    //    // Draw a bounding box around each face.
    for (Rect rect : faceDetections.toArray()) {
        Imgproc.rectangle(image, new Point(rect.x, rect.y),
                new Point(rect.x + rect.width, rect.y + rect.height), new Scalar(255, 0, 0));
        face = new Mat(image, rect);
    }
    //    // Save the visualized detection.
    //    String filename = "faceDetection.png";
    //    System.out.println(String.format("Writing %s", filename));
    //    imwrite(filename, image);
    //FaceRecognizer fr;//= new LBPHFaceRecognizer();
    return face;
}

From source file:by.zuyeu.deyestracker.core.detection.task.DetectPupilsTask.java

@Override
public Point call() throws Exception {
    long startTime = System.nanoTime();

    final Mat imageHSV = new Mat(frame.size(), Core.DEPTH_MASK_8U);
    Imgproc.cvtColor(frame, imageHSV, Imgproc.COLOR_BGR2GRAY);

    Imgproc.erode(imageHSV, imageHSV, Imgproc.getStructuringElement(Imgproc.MORPH_RECT, STRUCT_ELEMENT_SIZE));
    Imgproc.dilate(imageHSV, imageHSV, Imgproc.getStructuringElement(Imgproc.MORPH_RECT, STRUCT_ELEMENT_SIZE));
    Imgproc.GaussianBlur(imageHSV, imageHSV, STRUCT_ELEMENT_SIZE, GAUS_BLUR_DELTA);

    Core.MinMaxLocResult mmG = Core.minMaxLoc(imageHSV);

    long endTime = System.nanoTime();
    LOG.debug("pupil detected = {}", mmG.minLoc);
    LOG.debug("detection time: {} ms", (float) (endTime - startTime) / 1000000);
    return mmG.minLoc;
}

From source file:classes.FloodFiller.java

private void fillFrom(Point seed, int lo, int up, Scalar backgroundColor, Scalar contourFillingColor) {

    Mat object = ObjectGenerator.extract(image, seed.x, seed.y, 10, 10);
    this.meanColor = Core.mean(object);

    Rect ccomp = new Rect();
    Mat mask = Mat.zeros(image.rows() + 2, image.cols() + 2, CvType.CV_8UC1);

    int connectivity = 4;
    int newMaskVal = 255;
    int ffillMode = 1;

    int flags = connectivity + (newMaskVal << 8) + (ffillMode == 1 ? Imgproc.FLOODFILL_FIXED_RANGE : 0);

    Scalar newVal = new Scalar(0.299, 0.587, 0.114);

    Imgproc.threshold(mask, mask, 1, 128, Imgproc.THRESH_BINARY);

    filledArea = Imgproc.floodFill(image.clone(), mask, seed, newVal, ccomp, new Scalar(lo, lo, lo),
            new Scalar(up, up, up), flags);

    //        Highgui.imwrite("mask.png", mask);
    ImageUtils.saveImage(mask, "mask.png", request);

    morphologicalImage = new Mat(image.size(), CvType.CV_8UC3);

    Mat element = new Mat(3, 3, CvType.CV_8U, new Scalar(1));

    ArrayList<Mat> mask3 = new ArrayList<Mat>();
    mask3.add(mask);//from   www  .j av  a  2  s .co  m
    mask3.add(mask);
    mask3.add(mask);
    Core.merge(mask3, mask);

    // Applying morphological filters
    Imgproc.erode(mask, morphologicalImage, element);
    Imgproc.morphologyEx(morphologicalImage, morphologicalImage, Imgproc.MORPH_CLOSE, element,
            new Point(-1, -1), 9);
    Imgproc.morphologyEx(morphologicalImage, morphologicalImage, Imgproc.MORPH_OPEN, element, new Point(-1, -1),
            2);
    Imgproc.resize(morphologicalImage, morphologicalImage, image.size());

    //        Highgui.imwrite("morphologicalImage.png", morphologicalImage);
    ImageUtils.saveImage(morphologicalImage, "morphologicalImage.png", request);

    List<MatOfPoint> contours = new ArrayList<MatOfPoint>();

    Core.split(mask, mask3);
    Mat binarymorphologicalImage = mask3.get(0);

    Imgproc.findContours(binarymorphologicalImage.clone(), contours, new Mat(), Imgproc.RETR_EXTERNAL,
            Imgproc.CHAIN_APPROX_NONE);

    contoursImage = new Mat(image.size(), CvType.CV_8UC3, backgroundColor);

    int thickness = -1; // Thicknes should be lower than zero in order to drawn the filled contours
    Imgproc.drawContours(contoursImage, contours, -1, contourFillingColor, thickness); // Drawing all the contours found
    //        Highgui.imwrite("allContoursImage.png", contoursImage);
    ImageUtils.saveImage(contoursImage, "allContoursImage.png", request);

    if (contours.size() > 1) {

        int minContourWith = 20;
        int minContourHeight = 20;
        int maxContourWith = 6400 / 2;
        int maxContourHeight = 4800 / 2;

        contours = filterContours(contours, minContourWith, minContourHeight, maxContourWith, maxContourHeight);
    }

    if (contours.size() > 0) {

        MatOfPoint biggestContour = contours.get(0); // getting the biggest contour
        contourArea = Imgproc.contourArea(biggestContour);

        if (contours.size() > 1) {
            biggestContour = Collections.max(contours, new ContourComparator()); // getting the biggest contour in case there are more than one
        }

        Point[] points = biggestContour.toArray();
        path = "M " + (int) points[0].x + " " + (int) points[0].y + " ";
        for (int i = 1; i < points.length; ++i) {
            Point v = points[i];
            path += "L " + (int) v.x + " " + (int) v.y + " ";
        }
        path += "Z";

        biggestContourImage = new Mat(image.size(), CvType.CV_8UC3, backgroundColor);

        Imgproc.drawContours(biggestContourImage, contours, 0, contourFillingColor, thickness);

        //            Highgui.imwrite("biggestContourImage.png", biggestContourImage);
        ImageUtils.saveImage(biggestContourImage, "biggestContourImage.png", request);

        Mat maskForColorExtraction = biggestContourImage.clone();

        if (isWhite(backgroundColor)) {
            Imgproc.dilate(maskForColorExtraction, maskForColorExtraction, new Mat(), new Point(-1, -1), 3);
        } else {
            Imgproc.erode(maskForColorExtraction, maskForColorExtraction, new Mat(), new Point(-1, -1), 3);
        }

        //            Highgui.imwrite("maskForColorExtraction.png", maskForColorExtraction);
        ImageUtils.saveImage(maskForColorExtraction, "maskForColorExtraction.png", request);

        Mat extractedColor = new Mat();

        if (isBlack(backgroundColor) && isWhite(contourFillingColor)) {
            Core.bitwise_and(maskForColorExtraction, image, extractedColor);

        } else {
            Core.bitwise_or(maskForColorExtraction, image, extractedColor);
        }

        //            Highgui.imwrite("extractedColor.png", extractedColor);
        ImageUtils.saveImage(extractedColor, "extractedColor.png", request);

        computedSearchWindow = Imgproc.boundingRect(biggestContour);
        topLeftCorner = computedSearchWindow.tl();

        Rect croppingRect = new Rect(computedSearchWindow.x, computedSearchWindow.y,
                computedSearchWindow.width - 1, computedSearchWindow.height - 1);

        Mat imageForTextRecognition = new Mat(extractedColor.clone(), croppingRect);
        //            Highgui.imwrite(outImageName, imageForTextRecognition);
        ImageUtils.saveImage(imageForTextRecognition, outImageName, request);

        //            
        //
        //            Mat data = new Mat(imageForTextRecognition.size(), CvType.CV_8UC3, backgroundColor);
        //            imageForTextRecognition.copyTo(data);
        //            data.convertTo(data, CvType.CV_8UC3);
        //
        //            // The meanColor variable represents the color in the GBR space, the following line transforms this to the RGB color space, which
        //            // is assumed in the prepareImage method of the TextRecognitionPreparer class
        //            Scalar userColor = new Scalar(meanColor.val[2], meanColor.val[1], meanColor.val[0]);
        //
        //            ArrayList<String> recognizableImageNames = TextRecognitionPreparer.generateRecognizableImagesNames(data, backgroundColor, userColor);
        //            for (String imageName : recognizableImageNames) {
        //
        //                try {
        //                    // First recognition step
        //                    String recognizedText = TextRecognizer.recognize(imageName, true).trim();
        //                    if (recognizedText != null && !recognizedText.isEmpty()) {
        //                        recognizedStrings.add(recognizedText);
        //                    }
        //                    // Second recognition step
        //                    recognizedText = TextRecognizer.recognize(imageName, false).trim();
        //                    if (recognizedText != null && !recognizedText.isEmpty()) {
        //                        recognizedStrings.add(recognizedText);
        //                    }
        //                    
        //                } catch (Exception e) {
        //                }
        //            }
        //            
        ////            ArrayList<BufferedImage> recognizableBufferedImages = TextRecognitionPreparer.generateRecognizableBufferedImages(data, backgroundColor, userColor);
        ////            for (BufferedImage bufferedImage : recognizableBufferedImages) {
        ////                try {
        ////                    // First recognition step
        ////                    String recognizedText = TextRecognizer.recognize(bufferedImage, true).trim();
        ////                    if (recognizedText != null && !recognizedText.isEmpty()) {
        ////                        recognizedStrings.add(recognizedText);
        ////                    }
        ////                    // Second recognition step
        ////                    recognizedText = TextRecognizer.recognize(bufferedImage, false).trim();
        ////                    if (recognizedText != null && !recognizedText.isEmpty()) {
        ////                        recognizedStrings.add(recognizedText);
        ////                    }
        ////                    
        ////                } catch (Exception e) {
        ////                }
        ////            }
        //
        //            
        //            

        // compute all moments
        Moments mom = Imgproc.moments(biggestContour);
        massCenter = new Point(mom.get_m10() / mom.get_m00(), mom.get_m01() / mom.get_m00());

        // draw black dot
        Core.circle(contoursImage, massCenter, 4, contourFillingColor, 8);
    }

}

From source file:classes.ObjectFinder.java

private void computeObjectHistogram() {
    // Converting the current fram to HSV color space
    Mat hsvImage = new Mat(this.objectImage.size(), CvType.CV_8UC3);

    System.out.println(this.objectImage);

    Imgproc.cvtColor(this.objectImage, hsvImage, Imgproc.COLOR_BGR2HSV);

    // Getting the pixels that are in te specified ranges
    Mat maskImage = new Mat(this.objectImage.size(), CvType.CV_8UC1);
    int hmin = thresholdsVector.get(0);
    int hmax = thresholdsVector.get(1);
    int smin = thresholdsVector.get(2);
    int smax = thresholdsVector.get(3);
    int vmin = thresholdsVector.get(4);
    int vmax = thresholdsVector.get(5);

    Core.inRange(hsvImage, new Scalar(hmin, smin, vmin), new Scalar(hmax, smax, vmax), maskImage);

    Mat hueImage = new Mat(hsvImage.size(), CvType.CV_8UC1);

    MatOfInt fromto = new MatOfInt(0, 0);
    Core.mixChannels(Arrays.asList(hsvImage), Arrays.asList(hueImage), fromto);

    MatOfInt sizes = new MatOfInt(16);
    MatOfFloat ranges = new MatOfFloat(0, 180);
    MatOfInt channels = new MatOfInt(0);

    Mat histogram = new Mat();
    boolean accumulate = false;
    Imgproc.calcHist(Arrays.asList(hueImage), channels, maskImage, histogram, sizes, ranges, accumulate);

    Highgui.imwrite("histogram.png", histogram);

    // The resulting histogram is normalized and placed in the class variable
    Core.normalize(histogram, objectHistogram, 0, 255, Core.NORM_MINMAX);

}

From source file:classes.ObjectFinder.java

private void backprojectObjectHistogram() {

    // Converting the current fram to HSV color space
    Mat hsvImage = new Mat(this.objectImage.size(), CvType.CV_8UC3);

    Imgproc.cvtColor(this.inputFrame, hsvImage, Imgproc.COLOR_BGR2HSV);

    // Getting the pixels that are in te specified ranges    
    int hmin = this.thresholdsVector.get(0);
    int hmax = this.thresholdsVector.get(1);
    int smin = this.thresholdsVector.get(2);
    int smax = this.thresholdsVector.get(3);
    int vmin = this.thresholdsVector.get(4);
    int vmax = this.thresholdsVector.get(5);

    Mat maskImage = new Mat(this.objectImage.size(), CvType.CV_8UC1);
    Core.inRange(hsvImage, new Scalar(hmin, smin, vmin), new Scalar(hmax, smax, vmax), maskImage);

    // Taking the hue channel of the image
    Mat hueImage = new Mat(hsvImage.size(), hsvImage.depth());

    MatOfInt fromto = new MatOfInt(0, 0);
    Core.mixChannels(Arrays.asList(hsvImage), Arrays.asList(hueImage), fromto);

    // Backprojecting the histogram over that hue channel image
    MatOfFloat ranges = new MatOfFloat(0, 180);
    MatOfInt channels = new MatOfInt(0);

    Imgproc.calcBackProject(Arrays.asList(hueImage), channels, this.objectHistogram, this.backprojectionImage,
            ranges, 1);//from   ww w .j  ava2 s .com

    Core.bitwise_and(backprojectionImage, maskImage, backprojectionImage);

}