Example usage for org.opencv.core Mat get

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

Introduction

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

Prototype

public double[] get(int row, int col) 

Source Link

Usage

From source file:SearchSystem.SearchingAlgorithms.CBIRSearchAlgorithm.java

public double[] extractFeatures(Mat image) {
    //       Imgproc.cvtColor(image, image, Imgproc.COLOR_BGR2HSV);
    int rows = image.rows();
    int cols = image.cols();
    int blockHeigth = rows / numberBlocksHeigth;
    int blockWidth = cols / numberBlocksWidth;
    int sizeOfBlocks = blockHeigth * blockWidth;
    System.out.println(sizeOfBlocks);
    rows = numberBlocksHeigth * blockHeigth;
    cols = numberBlocksWidth * blockWidth;
    Imgproc.resize(image, image, new Size(cols, rows));

    double[] vectors = new double[numberBlocksWidth * numberBlocksHeigth * 6]; // 3 channels, average and variance for each
    int counter = 0;

    for (int i = 0; i < rows; i += blockHeigth)
        for (int j = 0; j < cols; j += blockWidth) {
            for (int ii = i; ii < i + blockHeigth; ++ii)
                for (int jj = j; jj < j + blockWidth; ++jj) {
                    double pixel[] = image.get(ii, jj);
                    vectors[counter] += pixel[0]; // H mean
                    vectors[counter + 1] += pixel[1]; // S mean
                    vectors[counter + 2] += pixel[2]; // V mean
                }/*from   w w  w  .  ja  v  a  2 s.co m*/
            vectors[counter] /= sizeOfBlocks; // H mean
            vectors[counter + 1] /= sizeOfBlocks; // S mean
            vectors[counter + 2] /= sizeOfBlocks; // V mean

            for (int ii = i; ii < i + blockHeigth; ++ii)
                for (int jj = j; jj < j + blockWidth; ++jj) {
                    double pixel[] = image.get(ii, jj);
                    vectors[counter + 3] += Math.pow(pixel[0] - vectors[counter], 2); // H variation
                    vectors[counter + 4] += Math.pow(pixel[1] - vectors[counter + 1], 2); // S variation
                    vectors[counter + 5] += Math.pow(pixel[2] - vectors[counter + 2], 2); // V varation
                }
            vectors[counter + 3] = Math.sqrt(vectors[counter + 3] / sizeOfBlocks); // H variation
            vectors[counter + 4] = Math.sqrt(vectors[counter + 4] / sizeOfBlocks); // S variation
            vectors[counter + 5] = Math.sqrt(vectors[counter + 5] / sizeOfBlocks); // V varation

            counter += 6;
        }
    image.release();
    return vectors;
}

From source file:servershootingstar.BallDetector.java

