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

The following examples show how to use org.opencv.imgproc.Imgproc#boundingRect() . 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: RatioScorer.java    From DogeCV with GNU General Public License v3.0 6 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 score = Double.MAX_VALUE;

    // Get bounding rect of contour
    Rect rect = Imgproc.boundingRect(contour);
    double x = rect.x;
    double y = rect.y;
    double w = rect.width;
    double h = rect.height;

    double cubeRatio = Math.max(Math.abs(h/w), Math.abs(w/h)); // Get the ratio. We use max in case h and w get swapped??? it happens when u account for rotation
    double ratioDiffrence = Math.abs(cubeRatio - perfectRatio);
    return ratioDiffrence * weight;
}
 
Example 3
Source File: MovementDetectionProcessor.java    From Camdroid with Apache License 2.0 5 votes vote down vote up
protected void execute() {
    out = gray();

    Imgproc.equalizeHist(out, out);

    synchronized (mog) {
        mog.apply(out, this.mask, (double) (-10 + learning_rate) / 10);
    }

    Mat kernel = Imgproc.getStructuringElement(Imgproc.MORPH_DILATE,
            new Size(3, 3));
    Imgproc.dilate(mask, mask, kernel);

    ArrayList<MatOfPoint> contours = new ArrayList<MatOfPoint>();
    Imgproc.findContours(this.mask, contours, new Mat(),
            Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);

    double maxheight = object_max_size * this.in.height() / 100;
    double minheight = object_min_size * this.in.height() / 100;

    Iterator<MatOfPoint> each = contours.iterator();
    each = contours.iterator();
    while (each.hasNext()) {
        MatOfPoint contour = each.next();
        Rect rect = Imgproc.boundingRect(contour);
        if (rect.height > minheight && rect.height < maxheight) {
            Imgproc.rectangle(out, rect.tl(), rect.br(), new Scalar(255,
                    0, 0), 1);
        }
    }
}
 
Example 4
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 5
Source File: BackgroundSubtractionOp.java    From StormCV with Apache License 2.0 4 votes vote down vote up
@Override
public List<CVParticle> execute(CVParticle input) throws Exception {
	ArrayList<CVParticle> result = new ArrayList<CVParticle>();
	
	// sanity check
	if( !( input instanceof Frame ) ) 
		return result;
	
	// initialize input and output result
	Frame frame  = (Frame) input;
	String streamId = frame.getStreamId();
		
	// check if input frame has an image
	if( frame.getImageType().equals(Frame.NO_IMAGE) ) 
		return result;

	// decode input image to OpenCV Mat
	Mat inputImage = ImageUtils.bytes2Mat(frame.getImageBytes());
	
	if(!mogs.containsKey(streamId) ){
		mogs.put(streamId, new BackgroundSubtractorMOG());
	}
	// update the background model
	Mat mogMask = new Mat();
    mogs.get(streamId).apply(inputImage, mogMask, 1f/framesHistory);
    
   	// find contours for the blobs
   	List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
   	Imgproc.findContours(mogMask.clone(), contours, new Mat(), 0 /*CV_RETR_EXTERNAL*/, 2 /*CV_CHAIN_APPROX_SIMPLE*/);
   	ArrayList<Descriptor> descriptors = new ArrayList<Descriptor>();
   	for(MatOfPoint contour : contours){
   		float[] polygon = new float[contour.rows()*2];
   		for(int row=0; row<contour.rows(); row++){
   			double[] point = contour.get(row, 0);
   			polygon[row*2] = (float)point[0];
   			polygon[row*2+1] = (float)point[1];
   		}
   		Rect rect = Imgproc.boundingRect(contour);
   		if(rect.width < 5 || rect.height < 5 ) continue;
   		descriptors.add(new Descriptor(streamId, input.getSequenceNr(), new Rectangle(rect.x, rect.y, rect.width, rect.height), 0, polygon));
   	}
   	Feature feature = new Feature(streamId, input.getSequenceNr(), featureName, 0, descriptors, null);
   	if(!outputFrame) {
   		result.add(feature);
   		return result;
   	}
   	if(binaryFrame){
   		byte[] outputBytes = ImageUtils.Mat2ImageBytes( mogMask, frame.getImageType() );
           frame.setImage( outputBytes, frame.getImageType() );
   	}
   	frame.getFeatures().add(feature);
   	result.add(frame);
   	return result;
}
 
Example 6
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);
}