#include "iostream"
#include "opencv2/opencv.hpp"
using namespace std;
using namespace cv;
int main()
{
Mat img, temp, temp2,dst, dstbin, distancetransform,rel, rel2;
img = imread("lunkuo.jpg");
resize(img, dst, Size(0, 0), 0.1, 0.1);
//转为灰度图
cvtColor(dst, temp, COLOR_BGR2GRAY);
//高斯滤波
GaussianBlur(temp, temp2, Size(3, 3), 5, 0);
//二值化,找出目标区域
threshold(temp2, dstbin, 200, 255, THRESH_BINARY);
vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
findContours(dstbin, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE,Point());
drawContours(dst, contours, -1, Scalar(0, 0, 255));
for (int i = 0; i < hierarchy.size(); i++)
{
cout << hierarchy[i] << endl;
}
for (int i = 0; i < contours.size(); i++)
{
double ar = contourArea(contours[i]);
double len = arcLength(contours[i],true);
string text = "序号:" + to_string(i) + " 面积:" + to_string(ar) + " 闭合长度:" + to_string(len);
cout << text << endl;
putText(dst, to_string(i), contours[i][i], FONT_HERSHEY_SIMPLEX, 1.0, Scalar(0, 255, 0));
//drawContours(dst, contours, i, Scalar(0, 0, 255));
imshow("dst", dst);
//waitKey(0);
}
waitKey(0);
return 1;
}
opencv 轮廓检测 findContours drawContours
于 2023-07-22 13:28:14 首次发布