Java Code Examples for org.opencv.imgproc.Imgproc#contourArea()

The following examples show how to use org.opencv.imgproc.Imgproc#contourArea() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: VideoMotionDetector.java    From video-stream-analytics with Apache License 2.0 6 votes vote down vote up
private static ArrayList<Rect> getContourArea(Mat mat) {
	Mat hierarchy = new Mat();
	Mat image = mat.clone();
	List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
	Imgproc.findContours(image, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);
	Rect rect = null;
	double maxArea = 300;
	ArrayList<Rect> arr = new ArrayList<Rect>();
	for (int i = 0; i < contours.size(); i++) {
		Mat contour = contours.get(i);
		double contourArea = Imgproc.contourArea(contour);
		if (contourArea > maxArea) {
			rect = Imgproc.boundingRect(contours.get(i));
			arr.add(rect);
		}
	}
	return arr;
}
 
Example 2
Source File: MainActivity.java    From SimpleDocumentScanner-Android with MIT License 6 votes vote down vote up
/**
 * Find the largest 4 point contour in the given Mat.
 *
 * @param src A valid Mat
 * @return The largest contour as a Mat
 */
private MatOfPoint2f findLargestContour(Mat src) {
    List<MatOfPoint> contours = new ArrayList<>();
    Imgproc.findContours(src, contours, new Mat(), Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_SIMPLE);

    // Get the 5 largest contours
    Collections.sort(contours, new Comparator<MatOfPoint>() {
        public int compare(MatOfPoint o1, MatOfPoint o2) {
            double area1 = Imgproc.contourArea(o1);
            double area2 = Imgproc.contourArea(o2);
            return (int) (area2 - area1);
        }
    });
    if (contours.size() > 5) contours.subList(4, contours.size() - 1).clear();

    MatOfPoint2f largest = null;
    for (MatOfPoint contour : contours) {
        MatOfPoint2f approx = new MatOfPoint2f();
        MatOfPoint2f c = new MatOfPoint2f();
        contour.convertTo(c, CvType.CV_32FC2);
        Imgproc.approxPolyDP(c, approx, Imgproc.arcLength(c, true) * 0.02, true);

        if (approx.total() == 4 && Imgproc.contourArea(contour) > 150) {
            // the contour has 4 points, it's valid
            largest = approx;
            break;
        }
    }

    return largest;
}
 
Example 3
Source File: MaxAreaScorer.java    From DogeCV with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Calculate the score
 * @param input - Input mat (Can be MatOfPoint for contours)
 * @return - Difference from perfect score
 */
@Override
public double calculateScore(Mat input) {
    if(!(input instanceof MatOfPoint)) return Double.MAX_VALUE;
    MatOfPoint contour = (MatOfPoint) input;
    double area = Imgproc.contourArea(contour);

    return -area * weight;
}
 
Example 4
Source File: PerfectAreaScorer.java    From DogeCV with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @param input - Input mat (Can be MatOfPoint for contours)
 * @return - Difference from perfect score
 */
@Override
public double calculateScore(Mat input) {
    if(!(input instanceof MatOfPoint)) return Double.MAX_VALUE;
    MatOfPoint contour = (MatOfPoint) input;
    double area = Imgproc.contourArea(contour);
    double areaDiffrence = Math.abs(perfectArea - area);
    return areaDiffrence * weight;
}
 
