1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
| #include <opencv2/imgcodecs.hpp> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> #include <iostream>
using namespace cv; using namespace std;
void getContours(Mat imgDil, Mat img) {
vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
findContours(imgDil, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
for (int i = 0; i < contours.size(); i++) { double area = contourArea(contours[i]); cout << area << endl;
vector<vector<Point>> conPoly(contours.size()); vector<Rect> boundRect(contours.size()); string objectType;
if (area > 1000) { double peri = arcLength(contours[i], true); approxPolyDP(contours[i], conPoly[i], 0.02 * peri, true); cout << conPoly[i].size() << endl; boundRect[i] = boundingRect(conPoly[i]); int objCor = (int)conPoly[i].size();
if (objCor == 3) { objectType = "Tri"; } if (objCor == 4) { float aspRatio = (float)boundRect[i].width / boundRect[i].height; cout << aspRatio << endl; if (aspRatio > 0.95 && aspRatio < 1.05) { objectType = "Square"; } else { objectType = "Rect"; } } if (objCor > 4) { objectType = "CirCle"; }
drawContours(img, conPoly, i, Scalar(255, 0, 255), 2); rectangle(img, boundRect[i].tl(), boundRect[i].br(), Scalar(0, 255, 0), 5); putText(img, objectType, { boundRect[i].x, boundRect[i].y - 5 }, FONT_HERSHEY_PLAIN, 1, Scalar(0, 69, 255), 1); } } }
int main() { string path = "../lesson1_pictureRead/img1.jpg"; Mat img = imread(path); Mat imgGray, imgBlur, imgCanny, imgDil;
cvtColor(img, imgGray, COLOR_BGR2GRAY); GaussianBlur(imgGray, imgBlur, Size(3, 3), 3, 0); Canny(imgBlur, imgCanny, 75, 125); Mat kernel = getStructuringElement(MORPH_RECT, Size(3, 3)); dilate(imgCanny, imgDil, kernel);
getContours(imgDil, img);
namedWindow("Image",WINDOW_NORMAL); imshow("Image", img);
imshow("Image Dil", imgDil);
waitKey(0);
return 0; }
|