List of usage examples for org.opencv.imgproc Imgproc arcLength
public static double arcLength(MatOfPoint2f curve, boolean closed)
From source file:ac.robinson.ticqr.TickBoxImageParserTask.java
License:Apache License
@Override protected ArrayList<PointF> doInBackground(Void... unused) { Log.d(TAG, "Searching for tick boxes of " + mBoxSize + " size"); // we look for *un-ticked* boxes, rather than ticked, as they are uniform in appearance (and hence easier to // detect) - they show up as a box within a box ArrayList<PointF> centrePoints = new ArrayList<>(); int minimumOuterBoxArea = (int) Math.round(Math.pow(mBoxSize, 2)); int maximumOuterBoxArea = (int) Math.round(Math.pow(mBoxSize * 1.35f, 2)); int minimumInnerBoxArea = (int) Math.round(Math.pow(mBoxSize * 0.5f, 2)); // image adjustment - blurSize, blurSTDev and adaptiveThresholdSize must not be even numbers int blurSize = 9; int blurSTDev = 3; int adaptiveThresholdSize = Math.round(mBoxSize * 3); // (oddness ensured below) int adaptiveThresholdC = 4; // value to add to the mean (can be negative or zero) adaptiveThresholdSize = adaptiveThresholdSize % 2 == 0 ? adaptiveThresholdSize + 1 : adaptiveThresholdSize; // how similar the recognised polygon must be to its actual contour - lower is more similar float outerPolygonSimilarity = 0.045f; float innerPolygonSimilarity = 0.075f; // don't require as much accuracy for the inner part of the tick box // how large the maximum internal angle can be (e.g., for checking square shape) float maxOuterAngleCos = 0.3f; float maxInnerAngleCos = 0.4f; // use OpenCV to recognise boxes that have a box inside them - i.e. an un-ticked tick box // see: http://stackoverflow.com/a/11427501 // Bitmap newBitmap = mBitmap.copy(Bitmap.Config.RGB_565, true); // not needed Mat bitMat = new Mat(); Utils.bitmapToMat(mBitmap, bitMat);/*from ww w. j a v a 2s . c o m*/ // blur and convert to grey // alternative (less flexible): Imgproc.medianBlur(bitMat, bitMat, blurSize); Imgproc.GaussianBlur(bitMat, bitMat, new Size(blurSize, blurSize), blurSTDev, blurSTDev); Imgproc.cvtColor(bitMat, bitMat, Imgproc.COLOR_RGB2GRAY); // need 8uC1 (1 channel, unsigned char) image type // perform adaptive thresholding to detect edges // alternative (slower): Imgproc.Canny(bitMat, bitMat, 10, 20, 3, false); Imgproc.adaptiveThreshold(bitMat, bitMat, 255, Imgproc.ADAPTIVE_THRESH_GAUSSIAN_C, Imgproc.THRESH_BINARY, adaptiveThresholdSize, adaptiveThresholdC); // get the contours in the image, and their hierarchy Mat hierarchyMat = new Mat(); List<MatOfPoint> contours = new ArrayList<>(); Imgproc.findContours(bitMat, contours, hierarchyMat, Imgproc.RETR_TREE, Imgproc.CHAIN_APPROX_SIMPLE); if (DEBUG) { Imgproc.drawContours(bitMat, contours, -1, new Scalar(30, 255, 255), 1); } // parse the contours and look for a box containing another box, with similar enough sizes int numContours = contours.size(); ArrayList<Integer> searchedContours = new ArrayList<>(); Log.d(TAG, "Found " + numContours + " possible tick box areas"); if (numContours > 0 && !hierarchyMat.empty()) { for (int i = 0; i < numContours; i++) { // the original detected contour MatOfPoint boxPoints = contours.get(i); // hierarchy key: 0 = next sibling num, 1 = previous sibling num, 2 = first child num, 3 = parent num int childBox = (int) hierarchyMat.get(0, i)[2]; // usually the largest child (as we're doing RETR_TREE) if (childBox == -1) { // we only want elements that have children continue; } else { if (searchedContours.contains(childBox)) { if (DEBUG) { Log.d(TAG, "Ignoring duplicate box at first stage: " + childBox); } continue; } else { searchedContours.add(childBox); } } // discard smaller (i.e. noise) outer box areas as soon as possible for speed // used to do Imgproc.isContourConvex(outerPoints) later, but the angle check covers this, so no need double originalArea = Math.abs(Imgproc.contourArea(boxPoints)); if (originalArea < minimumOuterBoxArea) { // if (DEBUG) { // drawPoints(bitMat, boxPoints, new Scalar(255, 255, 255), 1); // Log.d(TAG, "Outer box too small"); // } continue; } if (originalArea > maximumOuterBoxArea) { // if (DEBUG) { // drawPoints(bitMat, boxPoints, new Scalar(255, 255, 255), 1); // Log.d(TAG, "Outer box too big"); // } continue; } // simplify the contours of the outer box - we want to detect four-sided shapes only MatOfPoint2f boxPoints2f = new MatOfPoint2f(boxPoints.toArray()); // Point2f for approxPolyDP Imgproc.approxPolyDP(boxPoints2f, boxPoints2f, outerPolygonSimilarity * Imgproc.arcLength(boxPoints2f, true), true); // simplify the contour if (boxPoints2f.height() != 4) { // height is number of points if (DEBUG) { // drawPoints(bitMat, new MatOfPoint(boxPoints2f.toArray()), new Scalar(255, 255, 255), 1); Log.d(TAG, "Outer box not 4 points"); } continue; } // check that the simplified outer box is approximately a square, angle-wise org.opencv.core.Point[] boxPointsArray = boxPoints2f.toArray(); double maxCosine = 0; for (int j = 0; j < 4; j++) { org.opencv.core.Point pL = boxPointsArray[j]; org.opencv.core.Point pIntersect = boxPointsArray[(j + 1) % 4]; org.opencv.core.Point pR = boxPointsArray[(j + 2) % 4]; getLineAngle(pL, pIntersect, pR); maxCosine = Math.max(maxCosine, getLineAngle(pL, pIntersect, pR)); } if (maxCosine > maxOuterAngleCos) { if (DEBUG) { // drawPoints(bitMat, new MatOfPoint(boxPoints2f.toArray()), new Scalar(255, 255, 255), 1); Log.d(TAG, "Outer angles not square enough"); } continue; } // check that the simplified outer box is approximately a square, line length-wise double minLine = Double.MAX_VALUE; double maxLine = 0; for (int p = 1; p < 4; p++) { org.opencv.core.Point p1 = boxPointsArray[p - 1]; org.opencv.core.Point p2 = boxPointsArray[p]; double xd = p1.x - p2.x; double yd = p1.y - p2.y; double lineLength = Math.sqrt((xd * xd) + (yd * yd)); minLine = Math.min(minLine, lineLength); maxLine = Math.max(maxLine, lineLength); } if (maxLine - minLine > minLine) { if (DEBUG) { // drawPoints(bitMat, new MatOfPoint(boxPoints2f.toArray()), new Scalar(255, 255, 255), 1); Log.d(TAG, "Outer lines not square enough"); } continue; } // draw the outer box if debugging if (DEBUG) { MatOfPoint debugBoxPoints = new MatOfPoint(boxPointsArray); Log.d(TAG, "Potential tick box: " + boxPoints2f.size() + ", " + "area: " + Math.abs(Imgproc.contourArea(debugBoxPoints)) + " (min:" + minimumOuterBoxArea + ", max:" + maximumOuterBoxArea + ")"); drawPoints(bitMat, debugBoxPoints, new Scalar(50, 255, 255), 2); } // loop through the children - they should be in descending size order, but sometimes this is wrong boolean wrongBox = false; while (true) { if (DEBUG) { Log.d(TAG, "Looping with box: " + childBox); } // we've previously tried a child - try the next one // key: 0 = next sibling num, 1 = previous sibling num, 2 = first child num, 3 = parent num if (wrongBox) { childBox = (int) hierarchyMat.get(0, childBox)[0]; if (childBox == -1) { break; } if (searchedContours.contains(childBox)) { if (DEBUG) { Log.d(TAG, "Ignoring duplicate box at loop stage: " + childBox); } break; } else { searchedContours.add(childBox); } //noinspection UnusedAssignment wrongBox = false; } // perhaps this is the outer box - check its child has no children itself // (removed so tiny children (i.e. noise) don't mean we mis-detect an un-ticked box as ticked) // if (hierarchyMat.get(0, childBox)[2] != -1) { // continue; // } // check the size of the child box is large enough boxPoints = contours.get(childBox); originalArea = Math.abs(Imgproc.contourArea(boxPoints)); if (originalArea < minimumInnerBoxArea) { if (DEBUG) { // drawPoints(bitMat, boxPoints, new Scalar(255, 255, 255), 1); Log.d(TAG, "Inner box too small"); } wrongBox = true; continue; } // simplify the contours of the inner box - again, we want four-sided shapes only boxPoints2f = new MatOfPoint2f(boxPoints.toArray()); Imgproc.approxPolyDP(boxPoints2f, boxPoints2f, innerPolygonSimilarity * Imgproc.arcLength(boxPoints2f, true), true); if (boxPoints2f.height() != 4) { // height is number of points // if (DEBUG) { // drawPoints(bitMat, boxPoints, new Scalar(255, 255, 255), 1); // } Log.d(TAG, "Inner box fewer than 4 points"); // TODO: allow > 4 for low quality images? wrongBox = true; continue; } // check that the simplified inner box is approximately a square, angle-wise // higher tolerance because noise means if we get several inners, the box may not be quite square boxPointsArray = boxPoints2f.toArray(); maxCosine = 0; for (int j = 0; j < 4; j++) { org.opencv.core.Point pL = boxPointsArray[j]; org.opencv.core.Point pIntersect = boxPointsArray[(j + 1) % 4]; org.opencv.core.Point pR = boxPointsArray[(j + 2) % 4]; getLineAngle(pL, pIntersect, pR); maxCosine = Math.max(maxCosine, getLineAngle(pL, pIntersect, pR)); } if (maxCosine > maxInnerAngleCos) { Log.d(TAG, "Inner angles not square enough"); wrongBox = true; continue; } // this is probably an inner box - log if debugging if (DEBUG) { Log.d(TAG, "Un-ticked inner box: " + boxPoints2f.size() + ", " + "area: " + Math.abs(Imgproc.contourArea(new MatOfPoint2f(boxPointsArray))) + " (min: " + minimumInnerBoxArea + ")"); } // find the inner box centre double centreX = (boxPointsArray[0].x + boxPointsArray[1].x + boxPointsArray[2].x + boxPointsArray[3].x) / 4f; double centreY = (boxPointsArray[0].y + boxPointsArray[1].y + boxPointsArray[2].y + boxPointsArray[3].y) / 4f; // draw the inner box if debugging if (DEBUG) { drawPoints(bitMat, new MatOfPoint(boxPointsArray), new Scalar(255, 255, 255), 1); Core.circle(bitMat, new org.opencv.core.Point(centreX, centreY), 3, new Scalar(255, 255, 255)); } // add to the list of boxes to check centrePoints.add(new PointF((float) centreX, (float) centreY)); break; } } } Log.d(TAG, "Found " + centrePoints.size() + " un-ticked boxes"); return centrePoints; }
From source file:com.mycompany.objectdetection.ObjectDetector.java
public void findObjects() { // Imgproc.cvtColor(img, imgGrayscale, Imgproc.COLOR_RGBA2GRAY, 1); // Core.convertScaleAbs(img, imgGrayscale); // Core.normalize(imgGrayscale, imgMeanShifted, 0.0, 1.0, NORM_MINMAX); preProcessImg();//from ww w. j a v a2 s .c o m toGrayScale(imgMeanShifted); detectEdges(imgGrayscale); Imgproc.findContours(imgCanny, contours, imgCanny, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE); objList = new ArrayList(); for (MatOfPoint mop : contours) { MatOfPoint2f m2p; m2p = new MatOfPoint2f(mop.toArray()); Double peri = Imgproc.arcLength(m2p, true); Imgproc.approxPolyDP(m2p, m2p, 0.02 * peri, true); Imgproc.drawContours(imgOut, contours, -1, new Scalar(0, 0, 255), 2); float area = img.width() * img.height(); Rect rect = Imgproc.boundingRect(mop); objList.add(rect); Imgproc.rectangle(imgOut, rect.tl(), rect.br(), new Scalar(255, 0, 0)); } Collections.sort(objList, new Comparator<Rect>() { @Override public int compare(Rect r1, Rect r2) { return (int) (r2.area() - r1.area()); } }); List<Rect> arr = objList; while (arr.size() > 0) { //System.out.println("---->" + arr); Rect bigRect = arr.get(0); arr.remove(0); Rect bigRect2 = new Rect(); while (!equals(bigRect, bigRect2)) { bigRect2 = bigRect; for (int i = 0; i < arr.size(); ++i) { // System.out.println("elotte"+arr.get(i)); if (doOverlap(bigRect, arr.get(i))) { //System.out.println("utana"+arr.get(i)); bigRect = union(bigRect, arr.get(i)); arr.remove(i); break; } } } mainRect = bigRect; if (objList.size() > 5 && mainRect.area() >= img.width() * img.height() * 3 / 100) { Imgproc.rectangle(imgOut, bigRect.tl(), bigRect.br(), new Scalar(255, 255, 0)); mainObjects.add(mainRect); } else if (objList.size() <= 5) { mainObjects.add(mainRect); } } }
From source file:dfmDrone.examples.fitEllipseExample.java
private static Mat findAndDrawEllipse(Mat sourceImg) { Mat grayScaleImg = new Mat(); Mat hsvImg = new Mat(); Imgproc.cvtColor(sourceImg, hsvImg, Imgproc.COLOR_BGR2HSV); Mat lower_hue_range = new Mat(); Mat upper_hue_range = new Mat(); Core.inRange(hsvImg, new Scalar(0, 100, 45), new Scalar(15, 255, 255), lower_hue_range); Core.inRange(hsvImg, new Scalar(160, 100, 45), new Scalar(180, 255, 255), upper_hue_range); Mat red_hue_image = new Mat(); Core.addWeighted(lower_hue_range, 1.0, upper_hue_range, 1.0, 0, red_hue_image); Mat dilateElement = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(24, 24)); Mat erodeElement = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(10, 10)); Imgproc.blur(red_hue_image, red_hue_image, new Size(11, 11)); // init// w ww . j a v a2 s. co m List<MatOfPoint> contours = new ArrayList<>(); Mat hierarchy = new Mat(); // find contours Imgproc.findContours(red_hue_image, contours, hierarchy, Imgproc.RETR_CCOMP, Imgproc.CHAIN_APPROX_SIMPLE); System.out.println("After findcontours"); // if any contour exist... if (hierarchy.size().height > 0 && hierarchy.size().width > 0) { // for each contour, display it in blue for (int idx = 0; idx >= 0; idx = (int) hierarchy.get(0, idx)[0]) { System.out.println(idx); // Imgproc.drawContours(frame, contours, idx, new Scalar(250, 0, 0), 3); } } MatOfPoint2f approxCurve = new MatOfPoint2f(); //For each contour found MatOfPoint2f contour2f = null; RotatedRect rotatedrect = null; for (MatOfPoint contour : contours) { //Convert contours(i) from MatOfPoint to MatOfPoint2f if (contour2f == null) contour2f = new MatOfPoint2f(contour.toArray()); if (contour.size().area() > contour2f.size().area()) { contour2f = new MatOfPoint2f(contour.toArray()); } } try { Imgproc.fitEllipse(contour2f); rotatedrect = Imgproc.fitEllipse(contour2f); double approxDistance = Imgproc.arcLength(contour2f, true) * 0.02; Imgproc.approxPolyDP(contour2f, approxCurve, approxDistance, true); //Convert back to MatOfPoint MatOfPoint points = new MatOfPoint(approxCurve.toArray()); // Get bounding rect of contour Rect rect = Imgproc.boundingRect(points); // draw enclosing rectangle (all same color, but you could use variable i to make them unique) Imgproc.rectangle(sourceImg, rect.tl(), rect.br(), new Scalar(255, 0, 0), 1, 8, 0); Imgproc.ellipse(sourceImg, rotatedrect, new Scalar(255, 192, 203), 4, 8); } catch (CvException e) { e.printStackTrace(); System.out.println("Ingen ellipse fundet"); } return sourceImg; }
From source file:objectdetection.ObjectDetector.java
public void findObjects() { preProcessImg();/*from w w w .j a v a 2 s . c o m*/ Imgproc.findContours(imgCanny, contours, imgCanny, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE); for (MatOfPoint mop : contours) { MatOfPoint2f m2p; m2p = new MatOfPoint2f(mop.toArray()); Double peri = Imgproc.arcLength(m2p, true); Imgproc.approxPolyDP(m2p, m2p, 0.02 * peri, true); //Imgproc.drawContours(img, contours, -1, new Scalar(0, 0, 255), 2); float area = img.width() * img.height(); Rect rect = Imgproc.boundingRect(mop); objList.add(rect); //if (rect.height * rect.width > area*5/100) { Imgproc.rectangle(img, rect.tl(), rect.br(), new Scalar(255, 0, 0)); //} } Collections.sort(objList, new Comparator<Rect>() { @Override public int compare(Rect r1, Rect r2) { return (int) (r2.area() - r1.area()); } }); List<Rect> arr = objList; Rect bigRect = arr.get(0); Rect bigRect2 = arr.get(1); while (!equals(bigRect, bigRect2)) { bigRect2 = bigRect; for (int i = 1; i < arr.size(); ++i) { if (doOverlap(bigRect, arr.get(i))) { bigRect = union(bigRect, arr.get(i)); arr.remove(i); break; } } } Imgproc.rectangle(img, bigRect.tl(), bigRect.br(), new Scalar(255, 255, 0)); mainRect = bigRect; }
From source file:org.lasarobotics.vision.detection.objects.Contour.java
License:Open Source License
/** * Get the arc length of the contour//from w w w. jav a 2s .c om * * @param closed True if the contour should be calculated as closed * @return Arc length */ public double arcLength(boolean closed) { return Imgproc.arcLength(getDoubleData(), closed); }
From source file:video.PictureAnalyser.java
public List<MatOfPoint> getConturs(Scalar low, Scalar high, Mat img) { Mat imgThresholded = new Mat(); Mat imgThresholded2 = new Mat(); Core.inRange(img, low, high, imgThresholded); if (low.val[0] < 0) { low.val[0] = 180 + low.val[0]; high.val[0] = 179; Core.inRange(img, low, high, imgThresholded2); Core.bitwise_or(imgThresholded, imgThresholded2, imgThresholded); }/* ww w . java2 s . c o m*/ if (high.val[0] > 179) { low.val[0] = 0; high.val[0] = high.val[0] - 180; Core.inRange(img, low, high, imgThresholded2); Core.bitwise_or(imgThresholded, imgThresholded2, imgThresholded); } List<MatOfPoint> contours = new ArrayList<MatOfPoint>(); int dilation_size = 3; Mat element1 = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(2 * dilation_size + 1, 2 * dilation_size + 1)); Imgproc.dilate(imgThresholded, imgThresholded, element1); Imgproc.findContours(imgThresholded, contours, new Mat(), Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_SIMPLE); MatOfPoint2f approxCurve = new MatOfPoint2f(); for (int i = 0; i < contours.size(); i++) { MatOfPoint2f contour2f = new MatOfPoint2f(contours.get(i).toArray()); double approxDistance = Imgproc.arcLength(contour2f, true) * 0.02; Imgproc.approxPolyDP(contour2f, approxCurve, approxDistance, true); MatOfPoint points = new MatOfPoint(approxCurve.toArray()); Rect rect = Imgproc.boundingRect(points); int area = (rect.width) * (rect.height); //tester og arealet er for smt if (area > 500) { } else { contours.remove(i); i--; } } return contours; }