Example 5
Source File: ColorBlobDetector.java    From FaceT with Mozilla Public License 2.0 5 votes vote down vote up
public void process(Mat rgbaImage) {
    Imgproc.pyrDown(rgbaImage, mPyrDownMat);
    Imgproc.pyrDown(mPyrDownMat, mPyrDownMat);

    Imgproc.cvtColor(mPyrDownMat, mHsvMat, Imgproc.COLOR_RGB2HSV_FULL);

    Core.inRange(mHsvMat, mLowerBound, mUpperBound, mMask);
    Imgproc.dilate(mMask, mDilatedMask, new Mat());

    List<MatOfPoint> contours = new ArrayList<MatOfPoint>();

    Imgproc.findContours(mDilatedMask, contours, mHierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);

    // Find max contour area
    double maxArea = 0;
    Iterator<MatOfPoint> each = contours.iterator();
    while (each.hasNext()) {
        MatOfPoint wrapper = each.next();
        double area = Imgproc.contourArea(wrapper);
        if (area > maxArea)
            maxArea = area;
    }

    // Filter contours by area and resize to fit the original image size
    mContours.clear();
    each = contours.iterator();
    while (each.hasNext()) {
        MatOfPoint contour = each.next();
        if (Imgproc.contourArea(contour) > mMinContourArea*maxArea) {
            Core.multiply(contour, new Scalar(4,4), contour);
            mContours.add(contour);
        }
    }
}
 
Example 6
Source File: ContoursFinder.java    From go-bees with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Mat process(@NonNull Mat frame) {
    if (frame.empty()) {
        Log.e("Invalid input frame.");
        return null;
    }
    Mat tmp = frame.clone();
    // Finding outer contours
    contourList.clear();
    Imgproc.findContours(tmp, contourList, hierarchy,
            Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);
    // Filter bees
    Mat contours = new Mat(tmp.rows(), tmp.cols(), CvType.CV_8UC3);
    tmp.release();
    double area;
    Scalar color;
    numBees = 0;
    for (int i = 0; i < contourList.size(); i++) {
        area = Imgproc.contourArea(contourList.get(i));
        if (area > minArea && area < maxArea) {
            color = GREEN;
            numBees++;
        } else {
            color = RED;
        }
        // Draw contour
        Imgproc.drawContours(contours, contourList, i, color, -1);
    }
    return contours;
}
 
Example 7
Source File: ColorBlobDetector.java    From OpenCV-AndroidSamples with MIT License 5 votes vote down vote up
public void process(Mat rgbaImage) {
    Imgproc.pyrDown(rgbaImage, mPyrDownMat);
    Imgproc.pyrDown(mPyrDownMat, mPyrDownMat);

    Imgproc.cvtColor(mPyrDownMat, mHsvMat, Imgproc.COLOR_RGB2HSV_FULL);

    Core.inRange(mHsvMat, mLowerBound, mUpperBound, mMask);
    Imgproc.dilate(mMask, mDilatedMask, new Mat());

    List<MatOfPoint> contours = new ArrayList<MatOfPoint>();

    Imgproc.findContours(mDilatedMask, contours, mHierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);

    // Find max contour area
    double maxArea = 0;
    Iterator<MatOfPoint> each = contours.iterator();
    while (each.hasNext()) {
        MatOfPoint wrapper = each.next();
        double area = Imgproc.contourArea(wrapper);
        if (area > maxArea)
            maxArea = area;
    }

    // Filter contours by area and resize to fit the original image size
    mContours.clear();
    each = contours.iterator();
    while (each.hasNext()) {
        MatOfPoint contour = each.next();
        if (Imgproc.contourArea(contour) > mMinContourArea*maxArea) {
            Core.multiply(contour, new Scalar(4,4), contour);
            mContours.add(contour);
        }
    }
}
 
