Example usage for org.opencv.core Mat put

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

Introduction

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

Prototype

public int put(int row, int col, byte[] data) 

Source Link

Usage

From source file:org.vinesrobotics.bot.utils.opencv.ColorBlobDetector.java

License:Open Source License

public void setHsvColor(Scalar hsvColor) {
    double minH = (hsvColor.val[0] >= mColorRadius.val[0]) ? hsvColor.val[0] - mColorRadius.val[0] : 0;
    double maxH = (hsvColor.val[0] + mColorRadius.val[0] <= 255) ? hsvColor.val[0] + mColorRadius.val[0] : 255;

    mLowerBound.val[0] = minH;
    mUpperBound.val[0] = maxH;

    mLowerBound.val[1] = hsvColor.val[1] - mColorRadius.val[1];
    mUpperBound.val[1] = hsvColor.val[1] + mColorRadius.val[1];

    mLowerBound.val[2] = hsvColor.val[2] - mColorRadius.val[2];
    mUpperBound.val[2] = hsvColor.val[2] + mColorRadius.val[2];

    mLowerBound.val[3] = 0;
    mUpperBound.val[3] = 255;

    Mat spectrumHsv = new Mat(1, (int) Math.abs(maxH - minH), CvType.CV_8UC3);

    mBaseColor = hsvColor;//from   w w  w .ja va  2  s  . c  o  m

    for (int j = 0; j < maxH - minH; j++) {
        byte[] tmp = { (byte) (minH + j), (byte) 255, (byte) 255 };
        spectrumHsv.put(0, j, tmp);
    }

    Imgproc.cvtColor(spectrumHsv, mSpectrum, Imgproc.COLOR_HSV2RGB_FULL, 4);
}

From source file:overwatchteampicker.OverwatchTeamPicker.java

public static ReturnValues findImage(String template, String source, int flag) {
    File lib = null;/*  w  ww.ja va2 s. c  om*/
    BufferedImage image = null;
    try {
        image = ImageIO.read(new File(source));
    } catch (Exception e) {
        e.printStackTrace();
    }

    String os = System.getProperty("os.name");
    String bitness = System.getProperty("sun.arch.data.model");

    if (os.toUpperCase().contains("WINDOWS")) {
        if (bitness.endsWith("64")) {
            lib = new File("C:\\Users\\POWERUSER\\Downloads\\opencv\\build\\java\\x64\\"
                    + System.mapLibraryName("opencv_java2413"));
        } else {
            lib = new File("libs//x86//" + System.mapLibraryName("opencv_java2413"));
        }
    }
    System.load(lib.getAbsolutePath());
    String tempObject = "images\\hero_templates\\" + template + ".png";
    String source_pic = source;
    Mat objectImage = Highgui.imread(tempObject, Highgui.CV_LOAD_IMAGE_GRAYSCALE);
    Mat sceneImage = Highgui.imread(source_pic, Highgui.CV_LOAD_IMAGE_GRAYSCALE);

    MatOfKeyPoint objectKeyPoints = new MatOfKeyPoint();
    FeatureDetector featureDetector = FeatureDetector.create(FeatureDetector.SURF);
    featureDetector.detect(objectImage, objectKeyPoints);
    KeyPoint[] keypoints = objectKeyPoints.toArray();
    MatOfKeyPoint objectDescriptors = new MatOfKeyPoint();
    DescriptorExtractor descriptorExtractor = DescriptorExtractor.create(DescriptorExtractor.SURF);
    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);
    Features2d.drawKeypoints(objectImage, objectKeyPoints, outputImage, newKeypointColor, 0);

    // Match object image with the scene image
    MatOfKeyPoint sceneKeyPoints = new MatOfKeyPoint();
    MatOfKeyPoint sceneDescriptors = new MatOfKeyPoint();
    featureDetector.detect(sceneImage, sceneKeyPoints);
    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, 25);

    List<MatOfDMatch> matches = new LinkedList<MatOfDMatch>();
    DescriptorMatcher descriptorMatcher = DescriptorMatcher.create(DescriptorMatcher.FLANNBASED);
    descriptorMatcher.knnMatch(objectDescriptors, sceneDescriptors, matches, 2);

    LinkedList<DMatch> goodMatchesList = new LinkedList<DMatch>();

    float nndrRatio = .78f;

    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() >= 4) {

        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() });

        Core.perspectiveTransform(obj_corners, scene_corners, homography);

        Mat img = Highgui.imread(source_pic, 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, 255), 4);
        Core.line(img, new Point(scene_corners.get(1, 0)), new Point(scene_corners.get(2, 0)),
                new Scalar(255, 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);

        MatOfDMatch goodMatches = new MatOfDMatch();
        goodMatches.fromList(goodMatchesList);

        Features2d.drawMatches(objectImage, objectKeyPoints, sceneImage, sceneKeyPoints, goodMatches,
                matchoutput, matchestColor, newKeypointColor, new MatOfByte(), 2);
        if (new Point(scene_corners.get(0, 0)).x < new Point(scene_corners.get(1, 0)).x
                && new Point(scene_corners.get(0, 0)).y < new Point(scene_corners.get(2, 0)).y) {
            System.out.println("found " + template);
            Highgui.imwrite("points.jpg", outputImage);
            Highgui.imwrite("matches.jpg", matchoutput);
            Highgui.imwrite("final.jpg", img);

            if (flag == 0) {
                ReturnValues retVal = null;
                int y = (int) new Point(scene_corners.get(3, 0)).y;
                int yHeight = (int) new Point(scene_corners.get(3, 0)).y
                        - (int) new Point(scene_corners.get(2, 0)).y;
                if (y < image.getHeight() * .6) { //if found hero is in upper half of image then return point 3,0
                    retVal = new ReturnValues(y + (int) (image.getHeight() * .01), yHeight);
                } else { //if found hero is in lower half of image then return point 2,0
                    y = (int) new Point(scene_corners.get(2, 0)).y;
                    retVal = new ReturnValues(y + (int) (image.getHeight() * .3), yHeight);
                }
                return retVal;
            } else if (flag == 1) {
                int[] xPoints = new int[4];
                int[] yPoints = new int[4];

                xPoints[0] = (int) (new Point(scene_corners.get(0, 0)).x);
                xPoints[1] = (int) (new Point(scene_corners.get(1, 0)).x);
                xPoints[2] = (int) (new Point(scene_corners.get(2, 0)).x);
                xPoints[3] = (int) (new Point(scene_corners.get(3, 0)).x);

                yPoints[0] = (int) (new Point(scene_corners.get(0, 0)).y);
                yPoints[1] = (int) (new Point(scene_corners.get(1, 0)).y);
                yPoints[2] = (int) (new Point(scene_corners.get(2, 0)).y);
                yPoints[3] = (int) (new Point(scene_corners.get(3, 0)).y);

                ReturnValues retVal = new ReturnValues(xPoints, yPoints);
                return retVal;

            }
        }
    }
    return null;

}

From source file:pipeline.TextRegion.java

