欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

基于opencv计算星云图像的面积与周长

程序员文章站 2022-05-20 19:40:14
...

基于opencv计算星云图像的面积与周长

需求:以上图像是太空望远镜的星云图像,要求通过opencv计算出星云的面积与周长。

解决思路:通过二值分割+图像形态学+轮廓提取。

代码如下

#include <opencv2/opencv.hpp>
#include <iostream>
#include <math.h>

using namespace cv;
using namespace std;

int main()
{
    Mat src_image = imread("1.jpg");
    if(!src_image.data)
    {
        cout << "src image load failed!" << endl;
        return -1;
    }
    namedWindow("src image", WINDOW_NORMAL);
    imshow("src image", src_image);

    /*此处高斯去燥有助于后面二值化处理的效果*/
    Mat blur_image;
    GaussianBlur(src_image, blur_image, Size(15, 15), 0, 0);
    imshow("GaussianBlur", blur_image);

    /*灰度变换与二值化*/
    Mat gray_image, binary_image;
    cvtColor(blur_image, gray_image, COLOR_BGR2GRAY);
    threshold(gray_image, binary_image, 0, 255, THRESH_BINARY|THRESH_TRIANGLE);
    imshow("binary", binary_image);

    /*形态学闭操作*/
    Mat morph_image;
    Mat kernel = getStructuringElement(MORPH_RECT, Size(3, 3), Point(-1, -1));
    morphologyEx(binary_image, morph_image, MORPH_CLOSE, kernel, Point(-1, -1), 2);
    imshow("morphology", morph_image);

    /*查找外轮廓*/
    vector< vector<Point> > contours;
    vector<Vec4i> hireachy;
    findContours(morph_image, contours, hireachy, CV_RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point());
    Mat result_image = Mat::zeros(src_image.size(), CV_8UC3);
    for(size_t t = 0; t < contours.size(); t++)
    {
        /*过滤掉小的干扰轮廓*/
        Rect rect = boundingRect(contours[t]);
        if(rect.width < src_image.cols/2)
            continue;
        if(rect.width > (src_image.cols - 20))
            continue;

        /*计算面积与周长*/
        double area = contourArea(contours[t]);
        double len = arcLength(contours[t], true);

        drawContours(result_image, contours, static_cast<int>(t), Scalar(0, 0, 255), 1, 8, hireachy);
        cout << "area of start cloud: " << area << endl;
        cout << "len of start cloud: " << len << endl;
    }

    imshow("result image", result_image);

    waitKey(0);

    return 0;
}
  图像处理后的提取的轮廓图如下

基于opencv计算星云图像的面积与周长

  根据以上的轮廓图可以计算出星云的面积与周长,详见以上代码。