Example 8
Source File: ColorBlobDetector.java    From hand_finger_recognition_android with MIT License 5 votes vote down vote up
public void process(Mat rgbaImage) {
    Imgproc.pyrDown(rgbaImage, mPyrDownMat);
	Imgproc.pyrDown(mPyrDownMat, mPyrDownMat);

    Imgproc.cvtColor(mPyrDownMat, mHsvMat, Imgproc.COLOR_RGB2HSV_FULL);

    Core.inRange(mHsvMat, mLowerBound, mUpperBound, mMask);
    Imgproc.dilate(mMask, mDilatedMask, new Mat());

    List<MatOfPoint> contours = new ArrayList<MatOfPoint>();

    Imgproc.findContours(mDilatedMask, contours, mHierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);

    // Find max contour area
    double maxArea = 0;
    Iterator<MatOfPoint> each = contours.iterator();
    while (each.hasNext()) {
        MatOfPoint wrapper = each.next();
        double area = Imgproc.contourArea(wrapper);
        if (area > maxArea)
            maxArea = area;
    }

    // Filter contours by area and resize to fit the original image size
    mContours.clear();
    each = contours.iterator();
    while (each.hasNext()) {
        MatOfPoint contour = each.next();
        if (Imgproc.contourArea(contour) > mMinContourArea*maxArea) {
            Core.multiply(contour, new Scalar(4,4), contour);
            mContours.add(contour);
        }
    }
}
 
Example 9
Source File: NativeClass.java    From AndroidDocumentScanner with MIT License 4 votes vote down vote up
public int compare(MatOfPoint2f m1, MatOfPoint2f m2) {
    double area1 = Imgproc.contourArea(m1);
    double area2 = Imgproc.contourArea(m2);
    return (int) Math.ceil(area2 - area1);
}
 
Example 10
Source File: Proc.java    From android-object-distance with Apache License 2.0 4 votes vote down vote up
public static  double findMarkerWidth(String imgPath){
    Mat frame = Highgui.imread(imgPath);
    Mat gscale = new Mat();
    Mat blur = new Mat();
    Mat edged = new Mat();

    // convert the image to grayscale, blur it, and detect edges
    if(frame.channels()>1)
        Imgproc.cvtColor(frame, gscale, Imgproc.COLOR_BGR2GRAY);
    else
        gscale = frame;

    Imgproc.GaussianBlur(gscale, blur, new Size(5, 5), 0);
    Imgproc.Canny(blur, edged, 35, 125);

    // find the contours in the edged image and keep the largest one;
    // we'll assume that this is our piece of paper in the image
    List<MatOfPoint> contours = new ArrayList<>();
    Mat hierarchy = new Mat(edged.width(), edged.height(), CvType.CV_8UC1);
    Imgproc.findContours(edged.clone(), contours, hierarchy, Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_SIMPLE);
    int max_idx = 0;

    // if any contour exist...
    if (hierarchy.size().height > 0 && hierarchy.size().width > 0)
    {
        double max_area = 0;
        double area;
        // find the contour with largest area
        for (int idx = 0; idx >= 0; idx = (int) hierarchy.get(0, idx)[0])
        {
            area = Imgproc.contourArea(contours.get(idx));
            if(area > max_area){
                max_area = area;
                max_idx = idx;
            }
            Imgproc.drawContours(frame, contours, idx, new Scalar(0, 0, 255));
        }

        //Riz: Save File
        //Imgproc.drawContours(frame, contours, max_idx, new Scalar(250, 0, 0));
        byte[] bytes = new byte[ frame.rows() * frame.cols() * frame.channels() ];


        File file = new File(CameraActivity.activity.getExternalFilesDir(null), "pic_contour"+ Integer.toString(pic_count) + ".jpg");
        pic_count++;

        Boolean bool = null;
        String filename = file.toString();
        bool = Highgui.imwrite(filename, frame);

        if (bool == true)
            Log.d(LOG_TAG, "SUCCESS writing image to external storage");
        else
            Log.d(LOG_TAG, "Fail writing image to external storage");

        Log.i(LOG_TAG, "Max Area: " + Double.toString(max_area));
    }
    else{
        Log.e(LOG_TAG, "No Contour Found!");
    }

    MatOfPoint2f newPoint = new MatOfPoint2f(contours.get(max_idx).toArray());

    return Imgproc.arcLength(newPoint, true);
}
 
