OpenCV (33): Calculate contour area and contour length

1.Introduction to contour area and contour length

       Contour Area refers to the total area of ​​the area enclosed by the contour. Typically, the unit of outline area is pixels squared.

        Contour Length, also known as Perimeter, represents the length of the closed boundary of the contour. The boundary of the contour can be regarded as a continuous path composed of a series of adjacent pixel points, and the contour length is the total length of the path. Typically, the unit of outline length is pixels.

2.Contour area contourArea()

double cv::contourArea ( InputArray contour,

bool    oriented = false

)

  • contour: pixels of the contour
  • Oriented; whether the area of ​​the area has a direction flag, true means that the area is directional, false means it does not have directionality, and the default value is false which does not have directionality.

3.Contour length arcLength()

double cv::arcLength ( InputArray curve,

bool    closed

)

  • curve: 2D pixels of outline or curve.
  • closed: Flag whether the contour or curve is closed, true means closed.

4. Sample code

//计算轮廓面积与长度
void Contour_areaAndlength(Mat image){
    Mat gray,binary;
    cvtColor(image,gray,COLOR_BGR2GRAY);//灰度化
    GaussianBlur(gray,gray,Size(9,9),2,2);//滤波
    threshold(gray,binary,170,255,THRESH_BINARY|THRESH_OTSU);//自适应二值化
    //轮廓检测
    vector<vector<Point>> contours;//轮廓
    vector<Vec4i> hierarchy;//存放轮廓结构变量
    findContours(binary,contours,hierarchy,RETR_TREE,CHAIN_APPROX_SIMPLE,Point());
    ostringstream ss;
    //输出轮廓面积
    for(int t=0;t<contours.size();t++){
        double areal= contourArea(contours[t]);
        ss <<"第"<< t<<"轮廓面积:"<<areal<<std::endl;
    }
    //输出轮廓长度
    for(int t=0;t<contours.size();t++){
        double length2= arcLength(contours[t],true);
        ss <<"第"<< t<<"轮廓长度:"<<length2<<std::endl;
    }
    LOGD("%s",ss.str().c_str());
}

Guess you like

Origin blog.csdn.net/weixin_63357306/article/details/132787963
Recommended