在有背景的圖像進行中,往往你關注的區域并不是最大的輪廓(那是背景),而是第二大輪廓
之前我們有這樣的函數:
//尋找最大的輪廓
VP FindBigestContour(Mat src){
int
imax = 0; //代表最大輪廓的序号
int
imaxcontour = -1; //代表最大輪廓的大小
std::vector<std::vector<Point>>contours;
findContours(src,contours,CV_RETR_LIST,CV_CHAIN_APPROX_SIMPLE);
for
(
int
i=0;i<contours.size();i++){
int
itmp = contourArea(contours[i]);//這裡采用的是輪廓大小
if
(imaxcontour < itmp ){
imax = i;
imaxcontour = itmp;
}
}
return
contours[imax];
}
使用的是冒泡方法。實際上vector肯定是可以有排序算法的,能否将其融入進去?
肯定是可以的,我采用了這樣的方法,效果很好。
//尋找第nth的輪廓
//ith = 0代表最大,ith=1 代表第2個,以此類推
bool sortfunction (std::vector<Point> c1,std::vector<Point> c2) {
return
(contourArea(c1)>contourArea(c2)); }
VP FindnthContour(Mat src,
int
ith ){
std::vector<std::vector<Point>>contours;
findContours(src,contours,CV_RETR_LIST,CV_CHAIN_APPROX_SIMPLE);
std::sort(contours.begin(),contours.end(),sortfunction);
return
contours[ith];
}
來自為知筆記(Wiz) 目前方向:圖像拼接融合、圖像識别
聯系方式:[email protected]