public static String SplitFiles(File fileIn) {
    String result = "";
    try {/*  w  w  w .j a va2s  .  co m*/
        String nomeFile = fileIn.getName();
        //System.out.println("il nome del file  "+nomeFile);
        FileInputStream in = new FileInputStream("src/pipeline/receivedImg/" + nomeFile);
        JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(in);
        BufferedImage image = decoder.decodeAsBufferedImage();
        in.close();

        TextRecognition myget = new TextRecognition(image);
        LinkedList boxes = myget.getTextBoxes();

        String nomeFileOut = "src/pipeline/outputImg/" + Global.getJPGNameFile() + " out.jpg";
        FileOutputStream out = new FileOutputStream(nomeFileOut);
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
        encoder.encode(myget.isolateText(boxes));
        out.close();

        //parte con opencv

        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
        File f = new File("src/pipeline/receivedImg/" + nomeFile);
        BufferedImage imageFile = ImageIO.read(f);

        byte[] data = ((DataBufferByte) imageFile.getRaster().getDataBuffer()).getData();
        Mat mat = new Mat(imageFile.getHeight(), imageFile.getWidth(), CvType.CV_8UC3);
        mat.put(0, 0, data);
        int tolleranza = 15;

        for (int i = 0; i < boxes.size(); i++) {
            TextRegion app = (TextRegion) boxes.get(i);
            //             System.out.println("RIGA: "+i+"  -> "+app.x1 +" "+app.x2 +" "+app.y1 +" "+app.y2 +" ");
            Rect roi1 = new Rect(app.x1 - tolleranza, app.y1 - tolleranza, app.x2 - app.x1 + tolleranza,
                    app.y2 - app.y1 + 2 * tolleranza);
            Mat mat1 = new Mat(mat, roi1);

            byte[] data1 = new byte[mat1.rows() * mat1.cols() * (int) (mat1.elemSize())];
            mat1.get(0, 0, data1);
            BufferedImage image1 = new BufferedImage(mat1.cols(), mat1.rows(), BufferedImage.TYPE_3BYTE_BGR);
            image1.getRaster().setDataElements(0, 0, mat1.cols(), mat1.rows(), data1);

            String nomeFileUscrita = "src/pipeline/outputImg/" + i + Global.getJPGNameFile() + " uscita.jpg";
            File tmp = new File(nomeFileUscrita);
            File output = new File(nomeFileUscrita);
            ImageIO.write(image1, "jpg", output);
            result += (i + 1) + ")" + OCR_Processing.performOCR_String2Text(output);
            tmp.delete();

        }
        f.delete();
        File foo = new File(nomeFileOut);
        foo.delete();

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

    return result;

}

From source file:processdata.depthDataProcessingUtilities.java

/**
* converts depth data to opencv Mat object leaving depth values that are only within min and max thresholds
* @param path/*from w  w  w.  j a va  2s . c  o  m*/
* @param minThreshold
* @param maxThreshold
* @return
* @throws FileNotFoundException
*/
public static Mat processDepthDataFile(String path, int minThreshold, int maxThreshold)
        throws FileNotFoundException {
    File depthData = new File(path);

    double[][] depthDataArray = new double[1][217088];

    //read depth data into array
    int count = 0;

    inDepthDataFile = new Scanner(depthData);//.useDelimiter(",\\s*");

    while (inDepthDataFile.hasNext()) {
        String currentStr = inDepthDataFile.nextLine();
        if (!currentStr.isEmpty())
            depthDataArray[0][count++] = Double.parseDouble(currentStr);
    }

    double depthDataMatrix[][] = new double[512][424];

    depthDataMatrix = reshape(depthDataArray, 512, 424);

    Mat matDepthDataMatrix = new Mat(512, 424, CvType.CV_64F);

    //cut-off the remaining depth values
    for (int i = 0; i < depthDataMatrix.length; i++) {
        for (int j = 0; j < depthDataMatrix[0].length; j++) {
            if (depthDataMatrix[i][j] > maxThreshold || depthDataMatrix[i][j] < minThreshold)
                depthDataMatrix[i][j] = 0;
        }
    }

    //find max value
    double max = 0;

    for (int i = 0; i < depthDataMatrix.length; i++) {
        for (int j = 0; j < depthDataMatrix[0].length; j++) {
            if (depthDataMatrix[i][j] > max)
                max = depthDataMatrix[i][j];
        }
    }

    //FILL THE DEPTH MATRIX
    //System.out.println("Max Element "+ max);

    for (int i = 0; i < depthDataMatrix.length; i++) {
        for (int j = 0; j < depthDataMatrix[0].length; j++) {
            matDepthDataMatrix.put(i, j, depthDataMatrix[i][j] / max * 255.0);
        }
    }

    //      //printout the depth matrix
    //      for(int i = 0;i<depthDataMatrix.length;i++){
    //          for(int j = 0;j<depthDataMatrix[0].length;j++){
    //              System.out.print(depthDataMatrix[i][j]+"\t");
    //          }
    //        System.out.println();
    //      }
    //      

    //apply colormap to visualize
    Mat processedMathDepthImage = new Mat(matDepthDataMatrix.size(), CvType.CV_8U);
    matDepthDataMatrix.convertTo(processedMathDepthImage, CvType.CV_8UC1);

    Core.transpose(processedMathDepthImage, processedMathDepthImage);
    org.opencv.contrib.Contrib.applyColorMap(processedMathDepthImage, processedMathDepthImage,
            org.opencv.contrib.Contrib.COLORMAP_JET);

    return processedMathDepthImage;
}

From source file:processdata.ExperimentalDataProcessingUI.java

public static Mat BufferedImage2Mat(BufferedImage image) {
    //source: http://stackoverflow.com/questions/18581633/fill-in-and-detect-contour-rectangles-in-java-opencv
    byte[] data = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
    Mat mat = new Mat(image.getHeight(), image.getWidth(), CvType.CV_8UC3);
    mat.put(0, 0, data);
    return mat;//from   w  ww.  j a v  a  2  s  .  co  m
}

From source file:processdata.ProcessImages.java

/**
 * //  w w w.j  a  v  a  2  s.c o  m
 * @param imgFile
 * @return
 * @throws IOException
 * @throws ClassNotFoundException
 */
public static Mat reconstructImage(File imgFile, int index) {
    Mat mat = new Mat();

    FileInputStream fis;
    try {
        fis = new FileInputStream(imgFile.getPath());
        ObjectInputStream ois = new ObjectInputStream(fis);
        byte[] data = (byte[]) ois.readObject();

        if (index == 1) {
            mat = new Mat(1080, 1920, CvType.CV_8UC3);
        }
        if (index == 2) {
            mat = new Mat(424, 512, CvType.CV_8UC3);
        }

        mat.put(0, 0, data);

        ois.close();
        fis.close();

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();

    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return mat;

}

From source file:qupath.opencv.classify.NeuralNetworksClassifier.java

License:Open Source License

@Override
protected void createAndTrainClassifier() {
    // Create the required Mats
    int nMeasurements = measurements.size();
    Mat matTraining = new Mat(arrayTraining.length / nMeasurements, nMeasurements, CvType.CV_32FC1);
    matTraining.put(0, 0, arrayTraining);

    // Parse parameters
    ParameterList params = getParameterList();
    int nHidden = Math.max(2, params.getIntParameterValue("nHidden"));
    int termIterations = params.getIntParameterValue("termCritMaxIterations");
    double termEPS = params.getDoubleParameterValue("termCritEPS");
    TermCriteria crit = createTerminationCriteria(termIterations, termEPS);

    // Create & train the classifier
    classifier = createClassifier();/*  w  ww. ja va2 s  .  com*/
    ANN_MLP nnet = (ANN_MLP) classifier;
    System.out.println(nnet.getLayerSizes());
    Mat layers = new Mat(3, 1, CvType.CV_32F);
    int n = arrayTraining.length / nMeasurements;
    //      layers.put(0, 0, new float[]{nMeasurements, nHidden, pathClasses.size()});
    layers.put(0, 0, nMeasurements);
    layers.put(1, 0, nHidden); // Number of hidden layers
    layers.put(2, 0, pathClasses.size());
    if (crit != null)
        nnet.setTermCriteria(crit);
    else
        crit = nnet.getTermCriteria();
    nnet.setLayerSizes(layers);
    //         matResponses.convertTo(matResponses, CvType.CV_32F);
    Mat matResponses = new Mat(n, pathClasses.size(), CvType.CV_32F);
    matResponses.setTo(new Scalar(0));
    for (int i = 0; i < n; i++) {
        matResponses.put(i, arrayResponses[i], 1);
    }
    nnet.setActivationFunction(ANN_MLP.SIGMOID_SYM, 1, 1);
    nnet.train(matTraining, Ml.ROW_SAMPLE, matResponses);

    //      lastDescription = getName() + "\n\nMain parameters:\n  " + DefaultPluginWorkflowStep.getParameterListJSON(params, "\n  ") + "\n\nTermination criteria:\n  " + crit.toString();
}

From source file:qupath.opencv.classify.OpenCvClassifier.java

License:Open Source License

protected void createAndTrainClassifier() {

    // Create the required Mats
    int nMeasurements = measurements.size();

    Mat matTraining = new Mat(arrayTraining.length / nMeasurements, nMeasurements, CvType.CV_32FC1);
    matTraining.put(0, 0, arrayTraining);
    Mat matResponses = new Mat(arrayResponses.length, 1, CvType.CV_32SC1);
    matResponses.put(0, 0, arrayResponses);

    //      // Clear any existing classifier
    //      if (classifier != null)
    //         classifier.clear();

    logger.info("Training size: " + matTraining.size());
    logger.info("Responses size: " + matResponses.size());

    // Create & train the classifier
    try {//from   w  ww  .  jav  a 2  s.  com
        classifier = createClassifier();
        classifier.train(matTraining, Ml.ROW_SAMPLE, matResponses);
    } catch (CvException e) {
        // For reasons I haven't yet discerned, sometimes OpenCV throws an exception with the following message:
        // OpenCV Error: Assertion failed ((int)_sleft.size() < n && (int)_sright.size() < n) in calcDir, file /tmp/opencv320150620-1681-1u5iwhh/opencv-3.0.0/modules/ml/src/tree.cpp, line 1190
        // With one sample fewer, it can often recover... so attempt that, rather than failing miserably...
        //         logger.error("Classifier training error", e);
        logger.info("Will attempt retraining classifier with one sample fewer...");
        matTraining = matTraining.rowRange(0, matTraining.rows() - 1);
        matResponses = matResponses.rowRange(0, matResponses.rows() - 1);
        classifier = createClassifier();
        classifier.train(matTraining, Ml.ROW_SAMPLE, matResponses);
    }

    matTraining.release();
    matResponses.release();

    logger.info("Classifier trained with " + arrayResponses.length + " samples");
}

From source file:qupath.opencv.classify.OpenCvClassifier.java

License:Open Source License

@Override
public int classifyPathObjects(Collection<PathObject> pathObjects) {

    int counter = 0;
    float[] array = new float[measurements.size()];
    Mat samples = new Mat(1, array.length, CvType.CV_32FC1);

    Mat results = new Mat();

    for (PathObject pathObject : pathObjects) {
        MeasurementList measurementList = pathObject.getMeasurementList();
        int idx = 0;
        for (String m : measurements) {
            double value = measurementList.getMeasurementValue(m);

            if (normScale != null && normOffset != null)
                value = (value + normOffset[idx]) * normScale[idx];

            array[idx] = (float) value;
            idx++;/* w  w w  . ja v  a 2  s  .c o  m*/
        }

        samples.put(0, 0, array);

        try {
            setPredictedClass(classifier, pathClasses, samples, results, pathObject);
            //            float prediction = classifier.predict(samples);
            //            
            ////            float prediction2 = classifier.predict(samples, results, StatModel.RAW_OUTPUT);
            //            float prediction2 = classifier.predict(samples, results, StatModel.RAW_OUTPUT);
            //            
            //            pathObject.setPathClass(pathClasses.get((int)prediction), prediction2);
        } catch (Exception e) {
            pathObject.setPathClass(null);
            logger.trace("Error with samples: " + samples.dump());
            //               e.printStackTrace();
        }
        //         }
        counter++;
    }

    samples.release();
    results.release();

    return counter;
}

From source file:qupath.opencv.processing.OpenCVTools.java

License:Open Source License

/**
 * Convert an RGB image to an OpenCV Mat.
 * //  w ww .  ja v  a2s  .  com
 * @param img
 * @return
 */
public static Mat imageToMat(BufferedImage img) {
    //      img.getRaster().getDataBuffer()
    //      img.getRaster().getDataBuffer().getDataType()
    //      byte[] data = ((DataBufferByte) img.getRaster().getDataBuffer()).getData();
    int[] data = ((DataBufferInt) img.getRaster().getDataBuffer()).getData();

    ByteBuffer byteBuffer = ByteBuffer.allocate(data.length * 4);
    IntBuffer intBuffer = byteBuffer.asIntBuffer();
    intBuffer.put(data);
    byte[] dataBytes = byteBuffer.array();

    //      byte[] dataBytes = new byte[data.length * 4];
    //      int j = 0;
    //       for (int x : data) {
    //          dataBytes[j] = (byte) ((x >>> 0) & 0xff);           
    //          dataBytes[j] = (byte) ((x >>> 8) & 0xff);
    //          dataBytes[j] = (byte) ((x >>> 16) & 0xff);
    //          dataBytes[j] = (byte) ((x >>> 24) & 0xff);
    //           j++;
    //       }

    //      Mat mat = new Mat(img.getHeight(), img.getWidth(), CvType.CV_8UC3);
    Mat mat = new Mat(img.getHeight(), img.getWidth(), CvType.CV_8UC4);
    mat.put(0, 0, dataBytes);
    return mat;
}