• opencv——对象提取与测量


     1 #include <opencv2/opencv.hpp>
     2 #include <iostream>
     3 #include <math.h>
     4 
     5 using namespace cv;
     6 using namespace std;
     7 
     8 int main(int argc, char** argv) {
     9     Mat src = imread("test.jpg");
    10     if (src.empty()) {
    11         printf("could not load image...
    ");
    12         return -1;
    13     }
    14     namedWindow("input image", CV_WINDOW_AUTOSIZE);
    15     imshow("input image", src);
    16 
    17     //高斯降噪
    18     Mat blurImage;
    19     GaussianBlur(src, blurImage, Size(15, 15), 0, 0);
    20     imshow("blur", blurImage);
    21 
    22     Mat gray_src, binary;
    23     cvtColor(blurImage, gray_src, COLOR_BGR2GRAY);
    24     threshold(gray_src, binary, 0, 255, THRESH_BINARY | THRESH_TRIANGLE);//颜色单一的图像使用THRESH_TRIANGLE
    25     imshow("binary", binary);
    26 
    27     // 形态学闭操作,去掉空洞
    28     Mat morphImage;
    29     Mat kernel = getStructuringElement(MORPH_RECT, Size(3, 3), Point(-1, -1));
    30     morphologyEx(binary, morphImage, MORPH_CLOSE, kernel, Point(-1, -1), 2);
    31     imshow("morphology", morphImage);
    32 
    33     // 获取最大轮廓
    34     vector<vector<Point>> contours;
    35     vector<Vec4i> hireachy;
    36     findContours(morphImage, contours, hireachy, CV_RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point());
    37     Mat connImage = Mat::zeros(src.size(), CV_8UC3);
    38     for (size_t t = 0; t < contours.size(); t++) {
    39         Rect rect = boundingRect(contours[t]);
    40         if (rect.width < src.cols / 2) continue;//轮廓筛选
    41         if (rect.width > (src.cols - 20)) continue;//轮廓筛选
    42         double area = contourArea(contours[t]);
    43         double len = arcLength(contours[t], true);
    44         drawContours(connImage, contours, static_cast<int>(t), Scalar(0, 0, 255), 1, 8, hireachy);
    45         printf("area  of star could : %f
    ", area);
    46         printf("length  of star could : %f
    ", len);
    47     }
    48     imshow("result", connImage);
    49 
    50     waitKey(0);
    51     return 0;
    52 }
  • 相关阅读:
    《冒号课堂》目录 书名:冒号课堂——编程范式与OOP思想
    很好的WEB打印网页打印功能
    桌面搜索程序 Python
    面向对象保存爬虫数据 Python
    爬取微博热搜榜 李白之死 Python
    雪中悍刀行热播,来做一篇关于python的作业 爬虫与数据分析
    几个简单的例子 巩固Xpath语法 Python
    替换特殊字符 Python
    爬取酷狗榜单并可视化词云 Python
    Selenium尝试更改useragent 基于Python
  • 原文地址:https://www.cnblogs.com/long5683/p/9750416.html
Copyright © 2020-2023  润新知