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

The following examples show how to use org.opencv.imgproc.Imgproc#drawContours() . 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: MainActivity.java    From MOAAP with MIT License 8 votes vote down vote up
void Contours() {
    Mat grayMat = new Mat();
    Mat cannyEdges = new Mat();
    Mat hierarchy = new Mat();

    List<MatOfPoint> contourList = new ArrayList<MatOfPoint>(); //A list to store all the contours

    //Converting the image to grayscale
    Imgproc.cvtColor(originalMat, grayMat, Imgproc.COLOR_BGR2GRAY);

    Imgproc.Canny(originalMat, cannyEdges, 10, 100);

    //finding contours
    Imgproc.findContours(cannyEdges, contourList, hierarchy, Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_SIMPLE);

    //Drawing contours on a new image
    Mat contours = new Mat();
    contours.create(cannyEdges.rows(), cannyEdges.cols(), CvType.CV_8UC3);
    Random r = new Random();
    for (int i = 0; i < contourList.size(); i++) {
        Imgproc.drawContours(contours, contourList, i, new Scalar(r.nextInt(255), r.nextInt(255), r.nextInt(255)), -1);
    }
    //Converting Mat back to Bitmap
    Utils.matToBitmap(contours, currentBitmap);
    imageView.setImageBitmap(currentBitmap);
}
 
Example 2
Source File: ColorBlobDetectionActivity.java    From OpenCV-AndroidSamples with MIT License 7 votes vote down vote up
public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
    mRgba = inputFrame.rgba();

    if (mIsColorSelected) {
        mDetector.process(mRgba);
        List<MatOfPoint> contours = mDetector.getContours();
        Log.e(TAG, "Contours count: " + contours.size());
        Imgproc.drawContours(mRgba, contours, -1, CONTOUR_COLOR);

        Mat colorLabel = mRgba.submat(4, 68, 4, 68);
        colorLabel.setTo(mBlobColorRgba);

        Mat spectrumLabel = mRgba.submat(4, 4 + mSpectrum.rows(), 70, 70 + mSpectrum.cols());
        mSpectrum.copyTo(spectrumLabel);
    }

    return mRgba;
}
 
Example 3
Source File: MainActivity.java    From Android_OCV_Movement_Detection with MIT License 6 votes vote down vote up
public Mat onCameraFrame(CvCameraViewFrame inputFrame) 
{   
	contours.clear();
	//gray frame because it requires less resource to process
	mGray = inputFrame.gray(); 
	
	//this function converts the gray frame into the correct RGB format for the BackgroundSubtractorMOG apply function
	Imgproc.cvtColor(mGray, mRgb, Imgproc.COLOR_GRAY2RGB); 
	
	//apply detects objects moving and produces a foreground mask
	//the lRate updates dynamically dependent upon seekbar changes
	sub.apply(mRgb, mFGMask, lRate); 

	//erode and dilate are used  to remove noise from the foreground mask
	Imgproc.erode(mFGMask, mFGMask, new Mat());
	Imgproc.dilate(mFGMask, mFGMask, new Mat());
	
	//drawing contours around the objects by first called findContours and then calling drawContours
	//RETR_EXTERNAL retrieves only external contours
	//CHAIN_APPROX_NONE detects all pixels for each contour
	Imgproc.findContours(mFGMask, contours, new Mat(), Imgproc.RETR_EXTERNAL , Imgproc.CHAIN_APPROX_NONE);
	
	//draws all the contours in red with thickness of 2
	Imgproc.drawContours(mRgb, contours, -1, new Scalar(255, 0, 0), 2);
	
	return mRgb;
}
 