public static String getAngleFromRobot(int input) {
    System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
    System.out.println("before");
    int point;/*from   www .j a  v  a 2 s .  com*/
    try {
        Mat frame = new Mat();
        System.out.println("AAAAAA");
        Mat originalFrame = new Mat();
        System.out.println("BBBBBB");
        VideoCapture videoCapture = new VideoCapture(0);
        System.out.println("CCCCCCCC");
        videoCapture.read(originalFrame);
        //                System.out.println("original" + originalFrame.dump());
        //                initSwing(originalFrame);
        int workaround = 20;
        while (workaround > 0) {
            System.out.println("workaround " + workaround);
            videoCapture.read(originalFrame);
            //                    System.out.println(originalFrame.dump() + originalFrame.dump().length());
            workaround--;
        }
        //                Imgcodecs.imwrite("C:\\Users\\Goran\\Desktop\\Goran.jpg", originalFrame);
        Mat cropped = originalFrame.submat(originalFrame.rows() / 4, originalFrame.rows() / 4 * 3, 0,
                originalFrame.cols());
        initSwing(cropped);
        Imgproc.cvtColor(cropped, frame, Imgproc.COLOR_BGR2HSV);

        // insert lower and upper bounds for colors
        Scalar greenLowerB = new Scalar(20, 55, 55);
        Scalar greenUpperB = new Scalar(40, 255, 255);

        Scalar redLowerB = new Scalar(160, 100, 35);
        Scalar red1LowerB = new Scalar(0, 100, 35);

        Scalar redUpperB = new Scalar(180, 255, 255);
        Scalar red1UpperB = new Scalar(20, 255, 255);

        Scalar blueLowerB = new Scalar(100, 100, 35);
        Scalar blueUpperB = new Scalar(120, 255, 155);

        Mat mask = new Mat();

        if (input == 1) {
            Mat otherMask = new Mat();
            Core.inRange(frame, redLowerB, redUpperB, mask);
            Core.inRange(frame, red1LowerB, red1UpperB, otherMask);
            Core.bitwise_or(mask, otherMask, mask);
        } else if (input == 2) {
            Core.inRange(frame, greenLowerB, greenUpperB, mask);
        } else {
            Core.inRange(frame, blueLowerB, blueUpperB, mask);
        }
        Imgproc.erode(mask, mask, Imgproc.getStructuringElement(Imgproc.CV_SHAPE_ELLIPSE, new Size(5, 5)));
        Imgproc.erode(mask, mask, Imgproc.getStructuringElement(Imgproc.CV_SHAPE_ELLIPSE, new Size(5, 5)));
        Imgproc.erode(mask, mask, Imgproc.getStructuringElement(Imgproc.CV_SHAPE_ELLIPSE, new Size(5, 5)));
        Imgproc.erode(mask, mask, Imgproc.getStructuringElement(Imgproc.CV_SHAPE_ELLIPSE, new Size(5, 5)));

        int minX = Integer.MAX_VALUE, maxX = Integer.MIN_VALUE, minY = Integer.MAX_VALUE,
                maxY = Integer.MIN_VALUE;
        for (int i = 0; i < mask.rows(); ++i) {
            for (int j = 0; j < mask.cols(); ++j) {
                double value = mask.get(i, j)[0];
                //System.out.println(value);
                if (value > 1) {
                    minX = Math.min(minX, i);
                    maxX = Math.max(maxX, i);
                    minY = Math.min(minY, j);
                    maxY = Math.max(maxY, j);
                }
            }
        }

        Imgproc.circle(mask, new Point((maxY + minY) / 2, (minX + maxX) / 2), 3, new Scalar(0, 0, 0));
        initSwing(mask);

        point = (minY + maxY) / 2;

        point = point - 320;

        cos = point / 320.0;
        System.out.println("OK");
    } catch (Exception ex) {
        point = (new Random()).nextInt(640);
        cos = -1;
        System.out.println("error imase, davam random brojka: " + point);
        ex.printStackTrace();

    }

    //            System.out.println();
    //            System.out.println("tockata u granica od [-320, 320]");
    //            System.out.println(point);
    //            System.out.println("cosinus vrednost");
    //            System.out.println(cos);
    //            System.out.println();
    System.out.println("cos = " + cos);
    if (cos == -1) {
        return "-1";
    }
    int res = (int) (2 * Math.toDegrees(Math.acos(cos)) / 3);
    System.out.println("Res: " + res);
    return String.valueOf(res);
}

From source file:servlets.FillAreaByScribble.java

public static int filterPoints(ArrayList<Point> points, Mat mask) {
    int removals = 0;
    for (int i = 0; i < points.size(); i++) {
        Point point = points.get(i);
        int col = (int) point.x;
        int row = (int) point.y;
        double[] value = mask.get(row, col);
        if (value[0] != 0) {
            //                System.out.println("Removing");
            points.remove(point);/*w w w. j  a  v  a  2  s .c  o  m*/
            i--;
            removals++;
        }
    }
    return removals;
}

From source file:servlets.SampleColorsFromImageObject.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from ww w .jav  a  2 s.co  m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {

        String imageForTextRecognition = request.getParameter("imageForTextRecognition") + ".png";

        Mat image = ImageUtils.loadImage(imageForTextRecognition, request);

        String samplingPoints = request.getParameter("samplingPoints");

        ArrayList<int[]> results = new ArrayList<>();

        Gson gson = new Gson();
        Point[] samplingPositions = gson.fromJson(samplingPoints, Point[].class);
        for (Point point : samplingPositions) {

            int row = (int) point.y;
            int col = (int) point.x;
            int totalCols = image.cols();
            int totalRows = image.rows();

            int b = -1;
            int g = -1;
            int r = -1;

            if (row >= 0 && col >= 0 && col < totalCols && row < totalRows) {
                double[] color = image.get(row, col);
                b = (int) color[0];
                g = (int) color[1];
                r = (int) color[2];
            }

            int[] intColor = { r, g, b };
            results.add(intColor);

            System.out.println("Color at: (" + row + ", " + col + "): " + r + " " + g + " " + b);

        }

        String jsonResponse = gson.toJson(results);

        out.println(jsonResponse);

    }
}