Example 11
Source File: ResistorImageProcessor.java    From ResistorScanner with MIT License 4 votes vote down vote up
private void findLocations(Mat searchMat)
{
    _locationValues.clear();
    SparseIntArray areas = new SparseIntArray(4);

    for(int i = 0; i < NUM_CODES; i++)
    {
        Mat mask = new Mat();
        List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
        Mat hierarchy = new Mat();

        if(i == 2)
        {
            // combine the two ranges for red
            Core.inRange(searchMat, LOWER_RED1, UPPER_RED1, mask);
            Mat rmask2 = new Mat();
            Core.inRange(searchMat, LOWER_RED2, UPPER_RED2, rmask2);
            Core.bitwise_or(mask, rmask2, mask);
        }
        else
            Core.inRange(searchMat, COLOR_BOUNDS[i][0], COLOR_BOUNDS[i][1], mask);

        Imgproc.findContours(mask, contours, hierarchy, Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_SIMPLE);
        for (int contIdx = 0; contIdx < contours.size(); contIdx++)
        {
            int area;
            if ((area = (int)Imgproc.contourArea(contours.get(contIdx))) > 20)
            {
                Moments M = Imgproc.moments(contours.get(contIdx));
                int cx = (int) (M.get_m10() / M.get_m00());

                // if a colour band is split into multiple contours
                // we take the largest and consider only its centroid
                boolean shouldStoreLocation = true;
                for(int locIdx = 0; locIdx < _locationValues.size(); locIdx++)
                {
                    if(Math.abs(_locationValues.keyAt(locIdx) - cx) < 10)
                    {
                        if (areas.get(_locationValues.keyAt(locIdx)) > area)
                        {
                            shouldStoreLocation = false;
                            break;
                        }
                        else
                        {
                            _locationValues.delete(_locationValues.keyAt(locIdx));
                            areas.delete(_locationValues.keyAt(locIdx));
                        }
                    }
                }

                if(shouldStoreLocation)
                {
                    areas.put(cx, area);
                    _locationValues.put(cx, i);
                }
            }
        }
    }
}
 
Example 12
Source File: AAVActivity.java    From AAV with GNU General Public License v2.0 4 votes vote down vote up
@Override
public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
	synchronized (inputFrame) {

		_rgbaImage = inputFrame.rgba();

		if (android.os.Build.MODEL.equalsIgnoreCase("Nexus 5X")) {
			Core.flip(_rgbaImage, _rgbaImage, -1);
		}

		double current_contour;

		// In contrast to the C++ interface, Android API captures images in the RGBA format.
		// Also, in HSV space, only the hue determines which color it is. Saturation determines
		// how 'white' the color is, and Value determines how 'dark' the color is.
		Imgproc.cvtColor(_rgbaImage, _hsvMat, Imgproc.COLOR_RGB2HSV_FULL);

		Core.inRange(_hsvMat, _lowerThreshold, _upperThreshold, _processedMat);

		// Imgproc.dilate(_processedMat, _dilatedMat, new Mat());
		Imgproc.erode(_processedMat, _dilatedMat, new Mat());
		Imgproc.findContours(_dilatedMat, contours, new Mat(), Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);
		MatOfPoint2f points = new MatOfPoint2f();
		_contourArea = 7;
		for (int i = 0, n = contours.size(); i < n; i++) {
			current_contour = Imgproc.contourArea(contours.get(i));
			if (current_contour > _contourArea) {
				_contourArea = current_contour;
				contours.get(i).convertTo(points, CvType.CV_32FC2); // contours.get(x) is a single MatOfPoint, but to use minEnclosingCircle we need to pass a MatOfPoint2f so we need to do a
				// conversion
			}
		}
		if (!points.empty() && _contourArea > MIN_CONTOUR_AREA) {
			Imgproc.minEnclosingCircle(points, _centerPoint, null);
			// Core.circle(_rgbaImage, _centerPoint, 3, new Scalar(255, 0, 0), Core.FILLED);
			if (_showContourEnable)
				Core.circle(_rgbaImage, _centerPoint, (int) Math.round(Math.sqrt(_contourArea / Math.PI)), new Scalar(255, 0, 0), 3, 8, 0);// Core.FILLED);
		}
		contours.clear();
	}
	return _rgbaImage;
}
 
