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:SearchSystem.SearchingAlgorithms.CBIRSearchAlgorithm.java

@Override
public byte extractFeatures(Mat image, String outputFile) {
    int rows = image.rows();
    int cols = image.cols();
    int blockHeigth = rows / numberBlocksHeigth;
    int blockWidth = cols / numberBlocksWidth;
    int sizeOfBlocks = blockHeigth * blockWidth;
    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  . j av a2s.com*/
            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 variation
                }
            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 variation

            counter += 6;
        }

    writeVectorToFile(vectors, outputFile);
    image.release();
    return 1;
}

From source file:SearchSystem.SearchingAlgorithms.CBIRSearchAlgorithm.java

public byte extractFeaturesHUE(Mat image, String outputFile) {
    int rows = image.rows();
    int cols = image.cols();
    int blockHeigth = rows / numberBlocksHeigth;
    int blockWidth = cols / numberBlocksWidth;
    int sizeOfBlocks = blockHeigth * blockWidth;
    rows = numberBlocksHeigth * blockHeigth;
    cols = numberBlocksWidth * blockWidth;
    Imgproc.resize(image, image, new Size(cols, rows));
    Imgproc.cvtColor(image, image, Imgproc.COLOR_BGR2HSV);

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

    double Hmean = 0;
    double Smean = 0;
    double Vmean = 0;

    for (int i = 0; i < rows; i += blockHeigth)
        for (int j = 0; j < cols; j += blockWidth) {
            double pixel[] = image.get(i, j);
            for (int ii = i; ii < i + blockHeigth; ++ii)
                for (int jj = j; jj < j + blockWidth; ++jj) {
                    pixel = image.get(ii, jj);
                    if (vectors[counter] < pixel[0])
                        vectors[counter] = pixel[0]; // H max
                    if (vectors[counter + 1] < pixel[1])
                        vectors[counter + 1] = pixel[1]; // H max
                    if (vectors[counter + 2] < pixel[2])
                        vectors[counter + 2] = pixel[1]; // H max

                    Hmean += pixel[0]; // H mean
                    Smean += pixel[1]; // S mean
                    Vmean += pixel[2]; // V mean
                }//from w w  w  . j a va2 s.  co  m
            vectors[counter] *= 2; // OpenCV scales H to H/2 to fit uchar;

            Hmean = Hmean * 2 / sizeOfBlocks; // H mean
            Smean /= sizeOfBlocks; // S mean
            Vmean /= sizeOfBlocks; // V mean

            for (int ii = i; ii < i + blockHeigth; ++ii)
                for (int jj = j; jj < j + blockWidth; ++jj) {
                    pixel = image.get(ii, jj);
                    vectors[counter + 3] += Math.pow(pixel[0] * 2 - Hmean, 2); // H variation
                    vectors[counter + 4] += Math.pow(pixel[1] - Smean, 2); // S variation
                    vectors[counter + 5] += Math.pow(pixel[2] - Vmean, 2); // V variation
                }
            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 variation

            counter += 6;
        }

    writeVectorToFile(vectors, outputFile);
    image.release();
    return 1;
}

