簡體   English   中英

Android OpenCV - 在輪廓上繪制矩形

[英]Android OpenCV - Draw rectangle on contours

如何將List<MatOfPoint> contours轉換為Rect[] contoursArray ,以便我可以使用Core.rectangle(mRgba, contoursArray[i].tl(), contoursArray[i].br(), (255,0,0,255), 3)在上面畫一個矩形?

public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
    mRgba = inputFrame.rgba();
    mGray = inputFrame.gray();
    //Touch screen to track by color and draw rectangle on it
    if (mItem_select && Color_Select){
        mDetector.process(mRgba);
        List < MatOfPoint > contours = mDetector.getContours();
        Log.e(TAG, "Contours count: " + contours.size());
        Imgproc.drawContours(mRgba, contours, - 1, Rectangle_Color);
        //Draw rectangle on it
        Rect[] contoursArray = contours.toArray(); //error:Type mismatch: cannot convert from Object[] to Rect[]
        Core.rectangle(mRgba, contoursArray.tl(), contoursArray.br(), (255, 0, 0, 255), 3); //error:Cannot invoke tl() on the array type Rect[]、Cannot invoke br() on the array type Rect[]

        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;
}

試試這個在countours上繪制矩形

MatOfPoint2f approxCurve = new MatOfPoint2f();

        //For each contour found
        for (int i=0; i<contours.size(); i++)
        {
            //Convert contours(i) from MatOfPoint to MatOfPoint2f
            MatOfPoint2f contour2f = new MatOfPoint2f( contours.get(i).toArray() );
            //Processing on mMOP2f1 which is in type MatOfPoint2f
            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)
           Point(rect.x+rect.width,rect.y+rect.height) , new Scalar(255, 0, 0, 255), 3); 
        }

這里提供了非常相似的問題和工作答案: http//answers.opencv.org/question/25755/drawing-bounding-box-in-java/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM