輪廓發(fā)現(xiàn)
輪廓發(fā)現(xiàn)是基于圖像邊緣提取的基礎尋找對象輪廓的方法垢袱。
所以邊緣提取的閾值選定會影響最終輪廓發(fā)現(xiàn)結果
API介紹
findContours發(fā)現(xiàn)輪廓
drawContours繪制輪廓
在二值圖像上發(fā)現(xiàn)輪廓使用API cv::findContours(
InputOutputArray binImg, // 輸入圖像,非0的像素被看成1,0的像素值保持不變,8-bit
OutputArrayOfArrays contours,// 全部發(fā)現(xiàn)的輪廓對象
OutputArray, hierachy// 圖該的拓撲結構挠进,可選陕贮,該輪廓發(fā)現(xiàn)算法正是基于圖像拓撲結構實現(xiàn)唯笙。
int mode, // 輪廓返回的模式
int method,// 發(fā)現(xiàn)方法
Point offset=Point()// 輪廓像素的位移姜凄,默認(0, 0)沒有位移
)
在二值圖像上發(fā)現(xiàn)輪廓使用API cv::findContours之后對發(fā)現(xiàn)的輪廓數(shù)據(jù)進行繪制顯示
drawContours(
InputOutputArray binImg, // 輸出圖像
OutputArrayOfArrays contours,// 全部發(fā)現(xiàn)的輪廓對象
Int contourIdx// 輪廓索引號
const Scalar & color,// 繪制時候顏色
int thickness,// 繪制線寬
int lineType ,// 線的類型LINE_8
InputArray hierarchy,// 拓撲結構圖
int maxlevel,// 最大層數(shù), 0只繪制當前的坛芽,1表示繪制繪制當前及其內嵌的輪廓
Point offset=Point()// 輪廓位移留储,可選
#include "pch.h"
#include <opencv2/opencv.hpp>
#include <iostream>
#include <math.h>
using namespace std;
using namespace cv;
Mat src, dst;
const char* output_win = "findcontours-demo";
int threshold_value = 100;
int threshold_max = 255;
RNG rng;
void Demo_Contours(int, void*);
int main(int argc, char** argv) {
src = imread("D:/cir.png");
if (src.empty()) {
printf("could not load image...\n");
return -1;
}
namedWindow("input-image", CV_WINDOW_AUTOSIZE);
namedWindow(output_win, CV_WINDOW_AUTOSIZE);
imshow("input-image", src);
cvtColor(src, src, CV_BGR2GRAY);
const char* trackbar_title = "Threshold Value:";
createTrackbar(trackbar_title, output_win, &threshold_value, threshold_max, Demo_Contours);
Demo_Contours(0, 0);
waitKey(0);
return 0;
}
void Demo_Contours(int, void*) {
Mat canny_output;
vector<vector<Point>> contours;
vector<Vec4i> hierachy;
Canny(src, canny_output, threshold_value, threshold_value * 2, 3, false);
findContours(canny_output, contours, hierachy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0));
dst = Mat::zeros(src.size(), CV_8UC3);
RNG rng(12345);
for (size_t i = 0; i < contours.size(); i++) {
Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));
drawContours(dst, contours, i, color, 2, 8, hierachy, 0, Point(0, 0));
}
imshow(output_win, dst);
}
計算輪廓面積:
double contourArea(InputArray contour, bool oriented=false )
InputArray contour:輸入的點,一般是圖像的輪廓點
bool oriented=false:表示某一個方向上輪廓的的面積值咙轩,順時針或者逆時針获讳,一般選擇默認false
計算輪廓邊長:
double arcLength(InputArray curve, bool closed)
InputArray curve:表示圖像的輪廓
bool closed:表示輪廓是否封閉的
2、求面積和重心
利用矩可以求出圖形的面積和重心
opencv提供cv2.moments(輪廓)來求出圖形的矩活喊,這個函數(shù)只要提供Contours參數(shù)就可以丐膝。
例子:
M= cv2.moments(contours[0]) #求矩
cx = int(M[‘m10’]/M[‘m00’]) # 求x坐標
cy = int(M[‘m01’]/M[‘m00’]) # 求y坐標
img=cv2.circle(img ,(cx,cy),2,(0,0,255),4) #畫出重心
對于面積,本來圖形的矩里面M00就是表示面積钾菊,但opencv同時也提供cv2.ContourArea(輪廓)來計算面積帅矗,兩者并沒有什么區(qū)別
例子:
area = cv2.contourArea(contours[0])
print “area = %f”%area
print “M00 = %f”%M[“m00”]
注:cv2.moments這個函數(shù)返回的結果是一個字典類型的數(shù)據(jù),零階矩的鍵值是m00,一階矩的鍵值分別是m10和m01