Example 13
Source File: CropImage.java    From reader with MIT License 4 votes vote down vote up
private void makeDefault() {
            HighlightView hv = new HighlightView(mImageView);

            int width = mBitmap.getWidth();
            int height = mBitmap.getHeight();

            Rect imageRect = new Rect(0, 0, width, height);

            // make the default size about 4/5 of the width or height
//            int cropWidth = Math.min(width, height) * 4 / 5;
//            int cropHeight = cropWidth;
            int cropWidth = width;
            int cropHeight = height;

            if (mAspectX != 0 && mAspectY != 0) {
                if (mAspectX > mAspectY) {
                	// �����辩缉���
                    cropHeight = cropWidth * mAspectY ;// mAspectX;
                } else {
                    cropWidth = cropHeight * mAspectX ;// mAspectY;
                }
            }

            int x = (width - cropWidth) / 2;
            int y = (height - cropHeight) / 2;
            
            Mat imgSource = new Mat();
            Utils.bitmapToMat(mBitmap, imgSource);
            //convert the image to black and white 
            Imgproc.cvtColor(imgSource, imgSource, Imgproc.COLOR_BGR2GRAY);
            //convert the image to black and white does (8 bit)
            Imgproc.Canny(imgSource, imgSource, 50, 50);

            //apply gaussian blur to smoothen lines of dots
            Imgproc.GaussianBlur(imgSource, imgSource, new  org.opencv.core.Size(5, 5), 5);

            //find the contours
            List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
            Imgproc.findContours(imgSource, contours, new Mat(), Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_SIMPLE);

            double maxArea = -1;
            int maxAreaIdx = -1;
            Log.d("size",Integer.toString(contours.size()));
            MatOfPoint temp_contour = contours.get(0); //the largest is at the index 0 for starting point
            MatOfPoint2f approxCurve = new MatOfPoint2f();
            MatOfPoint largest_contour = contours.get(0);
            //largest_contour.ge
            List<MatOfPoint> largest_contours = new ArrayList<MatOfPoint>();
            //Imgproc.drawContours(imgSource,contours, -1, new Scalar(0, 255, 0), 1);

            for (int idx = 0; idx < contours.size(); idx++) {
                temp_contour = contours.get(idx);
                double contourarea = Imgproc.contourArea(temp_contour);
                //compare this contour to the previous largest contour found
                if (contourarea > maxArea) {
                    //check if this contour is a square
                    MatOfPoint2f new_mat = new MatOfPoint2f( temp_contour.toArray() );
                    int contourSize = (int)temp_contour.total();
                    MatOfPoint2f approxCurve_temp = new MatOfPoint2f();
                    Imgproc.approxPolyDP(new_mat, approxCurve_temp, contourSize*0.05, true);
                    if (approxCurve_temp.total() == 4) {
                        maxArea = contourarea;
                        maxAreaIdx = idx;
                        approxCurve=approxCurve_temp;
                        largest_contour = temp_contour;
                    }
                }
            }

           Imgproc.cvtColor(imgSource, imgSource, Imgproc.COLOR_BayerBG2RGB);
           double[] temp_double;
           float x1, y1, x2, y2;
           temp_double = approxCurve.get(0,0);       
           Point p1 = new Point(temp_double[0], temp_double[1]);
           x1 = (float)temp_double[0];
           y1 = (float)temp_double[1];
           //Core.circle(imgSource,p1,55,new Scalar(0,0,255));
           //Imgproc.warpAffine(sourceImage, dummy, rotImage,sourceImage.size());
           temp_double = approxCurve.get(1,0);       
           Point p2 = new Point(temp_double[0], temp_double[1]);
          // Core.circle(imgSource,p2,150,new Scalar(255,255,255));
           temp_double = approxCurve.get(2,0);       
           Point p3 = new Point(temp_double[0], temp_double[1]);
           x2 = (float)temp_double[0];
           y2 = (float)temp_double[1];
           //Core.circle(imgSource,p3,200,new Scalar(255,0,0));
           temp_double = approxCurve.get(3,0);       
           Point p4 = new Point(temp_double[0], temp_double[1]);

            RectF cropRect = new RectF(x, y, x + cropWidth, y + cropHeight);
            //RectF cropRect = new RectF(x1, y1, x2, y2);
         // �����辩缉���
            
            hv.setup(mImageMatrix, imageRect, cropRect, mCircleCrop,false
                     /*mAspectX != 0 && mAspectY != 0*/);
            mImageView.add(hv);
        }
 