From source file:simeav.filtros.instanciaciones.DetectorModulosEstandar.java

@Override
public Mat detectarModulos(Mat original, Diagrama diagrama) {
    Imgproc.blur(original, original, new Size(15, 15));
    original = Utils.dilate(original);//from  w w  w  .j av a  2  s.c o  m
    Mat jerarquia = new Mat();
    ArrayList<MatOfPoint> contornos = new ArrayList<>();
    Imgproc.findContours(original.clone(), contornos, jerarquia, Imgproc.RETR_CCOMP,
            Imgproc.CHAIN_APPROX_SIMPLE);
    ArrayList<MatOfPoint> cp = new ArrayList<>(contornos.size());
    Map<Integer, Rect> rectangulos = new HashMap<>();
    Integer id_cuadrado = 0;
    Mat resultado = Mat.zeros(original.size(), CvType.CV_8U);
    for (int i = contornos.size() - 1; i >= 0; i--) {
        if (jerarquia.get(0, i)[3] > -1) {
            MatOfPoint2f contorno2f = new MatOfPoint2f();
            contorno2f.fromList(contornos.get(i).toList());
            MatOfPoint2f c = new MatOfPoint2f();
            Imgproc.approxPolyDP(contorno2f, c, 3, true);
            cp.add(new MatOfPoint(c.toArray()));
            int lados = cp.get(cp.size() - 1).height();
            if ((4 <= lados) && lados < 12) {
                rectangulos.put(id_cuadrado, Imgproc.boundingRect(new MatOfPoint(c.toArray())));
                Point tl = new Point(rectangulos.get(id_cuadrado).tl().x - 20,
                        rectangulos.get(id_cuadrado).tl().y - 20);
                Point br = new Point(rectangulos.get(id_cuadrado).br().x + 20,
                        rectangulos.get(id_cuadrado).br().y + 20);
                Core.rectangle(resultado, tl, br, new Scalar(255, 255, 255), -1);
                diagrama.addModulo(id_cuadrado, new Rect(tl, br));
                Imgproc.drawContours(resultado, contornos, i, new Scalar(0, 0, 0), -1);
                id_cuadrado++;
            }
        }
    }
    return resultado;
}

From source file:spring2017ip.ConvolutionDemo.java

public Mat convolute(Mat inputImage, double kernel[][], double anchorX, double anchorY) {
    Mat outputImage = new Mat(inputImage.rows(), inputImage.cols(), inputImage.type());

    // have to fix this code so that it works for any sized kernel
    for (int i = 1; i < inputImage.rows() - 1; i++)
        for (int j = 1; j < inputImage.cols() - 1; j++) {
            double sum = 0;

            for (int r = 0; r < kernel.length; r++)
                for (int c = 0; c < kernel[r].length; c++) {
                    double pixel[] = inputImage.get(i - kernel.length / 2 + r, j - kernel[0].length / 2 + c);
                    double product = kernel[r][c] * pixel[0];
                    sum = sum + product;
                }/*  w  w w .  j a v a2 s  . c o  m*/

            outputImage.put(i, j, sum);
        }
    return outputImage;
}

From source file:spring2017ip.ConvolutionDemo.java

public Mat combineGxGy(Mat gx, Mat gy) {
    Mat outputImage = new Mat(gx.rows(), gx.cols(), gx.type());
    for (int r = 0; r < gx.height(); r++)
        for (int c = 0; c < gx.width(); c++) {
            double x[] = gx.get(r, c);
            double y[] = gy.get(r, c);
            double m = Math.sqrt(x[0] * x[0] + y[0] * y[0]);
            outputImage.put(r, c, m);/* w w  w .  j ava 2s  .  co  m*/
        }
    return outputImage;
}

