OpenCV尋找復(fù)雜背景下物體的輪廓
點(diǎn)擊下方“AI算法與圖像處理”,關(guān)注一下
重磅干貨,第一時(shí)間送達(dá)
本文轉(zhuǎn)自:opencv學(xué)堂
這是一個(gè)來自O(shè)PenCV問答社區(qū) - "answerOpenCV"問題,整編如下:
(http://answers.opencv.org/question/200422/opencv-c-filling-holes/)
title:OpenCV / C++ - Filling holes
content:
Hello there,
For a personnel projet, I'm trying to detect object and there shadow. These are the result I have for now: Original:


Object:
Shadow:
The external contours of the object are quite good, but as you can see, my object is not full. Same for the shadow. I would like to get full contours, filled, for the object and its shadow, and I don't know how to get better than this (I juste use "dilate" for the moment). Does someone knows a way to obtain a better result please? Regards.
從原始圖片上來看,這張圖片的拍攝的背景比較復(fù)雜,此外光照也存在偏光現(xiàn)象;而提問者雖然提出的是“將縫隙合并”的要求,實(shí)際上他還是想得到目標(biāo)物體的準(zhǔn)確輪廓。
基于現(xiàn)有經(jīng)驗(yàn),和OpenCV,GOCVhelper等工具,能夠很快得出以下結(jié)果
h通道:

去光差:

閾值:

標(biāo)注:

這套算法首先解決了這個(gè)問題,而且我認(rèn)為也是穩(wěn)健魯棒的。其中,算法中除了經(jīng)典的“hsv分解->ostu閾值->最大輪廓標(biāo)注”外,最為關(guān)鍵的算法為頂帽去光差。這個(gè)算法來自于岡薩雷斯《數(shù)字圖像處理教程》形態(tài)學(xué)篇章,完全按照書本建議實(shí)現(xiàn),體現(xiàn)良好作用。
//answerOpenCV OpenCV / C++ - Filling holes
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace cv;
using namespace std;
//find the biggest contour
vector<Point> 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];
}
//remove Light difference by using top hat
Mat moveLightDiff(Mat src,int radius){
Mat dst;
Mat srcclone = src.clone();
Mat mask = Mat::zeros(radius*2,radius*2,CV_8U);
circle(mask,Point(radius,radius),radius,Scalar(255),-1);
//top hat
erode(srcclone,srcclone,mask);
dilate(srcclone,srcclone,mask);
dst = src - srcclone;
return dst;
}
int main( void )
{
Mat src = imread("e:/sandbox/question.png");
Mat src_hsv;
Mat bin;
Mat src_h;
cvtColor(src,src_hsv,COLOR_BGR2HSV);
vector<Mat> rgb_planes;
split(src_hsv, rgb_planes );
src_h = rgb_planes[0]; // h channel is useful
src_h = moveLightDiff(src_h,40);
threshold(src_h,bin,100,255,THRESH_OTSU);
//find and draw the biggest contour
vector<Point> bigestcontrour = FindBigestContour(bin);
vector<vector<Point> > controus;
controus.push_back(bigestcontrour);
cv::drawContours(src,controus,0,Scalar(0,0,255),3);
waitKey();
return 0;
}努力分享優(yōu)質(zhì)的計(jì)算機(jī)視覺相關(guān)內(nèi)容,歡迎關(guān)注:
個(gè)人微信(如果沒有備注不拉群!) 請(qǐng)注明:地區(qū)+學(xué)校/企業(yè)+研究方向+昵稱
下載1:何愷明頂會(huì)分享
在「AI算法與圖像處理」公眾號(hào)后臺(tái)回復(fù):何愷明,即可下載。總共有6份PDF,涉及 ResNet、Mask RCNN等經(jīng)典工作的總結(jié)分析
下載2:終身受益的編程指南:Google編程風(fēng)格指南
在「AI算法與圖像處理」公眾號(hào)后臺(tái)回復(fù):c++,即可下載。歷經(jīng)十年考驗(yàn),最權(quán)威的編程規(guī)范!
下載3 CVPR2021 在「AI算法與圖像處理」公眾號(hào)后臺(tái)回復(fù):CVPR,即可下載1467篇CVPR 2020論文 和 CVPR 2021 最新論文
點(diǎn)亮
,告訴大家你也在看