From source file:SearchSystem.SearchingAlgorithms.CBIRSearchAlgorithm.java

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

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

    double Hmean = 0;
    double Smean = 0;
    double Vmean = 0;

    for (int i = 0; i < rows; i += blockHeigth)
        for (int j = 0; j < cols; j += blockWidth) {
            double pixel[] = image.get(i, j);
            for (int ii = i; ii < i + blockHeigth; ++ii)
                for (int jj = j; jj < j + blockWidth; ++jj) {
                    pixel = image.get(ii, jj);
                    if (vectors[counter] < pixel[0])
                        vectors[counter] = pixel[0]; // H max
                    if (vectors[counter + 1] < pixel[1])
                        vectors[counter + 1] = pixel[1]; // H max
                    if (vectors[counter + 2] < pixel[2])
                        vectors[counter + 2] = pixel[1]; // H max

                    Hmean += pixel[0]; // H mean
                    Smean += pixel[1]; // S mean
                    Vmean += pixel[2]; // V mean
                }//from  w w w .  j  ava2  s  .  c  om
            vectors[counter] *= 2; // OpenCV scales H to H/2 to fit uchar;

            Hmean = Hmean * 2 / sizeOfBlocks; // H mean
            Smean /= sizeOfBlocks; // S mean
            Vmean /= sizeOfBlocks; // V mean

            for (int ii = i; ii < i + blockHeigth; ++ii)
                for (int jj = j; jj < j + blockWidth; ++jj) {
                    pixel = image.get(ii, jj);
                    vectors[counter + 3] += Math.pow(pixel[0] * 2 - Hmean, 2); // H variation
                    vectors[counter + 4] += Math.pow(pixel[1] - Smean, 2); // S variation
                    vectors[counter + 5] += Math.pow(pixel[2] - Vmean, 2); // V variation
                }
            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 variation

            counter += 6;
        }

    image.release();
    return vectors;
}

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 ww  .j  a  va2 s .  c o 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 BufferedImage Mat2BufferedImage(Mat m) {
    // source: http://answers.opencv.org/question/10344/opencv-java-load-image-to-gui/
    // The output can be assigned either to a BufferedImage or to an Image

    int type = BufferedImage.TYPE_BYTE_GRAY;
    if (m.channels() > 1) {
        type = BufferedImage.TYPE_3BYTE_BGR;
    }/*  www . j  av a  2  s.  c o  m*/
    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:servershootingstar.BallDetector.java

public static String getAngleFromRobot(int input) {
    System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
    System.out.println("before");
    int point;// w w w .  jav a  2s  .c  o m
    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

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  w ww . j  a va 2s. c  o 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";
        String isSingleRegion = request.getParameter("isSingleRegion");
        boolean makeSingleRegion = isSingleRegion.toLowerCase().equals("true");

        Mat original = ImageUtils.loadImage(imageForTextRecognition, request);
        Mat image = original.clone();
        Mat mask = Mat.zeros(image.rows() + 2, image.cols() + 2, CvType.CV_8UC1);

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

        Gson gson = new Gson();
        Point[] tmpPoints = gson.fromJson(samplingPoints, Point[].class);

        ArrayList<Point> userPoints = new ArrayList<Point>(Arrays.asList(tmpPoints));

        Mat userPointsImage = image.clone();

        ArrayList<Mat> maskRegions = new ArrayList<>();

        Random random = new Random();
        int b = random.nextInt(256);
        int g = random.nextInt(256);
        int r = random.nextInt(256);
        Scalar newVal = new Scalar(b, g, r);
        FloodFillFacade floodFillFacade = new FloodFillFacade();

        int k = 0;

        for (int i = 0; i < userPoints.size(); i++) {
            Point point = userPoints.get(i);

            image = floodFillFacade.fill(image, mask, (int) point.x, (int) point.y, newVal);

            Mat seedImage = original.clone();
            Core.circle(seedImage, point, 9, new Scalar(0, 0, 255), -1);
            Core.putText(userPointsImage, "" + k, new Point(point.x + 5, point.y + 5), 3, 0.5,
                    new Scalar(0, 0, 0));
            //                ImageUtils.saveImage(seedImage, "mask_" + k + "_seed" + imageForTextRecognition + ".png", request);

            if (!makeSingleRegion) {
                Mat element = new Mat(3, 3, CvType.CV_8U, new Scalar(1));
                Imgproc.morphologyEx(mask, mask, Imgproc.MORPH_CLOSE, element, new Point(-1, -1), 3);
                Imgproc.resize(mask, mask, original.size());
            }

            //                ImageUtils.saveImage(mask, "mask_" + k + "" + imageForTextRecognition + ".png", request);

            Mat dilatedMask = new Mat();

            int elementSide = 21;
            Mat element = new Mat(elementSide, elementSide, CvType.CV_8U, new Scalar(1));
            Imgproc.morphologyEx(mask, dilatedMask, Imgproc.MORPH_DILATE, element, new Point(-1, -1), 1);
            Imgproc.resize(dilatedMask, dilatedMask, original.size());

            //                ImageUtils.saveImage(dilatedMask, "mask_" + k + "_dilated" + imageForTextRecognition + ".png", request);

            maskRegions.add(mask);

            if (!makeSingleRegion) {
                int totalRemovedPoints = filterPoints(userPoints, dilatedMask);
                if (totalRemovedPoints > 0) {
                    i = -1; // so that the algorithm starts again at the first element of the userPoints array
                }
            } else {
                filterPoints(userPoints, mask);
            }

            //                System.out.println("Total points after filtering:");
            //                System.out.println(userPoints.size());

            if (!makeSingleRegion) {
                mask = Mat.zeros(original.rows() + 2, original.cols() + 2, CvType.CV_8UC1);
            }

            k++;
        }

        ArrayList<FindingResponse> findingResponses = new ArrayList<>();

        if (makeSingleRegion) {

            Mat element = new Mat(3, 3, CvType.CV_8U, new Scalar(1));
            Imgproc.morphologyEx(mask, mask, Imgproc.MORPH_CLOSE, element, new Point(-1, -1), 3);

            Imgproc.resize(mask, mask, image.size());

            List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
            Imgproc.findContours(mask.clone(), contours, new Mat(), Imgproc.RETR_EXTERNAL,
                    Imgproc.CHAIN_APPROX_NONE);

            MatOfPoint biggestContour = contours.get(0); // getting the biggest contour
            double 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[] biggestContourPoints = biggestContour.toArray();
            String path = "M " + (int) biggestContourPoints[0].x + " " + (int) biggestContourPoints[0].y + " ";
            for (int i = 1; i < biggestContourPoints.length; ++i) {
                Point v = biggestContourPoints[i];
                path += "L " + (int) v.x + " " + (int) v.y + " ";
            }
            path += "Z";

            //                System.out.println("path:");
            //                System.out.println(path);

            Rect computedSearchWindow = Imgproc.boundingRect(biggestContour);
            Point massCenter = computedSearchWindow.tl();

            Scalar meanColor = Core.mean(original, mask);

            //                ImageUtils.saveImage(mask, "single_mask_" + imageForTextRecognition + ".png", request);

            FindingResponse findingResponse = new FindingResponse(path, meanColor, massCenter, -1, contourArea);
            findingResponses.add(findingResponse);

        } else {

            float imageArea = image.cols() * image.rows();

            for (int j = 0; j < maskRegions.size(); j++) {
                Mat region = maskRegions.get(j);

                List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
                Imgproc.findContours(region.clone(), contours, new Mat(), Imgproc.RETR_EXTERNAL,
                        Imgproc.CHAIN_APPROX_NONE);

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

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

                double contourArea = Imgproc.contourArea(biggestContour);

                if (contourArea / imageArea < 0.8) { // only areas less than 80% of that of the image are accepted

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

                    Rect computedSearchWindow = Imgproc.boundingRect(biggestContour);
                    Point massCenter = computedSearchWindow.tl();

                    //                        System.out.println("Contour area: " + contourArea);

                    Mat contoursImage = userPointsImage.clone();
                    Imgproc.drawContours(contoursImage, contours, 0, newVal, 1);

                    Scalar meanColor = Core.mean(original, region);

                    FindingResponse findingResponse = new FindingResponse(path, meanColor, massCenter, -1,
                            contourArea);
                    findingResponses.add(findingResponse);

                    //                        ImageUtils.saveImage(contoursImage, "mask_" + j + "_contourned" + imageForTextRecognition + ".png", request);

                }

            }

        }

        String jsonResponse = gson.toJson(findingResponses, ArrayList.class);

        out.println(jsonResponse);

    }
}

