OpenCV  4.5.1
Open Source Computer Vision
samples/cpp/segment_objects.cpp

An example using drawContours to clean up a background segmentation result

#include <stdio.h>
#include <string>
using namespace std;
using namespace cv;
static void help(char** argv)
{
printf("\n"
"This program demonstrated a simple method of connected components clean up of background subtraction\n"
"When the program starts, it begins learning the background.\n"
"You can toggle background learning on and off by hitting the space bar.\n"
"Call\n"
"%s [video file, else it reads camera 0]\n\n", argv[0]);
}
static void refineSegments(const Mat& img, Mat& mask, Mat& dst)
{
int niters = 3;
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
Mat temp;
dilate(mask, temp, Mat(), Point(-1,-1), niters);
erode(temp, temp, Mat(), Point(-1,-1), niters*2);
dilate(temp, temp, Mat(), Point(-1,-1), niters);
findContours( temp, contours, hierarchy, RETR_CCOMP, CHAIN_APPROX_SIMPLE );
dst = Mat::zeros(img.size(), CV_8UC3);
if( contours.size() == 0 )
return;
// iterate through all the top-level contours,
// draw each connected component with its own random color
int idx = 0, largestComp = 0;
double maxArea = 0;
for( ; idx >= 0; idx = hierarchy[idx][0] )
{
const vector<Point>& c = contours[idx];
double area = fabs(contourArea(Mat(c)));
if( area > maxArea )
{
maxArea = area;
largestComp = idx;
}
}
Scalar color( 0, 0, 255 );
drawContours( dst, contours, largestComp, color, FILLED, LINE_8, hierarchy );
}
int main(int argc, char** argv)
{
bool update_bg_model = true;
CommandLineParser parser(argc, argv, "{help h||}{@input||}");
if (parser.has("help"))
{
help(argv);
return 0;
}
string input = parser.get<std::string>("@input");
if (input.empty())
cap.open(0);
else
if( !cap.isOpened() )
{
printf("\nCan not open camera or video file\n");
return -1;
}
Mat tmp_frame, bgmask, out_frame;
cap >> tmp_frame;
if(tmp_frame.empty())
{
printf("can not read data from the video source\n");
return -1;
}
namedWindow("video", 1);
namedWindow("segmented", 1);
bgsubtractor->setVarThreshold(10);
for(;;)
{
cap >> tmp_frame;
if( tmp_frame.empty() )
break;
bgsubtractor->apply(tmp_frame, bgmask, update_bg_model ? -1 : 0);
refineSegments(tmp_frame, bgmask, out_frame);
imshow("video", tmp_frame);
imshow("segmented", out_frame);
char keycode = (char)waitKey(30);
if( keycode == 27 )
break;
if( keycode == ' ' )
{
update_bg_model = !update_bg_model;
printf("Learn background is in state = %d\n",update_bg_model);
}
}
return 0;
}
cv::RETR_CCOMP
@ RETR_CCOMP
Definition: imgproc.hpp:423
cv::erode
void erode(InputArray src, OutputArray dst, InputArray kernel, Point anchor=Point(-1,-1), int iterations=1, int borderType=BORDER_CONSTANT, const Scalar &borderValue=morphologyDefaultBorderValue())
Erodes an image by using a specific structuring element.
cv::BackgroundSubtractorMOG2::apply
virtual void apply(InputArray image, OutputArray fgmask, double learningRate=-1) CV_OVERRIDE=0
Computes a foreground mask.
cv::VideoCapture
Class for video capturing from video files, image sequences or cameras.
Definition: videoio.hpp:628
cv::waitKey
int waitKey(int delay=0)
Waits for a pressed key.
highgui.hpp
cv::namedWindow
void namedWindow(const String &winname, int flags=WINDOW_AUTOSIZE)
Creates a window.
cv::Scalar_< double >
cv::findContours
void findContours(InputArray image, OutputArrayOfArrays contours, OutputArray hierarchy, int mode, int method, Point offset=Point())
Finds contours in a binary image.
background_segm.hpp
cv::dilate
void dilate(InputArray src, OutputArray dst, InputArray kernel, Point anchor=Point(-1,-1), int iterations=1, int borderType=BORDER_CONSTANT, const Scalar &borderValue=morphologyDefaultBorderValue())
Dilates an image by using a specific structuring element.
CV_8UC3
#define CV_8UC3
Definition: interface.h:90
cv::contourArea
double contourArea(InputArray contour, bool oriented=false)
Calculates a contour area.
cv::FILLED
@ FILLED
Definition: imgproc.hpp:808
cv::Mat::size
MatSize size
Definition: mat.hpp:2114
cv::createBackgroundSubtractorMOG2
Ptr< BackgroundSubtractorMOG2 > createBackgroundSubtractorMOG2(int history=500, double varThreshold=16, bool detectShadows=true)
Creates MOG2 Background Subtractor.
cv::VideoCapture::isOpened
virtual bool isOpened() const
Returns true if video capturing has been initialized already.
cv::Ptr
std::shared_ptr< _Tp > Ptr
Definition: cvstd_wrapper.hpp:23
cv::imshow
void imshow(const String &winname, InputArray mat)
Displays an image in the specified window.
cv::drawContours
void drawContours(InputOutputArray image, InputArrayOfArrays contours, int contourIdx, const Scalar &color, int thickness=1, int lineType=LINE_8, InputArray hierarchy=noArray(), int maxLevel=INT_MAX, Point offset=Point())
Draws contours outlines or filled contours.
cv::Point
Point2i Point
Definition: types.hpp:194
cv::BackgroundSubtractorMOG2::setVarThreshold
virtual void setVarThreshold(double varThreshold)=0
Sets the variance threshold for the pixel-model match.
cv::Mat
n-dimensional dense array class
Definition: mat.hpp:798
cv::samples::findFileOrKeep
cv::String findFileOrKeep(const cv::String &relative_path, bool silentMode=false)
Definition: utility.hpp:1156
cv::CommandLineParser
Designed for command line parsing.
Definition: utility.hpp:789
cv
"black box" representation of the file storage associated with a file on disk.
Definition: affine.hpp:52
imgproc.hpp
cv::LINE_8
@ LINE_8
8-connected line
Definition: imgproc.hpp:810
cv::CHAIN_APPROX_SIMPLE
@ CHAIN_APPROX_SIMPLE
Definition: imgproc.hpp:437
cv::gapi::mask
GMat mask(const GMat &src, const GMat &mask)
Applies a mask to a matrix.
videoio.hpp
cv::VideoCapture::open
virtual bool open(const String &filename, int apiPreference=CAP_ANY)
Opens a video file or a capturing device or an IP video stream for video capturing.