From source file:uk.ac.horizon.aestheticodes.controllers.MarkerCode.java

License:Open Source License

/**
 * This function determines whether the input node is a valid branch. It is a valid branch if it contains zero or more dark regions.
 *
 * @param branchIndex Node index from the hierarchy.
 * @param hierarchy   This contains the contours or components hierarchy.
 * @return Returns branch status.//from   www  .  j  a va 2  s .co  m
 */
static int getRegionValue(int branchIndex, Mat hierarchy, int regionMaxValue) {
    double[] nodes = hierarchy.get(0, branchIndex);
    int currentLeafIndex = (int) nodes[FIRST_NODE];
    if (currentLeafIndex < 0) {
        return 0;
    }

    int leafCount = 0;
    //loop until there is a leaf node.
    while (currentLeafIndex >= 0) {
        if (verifyLeaf(currentLeafIndex, hierarchy)) {
            leafCount++;
            //get next leaf node.
            nodes = hierarchy.get(0, currentLeafIndex);
            currentLeafIndex = (int) nodes[NEXT_NODE];

            if (leafCount > regionMaxValue) {
                return REGION_INVALID;
            }
        } else {
            return REGION_INVALID;
        }
    }

    return leafCount;
}

From source file:uk.ac.horizon.aestheticodes.controllers.MarkerCode.java

License:Open Source License

/**
 * This function detects whether a particular node is a d-touch marker. A d-touch contains one dark (black) region which is called the root. A root can have
 * one or more light (white) regions. These light regions are called branches. Each branch can contain zero or more dark (black) regions and these dark regions
 * are called leaves. If a branch has no leaf then it is called an empty branch. In conclusion Root==> 1 or more branches ==> 0 or more leaves.
 *
 * @param rootIndex The index of the node which needs to be identified as the root. It is used to access the hierarchy of this node from the hierarchy parameter.    *
 * @param hierarchy This contains the contours or components hierarchy using opencv findContours function.
 * @return returns true if the root node is a valid d-touch marker otherwise returns false.
 *//*www  .  j av a  2s .  co  m*/
static MarkerCode findMarker(Mat hierarchy, int rootIndex, Experience experience) {
    double[] nodes = hierarchy.get(0, rootIndex);
    int currentRegionIndex = (int) nodes[MarkerCode.FIRST_NODE];
    if (currentRegionIndex < 0) {
        return null;
    }

    int regions = 0;
    int emptyRegions = 0;
    List<Integer> codes = null;

    //loop until there is a branch node.
    while (currentRegionIndex >= 0) {
        //verify current branch.
        final int regionValue = MarkerCode.getRegionValue(currentRegionIndex, hierarchy,
                experience.getMaxRegionValue());
        //if branch is valid or empty.
        if (regionValue == MarkerCode.REGION_INVALID) {
            return null;
        }

        regions++;
        if (regions > experience.getMaxRegions()) {
            return null;
        }
        if (regionValue == MarkerCode.REGION_EMPTY) {
            emptyRegions++;
            if (emptyRegions > experience.getMaxEmptyRegions()) {
                return null;
            }
        } else {
            if (codes == null) {
                codes = new ArrayList<>();
            }
            codes.add(regionValue);
        }
        //get next node.
        nodes = hierarchy.get(0, currentRegionIndex);
        currentRegionIndex = (int) nodes[MarkerCode.NEXT_NODE];
    }

    //Marker should have at least one non-empty branch. If all branches are empty then return false.
    if ((emptyRegions - regions) == 0) {
        return null;
    }

    if (experience.isValidMarker(codes)) {
        Collections.sort(codes);
        return new MarkerCode(codes, rootIndex);
    }

    return null;
}

From source file:uk.ac.horizon.aestheticodes.controllers.MarkerCode.java

License:Open Source License

/**
 * This functions determines if the node is a valid leaf. It is a valid leaf if it does not have any child nodes.
 *///from  w  ww. j  a v a 2s  . co m
private static Boolean verifyLeaf(int leafIndex, Mat hierarchy) {
    //Get nodes of branch index.
    double[] nodes = hierarchy.get(0, leafIndex);
    //check if there is no child node.
    return nodes[FIRST_NODE] < 0;
}