List of usage examples for org.opencv.core MatOfPoint get
public double[] get(int row, int col)
From source file:OCV_ConvexHull.java
License:Open Source License
private void showData(MatOfPoint pts, MatOfInt hull) { // set the ResultsTable ResultsTable rt = OCV__LoadLibrary.GetResultsTable(true); int num_hull = (int) hull.size().height; float[] xPoints = new float[num_hull]; float[] yPoints = new float[num_hull]; for (int i = 0; i < num_hull; i++) { int index = (int) hull.get(i, 0)[0]; xPoints[i] = (float) pts.get(index, 0)[0]; yPoints[i] = (float) pts.get(index, 0)[1]; rt.incrementCounter();//w w w .j av a2 s. c o m rt.addValue("X", xPoints[i]); rt.addValue("Y", yPoints[i]); } rt.show("Results"); // set the ROI RoiManager roiMan = OCV__LoadLibrary.GetRoiManager(true, true); PolygonRoi proi = new PolygonRoi(xPoints, yPoints, Roi.POLYGON); roiMan.addRoi(proi); }
From source file:edu.fiu.cate.breader.BaseSegmentation.java
/** * Finds the bounding box for the book on the stand using * the high resolution image.//from w ww. jav a2 s . c o m * @param src- High Resolution image of the book * @return Rectangle delineating the book */ public Rect highRes(Mat src) { Mat dst = src.clone(); Imgproc.blur(src, dst, new Size(100.0, 100.0), new Point(-1, -1), Core.BORDER_REPLICATE); Imgproc.threshold(dst, dst, 0, 255, Imgproc.THRESH_BINARY_INV + Imgproc.THRESH_OTSU); Imgproc.Canny(dst, dst, 50, 200, 3, false); List<MatOfPoint> contours = new LinkedList<>(); Mat hierarchy = new Mat(); Imgproc.findContours(dst, contours, hierarchy, Imgproc.RETR_TREE, Imgproc.CHAIN_APPROX_SIMPLE, new Point(0, 0)); Mat color = new Mat(); Imgproc.cvtColor(src, color, Imgproc.COLOR_GRAY2BGR); for (int k = 0; k < contours.size(); k++) { byte[] vals = ITools.getHeatMapColor((float) k / (float) contours.size()); Imgproc.drawContours(color, contours, k, new Scalar(vals[0], vals[1], vals[2]), 8); } new IViewer("HighRes Contours ", BReaderTools.bufferedImageFromMat(color)); Point center = new Point(src.cols() / 2, src.rows() / 2); //Check hierarchy tree int[] res = polySearch(center, hierarchy, contours, 0); while (res[0] != 1 && res[2] != -1) { res = polySearch(center, hierarchy, contours, res[2]); if (res[0] == 1) break; } MatOfInt tHull = new MatOfInt(); int index = 0; if (res[1] != -1) { index = res[1]; } Imgproc.convexHull(contours.get(index), tHull); //get bounding box MatOfPoint cont = contours.get(index); Point[] points = new Point[tHull.rows()]; for (int i = 0; i < tHull.rows(); i++) { int pIndex = (int) tHull.get(i, 0)[0]; points[i] = new Point(cont.get(pIndex, 0)); } Rect out = Imgproc.boundingRect(new MatOfPoint(points)); return out; }
From source file:org.usfirst.frc.team2084.CMonster2016.vision.BallProcessor.java
License:Open Source License
@Override public void process(Mat cameraImage) { Imgproc.blur(cameraImage, hsvImage, new Size(20, 20)); Imgproc.cvtColor(hsvImage, hsvImage, Imgproc.COLOR_BGR2HSV); // Threshold image to find blue/green Core.inRange(hsvImage, thresholdMin, thresholdMax, thresholdImage); Imgproc.erode(thresholdImage, thresholdImage, KERNEL); Imgproc.dilate(thresholdImage, thresholdImage, KERNEL); thresholdImage.copyTo(contourImage); contours.clear();//from w ww. j a va2 s . c o m hulls.clear(); Imgproc.findContours(contourImage, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE); Imgproc.drawContours(cameraImage, contours, -1, CONTOUR_COLOR); for (int i = 0; i < contours.size(); i++) { MatOfPoint contour = contours.get(i); MatOfInt hullIndices = new MatOfInt(); MatOfPoint hull; hulls.add(hull = new MatOfPoint()); Imgproc.convexHull(contour, hullIndices); for (int c = 0; c < hullIndices.rows(); c++) { int v = (int) hullIndices.get(c, 0)[0]; hull.put(c, 0, contour.get(v, 0)); // System.out.println(v); } // System.out.println(hull.size()); } Imgproc.drawContours(cameraImage, hulls, -1, CONTOUR_COLOR); debugImage("Threshold Image", thresholdImage); // debugImage("Contour Image", contourImage); }
From source file:org.usfirst.frc.team2084.CMonster2016.vision.BoulderProcessor.java
License:Open Source License
private static MatOfPoint convexHull(MatOfPoint contour) { MatOfInt hullMatrix = new MatOfInt(); Imgproc.convexHull(contour, hullMatrix); // perform convex hull, gap // filler MatOfPoint hull = new MatOfPoint(); hull.create(hullMatrix.rows(), 1, CvType.CV_32SC2); for (int r = 0; r < hullMatrix.rows(); r++) { hull.put(r, 0, contour.get((int) hullMatrix.get(r, 0)[0], 0)); }// www .ja v a2s.c o m return hull; }
From source file:org.usfirst.frc.team2084.CMonster2016.vision.HighGoalProcessor.java
License:Open Source License
private MatOfPoint convexHull(MatOfPoint contour) { MatOfInt hullMatrix = new MatOfInt(); Imgproc.convexHull(contour, hullMatrix); // perform convex hull, gap // filler MatOfPoint hull = new MatOfPoint(); hull.create(hullMatrix.rows(), 1, CvType.CV_32SC2); for (int r = 0; r < hullMatrix.rows(); r++) { hull.put(r, 0, contour.get((int) hullMatrix.get(r, 0)[0], 0)); }//from w w w . j av a 2s . co m return hull; }
From source file:org.usfirst.frc.team2084.CMonster2016.vision.Target.java
License:Open Source License
/** * Creates a new possible target based on the specified blob and calculates * its score./* w ww.j a va 2 s . co m*/ * * @param p the shape of the possible target */ public Target(MatOfPoint contour, Mat grayImage) { // Simplify contour to make the corner finding algorithm work better MatOfPoint2f fContour = new MatOfPoint2f(); contour.convertTo(fContour, CvType.CV_32F); Imgproc.approxPolyDP(fContour, fContour, VisionParameters.getGoalApproxPolyEpsilon(), true); fContour.convertTo(contour, CvType.CV_32S); this.contour = contour; // Check area, and don't do any calculations if it is not valid if (validArea = validateArea()) { // Find a bounding rectangle RotatedRect rect = Imgproc.minAreaRect(fContour); Point[] rectPoints = new Point[4]; rect.points(rectPoints); for (int j = 0; j < rectPoints.length; j++) { Point rectPoint = rectPoints[j]; double minDistance = Double.MAX_VALUE; Point point = null; for (int i = 0; i < contour.rows(); i++) { Point contourPoint = new Point(contour.get(i, 0)); double dist = distance(rectPoint, contourPoint); if (dist < minDistance) { minDistance = dist; point = contourPoint; } } rectPoints[j] = point; } MatOfPoint2f rectMat = new MatOfPoint2f(rectPoints); // Refine the corners to improve accuracy Imgproc.cornerSubPix(grayImage, rectMat, new Size(4, 10), new Size(-1, -1), new TermCriteria(TermCriteria.EPS + TermCriteria.COUNT, 30, 0.1)); rectPoints = rectMat.toArray(); // Identify each corner SortedMap<Double, List<Point>> x = new TreeMap<>(); Arrays.stream(rectPoints).forEach((p) -> { List<Point> points; if ((points = x.get(p.x)) == null) { x.put(p.x, points = new LinkedList<>()); } points.add(p); }); int i = 0; for (Iterator<List<Point>> it = x.values().iterator(); it.hasNext();) { List<Point> s = it.next(); for (Point p : s) { switch (i) { case 0: topLeft = p; break; case 1: bottomLeft = p; break; case 2: topRight = p; break; case 3: bottomRight = p; } i++; } } // Organize corners if (topLeft.y > bottomLeft.y) { Point p = bottomLeft; bottomLeft = topLeft; topLeft = p; } if (topRight.y > bottomRight.y) { Point p = bottomRight; bottomRight = topRight; topRight = p; } // Create corners for centroid calculation corners = new MatOfPoint2f(rectPoints); // Calculate center Moments moments = Imgproc.moments(corners); center = new Point(moments.m10 / moments.m00, moments.m01 / moments.m00); // Put the points in the correct order for solvePNP rectPoints[0] = topLeft; rectPoints[1] = topRight; rectPoints[2] = bottomLeft; rectPoints[3] = bottomRight; // Recreate corners in the new order corners = new MatOfPoint2f(rectPoints); widthTop = distance(topLeft, topRight); widthBottom = distance(bottomLeft, bottomRight); width = (widthTop + widthBottom) / 2.0; heightLeft = distance(topLeft, bottomLeft); heightRight = distance(topRight, bottomRight); height = (heightLeft + heightRight) / 2.0; Mat tvec = new Mat(); // Calculate target's location Calib3d.solvePnP(OBJECT_POINTS, corners, CAMERA_MAT, DISTORTION_MAT, rotation, tvec, false, Calib3d.CV_P3P); // ======================================= // Position and Orientation Transformation // ======================================= double armAngle = VisionResults.getArmAngle(); // Flip y axis to point upward Core.multiply(tvec, SIGN_NORMALIZATION_MATRIX, tvec); // Shift origin to arm pivot point, on the robot's centerline CoordinateMath.translate(tvec, CAMERA_X_OFFSET, CAMERA_Y_OFFSET, ARM_LENGTH); // Align axes with ground CoordinateMath.rotateX(tvec, -armAngle); Core.add(rotation, new MatOfDouble(armAngle, 0, 0), rotation); // Shift origin to robot center of rotation CoordinateMath.translate(tvec, 0, ARM_PIVOT_Y_OFFSET, -ARM_PIVOT_Z_OFFSET); double xPosFeet = tvec.get(0, 0)[0]; double yPosFeet = tvec.get(1, 0)[0]; double zPosFeet = tvec.get(2, 0)[0]; // Old less effective aiming heading and distance calculation // double pixelsToFeet = TARGET_WIDTH / width; // distance = (TARGET_WIDTH * HighGoalProcessor.IMAGE_SIZE.width // / (2 * width ** Math.tan(VisionParameters.getFOVAngle() / 2))); // double xPosFeet = (center.x - (HighGoalProcessor.IMAGE_SIZE.width // / 2)) * pixelsToFeet; // double yPosFeet = -(center.y - // (HighGoalProcessor.IMAGE_SIZE.height / 2)) * pixelsToFeet; distance = Math.sqrt(xPosFeet * xPosFeet + zPosFeet * zPosFeet); position = new Point3(xPosFeet, yPosFeet, zPosFeet); xGoalAngle = Math.atan(xPosFeet / zPosFeet); yGoalAngle = Math.atan(yPosFeet / zPosFeet); validate(); score = calculateScore(); } else { valid = false; } }
From source file:servlets.processScribble.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./* w w w . j a v a2s . 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"; 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:simeav.Utils.java
public static ArrayList<Point> detectarVertices(Mat original) { MatOfPoint corners = new MatOfPoint(); Imgproc.goodFeaturesToTrack(original, corners, 100, 0.01, 0, new Mat(), 2, false, 0.04); Mat vertices = Mat.zeros(original.size(), CvType.CV_8UC3); for (int i = 0; i < corners.height(); i++) { Core.circle(vertices, new Point(corners.get(i, 0)), 8, new Scalar(180, 170, 5), -1); }//from ww w. j av a 2s . c o m Mat imGrises = new Mat(); Mat bw = new Mat(); Imgproc.cvtColor(vertices, imGrises, Imgproc.COLOR_BGR2GRAY); Imgproc.Canny(imGrises, bw, 100, 150, 5, true); Mat jerarquia = new Mat(); ArrayList<MatOfPoint> contornos = new ArrayList<>(); Imgproc.findContours(bw.clone(), contornos, jerarquia, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE); ArrayList<Point> mc = Utils.getCentros(contornos); Mat resultado = Mat.zeros(original.size(), CvType.CV_8UC3); for (int i = 0; i < contornos.size(); i++) { Scalar color = new Scalar(180, 170, 5); // Imgproc.drawContours(resultado, contornos, i, color, 2, 8, jerarquia, 0, new Point()); Core.circle(resultado, mc.get(i), 4, color, -1, 8, 0); } return mc; }