OpenCV實現(xiàn)圖像輪廓檢測以及外接矩形
更新時間:2020年07月21日 11:38:32 作者:lindamtd
這篇文章主要為大家詳細(xì)介紹了OpenCV實現(xiàn)圖像輪廓檢測以及外接矩形,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
前兩篇博文分別介紹了圖像的邊緣檢測和輪廓檢測,本文接著介紹圖像的輪廓檢測和輪廓外接矩形:
一、代碼部分:
// extract_contours.cpp : 定義控制臺應(yīng)用程序的入口點。 // #include "stdafx.h" #include<cv.h> #include<highgui.h> using namespace cv; using namespace std; int _tmain(int argc, _TCHAR* argv[]) { //load src image string img_name="..\\image_norm\\71253.jpg"; Mat image=imread(img_name); imshow("src_image",image); cvWaitKey(0); //convert into gray image Mat gray(image.size(),CV_8U); cvtColor(image,gray,CV_BGR2GRAY); imshow("gray",gray); cvWaitKey(0); //convert into bin image threshold(gray,gray,128,255,THRESH_BINARY);//轉(zhuǎn)換成2值圖像 imshow("binary",gray); cvWaitKey(0); // Detecting contours vector<vector<Point>> contours; //定義輪廓集合 vector<Vec4i> hierarchy; findContours(gray, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);//CV_RETR_EXTERNAL只檢測外部輪廓 // draw black contours on white image Mat result(gray.size(),CV_8U,Scalar(255)); int index = 0; for (; index >= 0; index = hierarchy[index][0]) //hierarchy[index][0]表示后一個輪廓 { Scalar color(rand() & 255, rand() & 255, rand() & 255); drawContours(result, contours, index, Scalar(0), 1, 8, hierarchy);//描繪字符的外輪廓 Rect rect = boundingRect(contours[index]);//檢測外輪廓 rectangle(result, rect, Scalar(0,0,255), 3);//對外輪廓加矩形框 } imshow("Contours on white image",result); cvWaitKey(0); //draw contours on the original image Mat original=imread(img_name); int index_ori = 0; for (; index_ori >= 0; index_ori = hierarchy[index_ori][0]) { Scalar color(rand() & 255, rand() & 255, rand() & 255); //描繪字符的外輪廓 drawContours(original,contours,index_ori,Scalar(255),1,8, hierarchy); Rect rect = boundingRect(contours[index_ori]);//檢測外輪廓 //對外輪廓加加矩形框 rectangle(original, rect, Scalar(0,0,255), 3); } //print contours info cout<<"The number of external contours:"<<contours.size()<<endl; imshow("Contours on original image",original); waitKey(0); return 0; }
二、程序運行效果圖:
(1)源圖像:
(2)灰度圖像:
(3)二進(jìn)制圖像:
(4)輪廓在空白圖像上顯示:
(5)在原圖像上畫出圖像的輪廓以及外接矩形:
至此,圖像的輪廓檢測以及外接矩形已經(jīng)實現(xiàn),歡迎高人指正。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
c++調(diào)用實現(xiàn)yolov5轉(zhuǎn)onnx介紹
大家好,本篇文章主要講的是c++調(diào)用實現(xiàn)yolov5轉(zhuǎn)onnx介紹,感興趣的同學(xué)趕快來看一看吧,對你有幫助的話記得收藏一下,方便下次瀏覽2021-12-12Qt實現(xiàn)進(jìn)程界面之間的鼠標(biāo)焦點切換
這篇文章主要為大家詳細(xì)介紹了Qt實現(xiàn)進(jìn)程界面之間的鼠標(biāo)焦點切換,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-09-09C++ string與int的相互轉(zhuǎn)換(使用C++11)
本文主要介紹了C++ string與int的相互轉(zhuǎn)換(使用C++11),文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-01-01