Example 14
Source File: BallDetector.java    From opencv-fun with GNU Affero General Public License v3.0 4 votes vote down vote up
private void extractCircles (Mat mask, List<Circle> balls, List<BallCluster> ballClusters, List<MatOfPoint> contours) {
	// clear input
	balls.clear();
	ballClusters.clear();
	contours.clear();
	
	// find the contours
	Imgproc.findContours(mask.clone(), contours, new Mat(), Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_SIMPLE);
	
	// iterate through the contours, find single balls and clusters of balls touching each other
	double minArea = Math.PI * (calib.getBallRadius() * 0.9f) * (calib.getBallRadius() * 0.9f); // minimal ball area
	double maxArea = Math.PI * (calib.getBallRadius() * 1.1f) * (calib.getBallRadius() * 1.1f); // maximal ball area

	for (int i = 0; i < contours.size(); i++) {
		double area = Imgproc.contourArea(contours.get(i));
		if (area > minArea) {				
			if (area < maxArea) {
				// we found a ball
				float[] radius = new float[1];
				Point center = new Point();
				Imgproc.minEnclosingCircle(new MatOfPoint2f(contours.get(i).toArray()), center, radius);
				balls.add(new Circle(center.x, center.y, calib.getBallRadius()));
			} else {
				// we found a cluster of balls
				int numBalls = (int)(area / (Math.PI * calib.getBallRadius() * calib.getBallRadius() * 0.9));
				
				// draw the contours to a bit mask
				Mat hough = Mat.zeros(mask.size(), CvType.CV_8U);
				Imgproc.drawContours(hough, contours, i, new Scalar(255, 255, 255), -2);
				
				// detect hough circles, try different params until we hit the number of balls
				Mat houghCircles = new Mat();
				int hit = 0;
				for(int j = 8; j < 20; j++) {
					Imgproc.HoughCircles(hough, houghCircles, Imgproc.CV_HOUGH_GRADIENT, 2, calib.getBallRadius() * 0.9 * 2, 255, j, (int)(calib.getBallRadius() * 0.9), (int)(calib.getBallRadius() * 1.1));
					if(houghCircles.cols() <= numBalls) {
						hit++;
						if(hit == 4) break;
					}
				}
				
				
				List<Circle> estimatedCircles = new ArrayList<Circle>();
				for(int j = 0; j < houghCircles.cols(); j++) {
					double[] circle = houghCircles.get(0, j);
					if(circle != null) {
						estimatedCircles.add(new Circle(circle[0], circle[1], calib.getBallRadius()));
					}
				}
				
				ballClusters.add(new BallCluster(contours.get(i), numBalls, estimatedCircles));
			}
		}
	}
}
 
Example 15
Source File: Contour.java    From FTCVision with MIT License 2 votes vote down vote up
/**
 * Get the area of the contour
 * <p/>
 * A highly precise method that integrates the contour with respect to its arc length.
 *
 * @return Area of the contour
 */
public double area() {
    return Imgproc.contourArea(mat);
}