Example 4
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 5
Source File: Finder.java    From SikuliNG with MIT License 5 votes vote down vote up
public static List<Element> detectChanges(Mat base, Mat mChanged) {
  int PIXEL_DIFF_THRESHOLD = 3;
  int IMAGE_DIFF_THRESHOLD = 5;
  Mat mBaseGray = Element.getNewMat();
  Mat mChangedGray = Element.getNewMat();
  Mat mDiffAbs = Element.getNewMat();
  Mat mDiffTresh = Element.getNewMat();
  Mat mChanges = Element.getNewMat();
  List<Element> rectangles = new ArrayList<>();

  Imgproc.cvtColor(base, mBaseGray, toGray);
  Imgproc.cvtColor(mChanged, mChangedGray, toGray);
  Core.absdiff(mBaseGray, mChangedGray, mDiffAbs);
  Imgproc.threshold(mDiffAbs, mDiffTresh, PIXEL_DIFF_THRESHOLD, 0.0, Imgproc.THRESH_TOZERO);
  if (Core.countNonZero(mDiffTresh) > IMAGE_DIFF_THRESHOLD) {
    Imgproc.threshold(mDiffAbs, mDiffAbs, PIXEL_DIFF_THRESHOLD, 255, Imgproc.THRESH_BINARY);
    Imgproc.dilate(mDiffAbs, mDiffAbs, Element.getNewMat());
    Mat se = Imgproc.getStructuringElement(Imgproc.MORPH_ELLIPSE, new Size(5, 5));
    Imgproc.morphologyEx(mDiffAbs, mDiffAbs, Imgproc.MORPH_CLOSE, se);

    List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
    Mat mHierarchy = Element.getNewMat();
    Imgproc.findContours(mDiffAbs, contours, mHierarchy, Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_SIMPLE);
    rectangles = contoursToRectangle(contours);

    Core.subtract(mDiffAbs, mDiffAbs, mChanges);
    Imgproc.drawContours(mChanges, contours, -1, new Scalar(255));
    //logShow(mDiffAbs);
  }
  return rectangles;
}
 
Example 6
Source File: Finder.java    From SikuliNG with MIT License 5 votes vote down vote up
public static Mat drawContoursInImage(List<MatOfPoint> contours, Mat mBase) {
  Mat mResult = Element.getNewMat();
  Mat mWork = new Mat();
  Imgproc.cvtColor(mBase, mWork, toGray);
  Imgproc.cvtColor(mWork, mResult, toColor);
  Imgproc.drawContours(mResult, contours, -1, new Scalar(0, 0, 255));
  return mResult;
}
 
Example 7
Source File: StoneDetector.java    From DogeCV with GNU General Public License v3.0 4 votes vote down vote up
@Override
public Mat process(Mat input) {
    screenPositions.clear();
    foundRects.clear();
    
    input.copyTo(rawImage);
    input.copyTo(workingMat);
    input.copyTo(displayMat);
    input.copyTo(yellowMask);

    // Imgproc.GaussianBlur(workingMat,workingMat,new Size(5,5),0);
    filter.process(workingMat.clone(), yellowMask);

    List<MatOfPoint> contoursYellow = new ArrayList<>();
    Imgproc.findContours(yellowMask, contoursYellow, hierarchy, Imgproc.RETR_TREE, Imgproc.CHAIN_APPROX_SIMPLE);
    Imgproc.drawContours(displayMat,contoursYellow,-1,new Scalar(230,70,70),2);

    // Current result
    ArrayList<Rect> bestRects = new ArrayList<>();
    double bestDifference = Double.MAX_VALUE; // MAX_VALUE since less difference = better

    Collections.sort(contoursYellow, new Comparator<MatOfPoint>() {
        @Override
        public int compare(MatOfPoint matOfPoint, MatOfPoint t1) {
            return calculateScore(matOfPoint) > calculateScore(t1) ? 1 : 0;
        }
    });

    List<MatOfPoint> subList = contoursYellow;

    if (contoursYellow.size() > stonesToFind) {
        subList = contoursYellow.subList(0, stonesToFind);
    }

    for (MatOfPoint contour : subList) {
        Rect rect = Imgproc.boundingRect(contour);

        // Show chosen result
        Imgproc.rectangle(displayMat, rect.tl(), rect.br(), new Scalar(255, 0, 0), 4);
        Imgproc.putText(displayMat, "Chosen", rect.tl(), 0, 1, new Scalar(255, 255, 255));

        screenPositions.add(new Point(rect.x, rect.y));
        foundRects.add(rect);
    }

    if (foundRects.size() > 0) {
        found = true;
    }
    else {
        found = false;
    }

    switch (stageToRenderToViewport) {
        case THRESHOLD: {
            Imgproc.cvtColor(yellowMask, yellowMask, Imgproc.COLOR_GRAY2BGR);

            return yellowMask;
        }
        case RAW_IMAGE: {
            return rawImage;
        }
        default: {
            return displayMat;
        }
    }
}
 
Example 8
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 9
Source File: Drawing.java    From FTCVision with MIT License 4 votes vote down vote up
private static void drawContour(Mat img, Contour contour, Color color, int thickness) {
    List<MatOfPoint> contoursOut = new ArrayList<>();
    contoursOut.add(contour.getData());
    Imgproc.drawContours(img, contoursOut, -1, color.getScalarRGBA(), thickness);
}
 
