opencv3逼近多邊形曲線-approxPolyDP函式在影象中的應用
阿新 • • 發佈:2019-02-01
#include<opencv2/opencv.hpp> #include<iostream> #include<vector> using namespace cv; using namespace std; int main() { Mat srcImage = imread("1.jpg"); imshow("【原圖】", srcImage); //先對影象進行空間的轉換(為了之後要提取二值影象) Mat grayImage; cvtColor(srcImage, grayImage, CV_BGR2GRAY); //對影象進行濾波,達到較好的效果 GaussianBlur(grayImage, grayImage, Size(3, 3), 0, 0); imshow("【濾波後的影象】", grayImage); //用邊緣檢測的方式獲取二值影象 Mat cannyImage; Canny(grayImage, cannyImage, 128, 255, 3); //在二值影象中提取輪廓 vector<vector<Point>> contours; vector<Vec4i> hierarchy; findContours(cannyImage, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0)); //對每個輪廓的點集 找逼近多邊形 vector<vector<Point>> approxPoint(contours.size()); for (int i = 0; i < (int)contours.size(); i++) { approxPolyDP(contours[i], approxPoint[i], 3, true); } /******************************************繪製曲線的方式********************************************/ //用繪製輪廓的函式 繪製曲線 Mat drawImage = Mat::zeros(srcImage.size(), CV_8UC3); for (int i = 0; i < (int)contours.size(); i++) { drawContours(drawImage, contours, i, Scalar(255, 255, 255), 1); } imshow("【繪製後的影象】", drawImage); waitKey(0); return 0; }