From source file:servlets.processScribble.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from ww w .j a v  a 2 s.  c  om
 *
 * @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 original = ImageUtils.loadImage(imageForTextRecognition, request);
        Mat image = original.clone();
        Mat mask = Mat.zeros(image.rows() + 2, image.cols() + 2, CvType.CV_8UC1);

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

        Gson gson = new Gson();
        Point[] userPoints = gson.fromJson(samplingPoints, Point[].class);

        MatOfPoint points = new MatOfPoint(new Mat(userPoints.length, 1, CvType.CV_32SC2));
        int cont = 0;

        for (Point point : userPoints) {
            int y = (int) point.y;
            int x = (int) point.x;
            int[] data = { x, y };
            points.put(cont++, 0, data);
        }

        MatOfInt hull = new MatOfInt();
        Imgproc.convexHull(points, hull);

        MatOfPoint mopOut = new MatOfPoint();
        mopOut.create((int) hull.size().height, 1, CvType.CV_32SC2);

        int totalPoints = (int) hull.size().height;

        Point[] convexHullPoints = new Point[totalPoints];
        ArrayList<Point> seeds = new ArrayList<>();

        for (int i = 0; i < totalPoints; i++) {
            int index = (int) hull.get(i, 0)[0];
            double[] point = new double[] { points.get(index, 0)[0], points.get(index, 0)[1] };
            mopOut.put(i, 0, point);

            convexHullPoints[i] = new Point(point[0], point[1]);
            seeds.add(new Point(point[0], point[1]));

        }

        MatOfPoint mop = new MatOfPoint();
        mop.fromArray(convexHullPoints);

        ArrayList<MatOfPoint> arrayList = new ArrayList<MatOfPoint>();
        arrayList.add(mop);

        Random random = new Random();
        int b = random.nextInt(256);
        int g = random.nextInt(256);
        int r = random.nextInt(256);
        Scalar newVal = new Scalar(b, g, r);

        FloodFillFacade floodFillFacade = new FloodFillFacade();

        for (int i = 0; i < seeds.size(); i++) {
            Point seed = seeds.get(i);
            image = floodFillFacade.fill(image, mask, (int) seed.x, (int) seed.y, newVal);
        }

        Imgproc.drawContours(image, arrayList, 0, newVal, -1);

        Imgproc.resize(mask, mask, image.size());

        Scalar meanColor = Core.mean(original, mask);

        //            Highgui.imwrite("C:\\Users\\Gonzalo\\Documents\\NetBeansProjects\\iVoLVER\\uploads\\the_convexHull.png", image);
        ImageUtils.saveImage(image, imageForTextRecognition + "_the_convexHull.png", request);

        newVal = new Scalar(255, 255, 0);

        floodFillFacade.setMasked(false);
        System.out.println("Last one:");
        floodFillFacade.fill(image, mask, 211, 194, newVal);

        Core.circle(image, new Point(211, 194), 5, new Scalar(0, 0, 0), -1);
        ImageUtils.saveImage(image, imageForTextRecognition + "_final.png", request);
        //            Highgui.imwrite("C:\\Users\\Gonzalo\\Documents\\NetBeansProjects\\iVoLVER\\uploads\\final.png", image);

        Mat element = new Mat(3, 3, CvType.CV_8U, new Scalar(1));
        Imgproc.morphologyEx(mask, mask, Imgproc.MORPH_CLOSE, element, new Point(-1, -1), 3);

        Imgproc.resize(mask, mask, image.size());

        //            ImageUtils.saveImage(mask, "final_mask_dilated.png", request);
        //            Highgui.imwrite("C:\\Users\\Gonzalo\\Documents\\NetBeansProjects\\iVoLVER\\uploads\\final_mask_dilated.png", mask);

        List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
        Imgproc.findContours(mask.clone(), contours, new Mat(), Imgproc.RETR_EXTERNAL,
                Imgproc.CHAIN_APPROX_NONE);
        double contourArea = 0;
        String path = "";

        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[] biggestContourPoints = biggestContour.toArray();
        path = "M " + (int) biggestContourPoints[0].x + " " + (int) biggestContourPoints[0].y + " ";
        for (int i = 1; i < biggestContourPoints.length; ++i) {
            Point v = biggestContourPoints[i];
            path += "L " + (int) v.x + " " + (int) v.y + " ";
        }
        path += "Z";

        System.out.println("path:");
        System.out.println(path);

        Rect computedSearchWindow = Imgproc.boundingRect(biggestContour);
        Point massCenter = computedSearchWindow.tl();

        FindingResponse findingResponse = new FindingResponse(path, meanColor, massCenter, -1, contourArea);
        String jsonResponse = gson.toJson(findingResponse, FindingResponse.class);

        out.println(jsonResponse);

        //            String jsonResponse = gson.toJson(path);
        //            out.println(jsonResponse);
    }
}

From source file:servlets.SampleColorsFromImageObject.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//ww  w  .j  av  a2s  .  com
 *
 * @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: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;
                }//from   w ww.  j av a 2 s  .  c  om

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