Example 10
Source File: Drawing.java    From FTCVision with MIT License 4 votes vote down vote up
public static void drawContours(Mat img, List<Contour> contours, Color color, int thickness) {
    List<MatOfPoint> contoursOut = new ArrayList<>();
    for (Contour contour : contours)
        contoursOut.add(contour.getData());
    Imgproc.drawContours(img, contoursOut, -1, color.getScalarRGBA(), thickness);
}
 
Example 11
Source File: Finder.java    From SikuliNG with MIT License 4 votes vote down vote up
public static Mat drawContours(List<MatOfPoint> contours, Mat mBase) {
  Mat mResult = Element.getNewMat();
  Core.subtract(mBase, mBase, mResult);
  Imgproc.drawContours(mResult, contours, -1, new Scalar(255));
  return mResult;
}
 
Example 12
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 13
Source File: MainActivity.java    From effective_android_sample with Apache License 2.0 4 votes vote down vote up
/**
 * OpenCVで
 * @param bmpOrig
 */
private void extractObject(Bitmap bmpOrig) {

    // まずオリジナルのビットマップを表示
    mImageView1.setImageBitmap(bmpOrig);
    // 高さと幅を取得
    int height = bmpOrig.getHeight();
    int width = bmpOrig.getWidth();
    
    // OpenCVオブジェクトの用意
    Mat matOrig = new Mat(height,width,CvType.CV_8UC4); 
    // ビットマップをOpenCVオブジェクトに変換
    Utils.bitmapToMat(bmpOrig, matOrig);
    
    /**
     * グレースケールに変換
     */
    Mat matGray = new Mat(height,width,CvType.CV_8UC1);
    Imgproc.cvtColor(matOrig, matGray, Imgproc.COLOR_RGB2GRAY);
    // 表示
    Bitmap bmpGray = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Utils.matToBitmap(matGray, bmpGray);
    mImageView2.setImageBitmap(bmpGray);

    /**
     * グレースケール→二値化    
     */
    Mat matBlack = new Mat(height,width,CvType.CV_8UC1);
    // 二値化
    Imgproc.threshold(matGray, matBlack, sTH, 255, Imgproc.THRESH_BINARY);
    // 表示
    Bitmap bmpBlack = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Utils.matToBitmap(matBlack, bmpBlack);
    mImageView3.setImageBitmap(bmpBlack);

    /**
     * グレースケール→二値化→輪郭塗りつぶし
     */
    // 輪郭を抽出する
    ArrayList<MatOfPoint> contours = new ArrayList<MatOfPoint>();
    Mat hierarchy = new Mat(matBlack.height(),matBlack.width(),CvType.CV_8UC1);
    int mode = Imgproc.RETR_EXTERNAL;
    int method = Imgproc.CHAIN_APPROX_SIMPLE;

    // 輪郭を抽出する
    Imgproc.findContours(matBlack, contours, hierarchy, mode, method);
    // 輪郭を描く
    Scalar color = new Scalar(255.f, 0.f, 0.f, 0.f);
    Imgproc.drawContours(matBlack, contours, -1, color, 2);
    // 表示
    Bitmap bmpContour = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    org.opencv.android.Utils.matToBitmap(matBlack, bmpContour);
    mImageView4.setImageBitmap(bmpContour);

    // 抽出した輪郭の内部を塗りつぶす
    Imgproc.drawContours(matBlack, contours, -1, color, -1);
    // 表示
    Bitmap bmpContour2 = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    org.opencv.android.Utils.matToBitmap(matBlack, bmpContour2);
    mImageView5.setImageBitmap(bmpContour2);

    
    /**
     * 二値化したマスクを使ってオブジェクトだけをとりだす
     */
    Mat matObject = new Mat(height,width,CvType.CV_8UC4); 
    Core.add(matObject, matOrig, matObject, matBlack);  
    // 表示
    Bitmap bmpObject = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    org.opencv.android.Utils.matToBitmap(matObject, bmpObject);
    mImageView6.setImageBitmap(bmpObject);

    /**
     * とりだしたオブジェクトに外接する矩形のみをBMPとして抜き出す
     */
    Rect rect = Imgproc.boundingRect(contours.get(0));
    Mat matCut = new Mat(matObject, rect);
    // 表示
    Bitmap bmpCut = Bitmap.createBitmap(matCut.cols(), matCut.rows(), Bitmap.Config.ARGB_8888);
    org.opencv.android.Utils.matToBitmap(matCut, bmpCut);
    mImageView7.setImageBitmap(bmpCut);
}