OpenCV  4.2.0
Open Source Computer Vision
samples/cpp/camshiftdemo.cpp

An example using the mean-shift tracking algorithm

#include <iostream>
#include <ctype.h>
using namespace cv;
using namespace std;
Mat image;
bool backprojMode = false;
bool selectObject = false;
int trackObject = 0;
bool showHist = true;
Point origin;
Rect selection;
int vmin = 10, vmax = 256, smin = 30;
// User draws box around object to track. This triggers CAMShift to start tracking
static void onMouse( int event, int x, int y, int, void* )
{
if( selectObject )
{
selection.x = MIN(x, origin.x);
selection.y = MIN(y, origin.y);
selection.width = std::abs(x - origin.x);
selection.height = std::abs(y - origin.y);
selection &= Rect(0, 0, image.cols, image.rows);
}
switch( event )
{
origin = Point(x,y);
selection = Rect(x,y,0,0);
selectObject = true;
break;
selectObject = false;
if( selection.width > 0 && selection.height > 0 )
trackObject = -1; // Set up CAMShift properties in main() loop
break;
}
}
string hot_keys =
"\n\nHot keys: \n"
"\tESC - quit the program\n"
"\tc - stop the tracking\n"
"\tb - switch to/from backprojection view\n"
"\th - show/hide object histogram\n"
"\tp - pause video\n"
"To initialize tracking, select the object with mouse\n";
static void help()
{
cout << "\nThis is a demo that shows mean-shift based tracking\n"
"You select a color objects such as your face and it tracks it.\n"
"This reads from video camera (0 by default, or the camera number the user enters\n"
"Usage: \n"
" ./camshiftdemo [camera number]\n";
cout << hot_keys;
}
const char* keys =
{
"{help h | | show help message}{@camera_number| 0 | camera number}"
};
int main( int argc, const char** argv )
{
Rect trackWindow;
int hsize = 16;
float hranges[] = {0,180};
const float* phranges = hranges;
CommandLineParser parser(argc, argv, keys);
if (parser.has("help"))
{
help();
return 0;
}
int camNum = parser.get<int>(0);
cap.open(camNum);
if( !cap.isOpened() )
{
help();
cout << "***Could not initialize capturing...***\n";
cout << "Current parameter's value: \n";
parser.printMessage();
return -1;
}
cout << hot_keys;
namedWindow( "Histogram", 0 );
namedWindow( "CamShift Demo", 0 );
setMouseCallback( "CamShift Demo", onMouse, 0 );
createTrackbar( "Vmin", "CamShift Demo", &vmin, 256, 0 );
createTrackbar( "Vmax", "CamShift Demo", &vmax, 256, 0 );
createTrackbar( "Smin", "CamShift Demo", &smin, 256, 0 );
Mat frame, hsv, hue, mask, hist, histimg = Mat::zeros(200, 320, CV_8UC3), backproj;
bool paused = false;
for(;;)
{
if( !paused )
{
cap >> frame;
if( frame.empty() )
break;
}
frame.copyTo(image);
if( !paused )
{
cvtColor(image, hsv, COLOR_BGR2HSV);
if( trackObject )
{
int _vmin = vmin, _vmax = vmax;
inRange(hsv, Scalar(0, smin, MIN(_vmin,_vmax)),
Scalar(180, 256, MAX(_vmin, _vmax)), mask);
int ch[] = {0, 0};
hue.create(hsv.size(), hsv.depth());
mixChannels(&hsv, 1, &hue, 1, ch, 1);
if( trackObject < 0 )
{
// Object has been selected by user, set up CAMShift search properties once
Mat roi(hue, selection), maskroi(mask, selection);
calcHist(&roi, 1, 0, maskroi, hist, 1, &hsize, &phranges);
normalize(hist, hist, 0, 255, NORM_MINMAX);
trackWindow = selection;
trackObject = 1; // Don't set up again, unless user selects new ROI
histimg = Scalar::all(0);
int binW = histimg.cols / hsize;
Mat buf(1, hsize, CV_8UC3);
for( int i = 0; i < hsize; i++ )
buf.at<Vec3b>(i) = Vec3b(saturate_cast<uchar>(i*180./hsize), 255, 255);
cvtColor(buf, buf, COLOR_HSV2BGR);
for( int i = 0; i < hsize; i++ )
{
int val = saturate_cast<int>(hist.at<float>(i)*histimg.rows/255);
rectangle( histimg, Point(i*binW,histimg.rows),
Point((i+1)*binW,histimg.rows - val),
Scalar(buf.at<Vec3b>(i)), -1, 8 );
}
}
// Perform CAMShift
calcBackProject(&hue, 1, 0, hist, backproj, &phranges);
backproj &= mask;
RotatedRect trackBox = CamShift(backproj, trackWindow,
if( trackWindow.area() <= 1 )
{
int cols = backproj.cols, rows = backproj.rows, r = (MIN(cols, rows) + 5)/6;
trackWindow = Rect(trackWindow.x - r, trackWindow.y - r,
trackWindow.x + r, trackWindow.y + r) &
Rect(0, 0, cols, rows);
}
if( backprojMode )
cvtColor( backproj, image, COLOR_GRAY2BGR );
ellipse( image, trackBox, Scalar(0,0,255), 3, LINE_AA );
}
}
else if( trackObject < 0 )
paused = false;
if( selectObject && selection.width > 0 && selection.height > 0 )
{
Mat roi(image, selection);
bitwise_not(roi, roi);
}
imshow( "CamShift Demo", image );
imshow( "Histogram", histimg );
char c = (char)waitKey(10);
if( c == 27 )
break;
switch(c)
{
case 'b':
backprojMode = !backprojMode;
break;
case 'c':
trackObject = 0;
histimg = Scalar::all(0);
break;
case 'h':
showHist = !showHist;
if( !showHist )
destroyWindow( "Histogram" );
else
namedWindow( "Histogram", 1 );
break;
case 'p':
paused = !paused;
break;
default:
;
}
}
return 0;
}
cv::Vec3b
Vec< uchar, 3 > Vec3b
Definition: matx.hpp:401
cv::Mat::rows
int rows
the number of rows and columns or (-1, -1) when the matrix has more than 2 dimensions
Definition: mat.hpp:2086
cv::Point_< int >
cv::Scalar_< double >::all
static Scalar_< double > all(double v0)
returns a scalar with all elements set to v0
cv::TermCriteria
The class defining termination criteria for iterative algorithms.
Definition: types.hpp:852
cv::Rect
Rect2i Rect
Definition: types.hpp:462
cv::NORM_MINMAX
@ NORM_MINMAX
flag
Definition: base.hpp:207
cv::calcBackProject
void calcBackProject(const Mat *images, int nimages, const int *channels, InputArray hist, OutputArray backProject, const float **ranges, double scale=1, bool uniform=true)
Calculates the back projection of a histogram.
cv::cvtColor
void cvtColor(InputArray src, OutputArray dst, int code, int dstCn=0)
Converts an image from one color space to another.
cv::COLOR_BGR2HSV
@ COLOR_BGR2HSV
convert RGB/BGR to HSV (hue saturation value), color conversions
Definition: imgproc.hpp:585
cv::Mat::zeros
static MatExpr zeros(int rows, int cols, int type)
Returns a zero array of the specified size and type.
cv::inRange
void inRange(InputArray src, InputArray lowerb, InputArray upperb, OutputArray dst)
Checks if array elements lie between the elements of two other arrays.
cv::saturate_cast< uchar >
uchar saturate_cast< uchar >(schar v)
Definition: saturate.hpp:100
cv::Mat::at
_Tp & at(int i0=0)
Returns a reference to the specified array element.
cv::mixChannels
void mixChannels(const Mat *src, size_t nsrcs, Mat *dst, size_t ndsts, const int *fromTo, size_t npairs)
Copies specified channels from input arrays to the specified channels of output arrays.
cv::VideoCapture
Class for video capturing from video files, image sequences or cameras.
Definition: videoio.hpp:608
cv::waitKey
int waitKey(int delay=0)
Waits for a pressed key.
cv::TermCriteria::COUNT
@ COUNT
the maximum number of iterations or elements to compute
Definition: types.hpp:860
cv::TermCriteria::EPS
@ EPS
the desired accuracy or change in parameters at which the iterative algorithm stops
Definition: types.hpp:862
cv::Point_::y
_Tp y
y coordinate of the point
Definition: types.hpp:187
cv::Point_::x
_Tp x
x coordinate of the point
Definition: types.hpp:186
highgui.hpp
cv::namedWindow
void namedWindow(const String &winname, int flags=WINDOW_AUTOSIZE)
Creates a window.
cv::Scalar_< double >
cv::EVENT_LBUTTONDOWN
@ EVENT_LBUTTONDOWN
indicates that the left mouse button is pressed.
Definition: highgui.hpp:207
cv::destroyWindow
void destroyWindow(const String &winname)
Destroys the specified window.
cv::rectangle
void rectangle(InputOutputArray img, Point pt1, Point pt2, const Scalar &color, int thickness=1, int lineType=LINE_8, int shift=0)
Draws a simple, thick, or filled up-right rectangle.
cv::COLOR_HSV2BGR
@ COLOR_HSV2BGR
backward conversions to RGB/BGR
Definition: imgproc.hpp:596
cv::Vec
Template class for short numerical vectors, a partial case of Matx.
Definition: matx.hpp:332
cv::Mat::cols
int cols
Definition: mat.hpp:2086
CV_8UC3
#define CV_8UC3
Definition: interface.h:90
cv::Mat::size
MatSize size
Definition: mat.hpp:2108
MIN
#define MIN(a, b)
Definition: cvdef.h:453
cv::Rect_::y
_Tp y
y coordinate of the top-left corner
Definition: types.hpp:454
cv::abs
static uchar abs(uchar a)
Definition: cvstd.hpp:66
cv::VideoCapture::isOpened
virtual bool isOpened() const
Returns true if video capturing has been initialized already.
cv::RotatedRect
The class represents rotated (i.e. not up-right) rectangles on a plane.
Definition: types.hpp:503
tracking.hpp
cv::Rect_
Template class for 2D rectangles.
Definition: types.hpp:420
cv::imshow
void imshow(const String &winname, InputArray mat)
Displays an image in the specified window.
cv::Rect_::width
_Tp width
width of the rectangle
Definition: types.hpp:455
cv::Rect_::area
_Tp area() const
area (width*height) of the rectangle
cv::CamShift
RotatedRect CamShift(InputArray probImage, Rect &window, TermCriteria criteria)
Finds an object center, size, and orientation.
cv::Scalar
Scalar_< double > Scalar
Definition: types.hpp:669
cv::Rect_::height
_Tp height
height of the rectangle
Definition: types.hpp:456
cv::setMouseCallback
void setMouseCallback(const String &winname, MouseCallback onMouse, void *userdata=0)
Sets mouse handler for the specified window.
cv::Point
Point2i Point
Definition: types.hpp:194
cv::calcHist
void calcHist(const Mat *images, int nimages, const int *channels, InputArray mask, OutputArray hist, int dims, const int *histSize, const float **ranges, bool uniform=true, bool accumulate=false)
Calculates a histogram of a set of arrays.
cv::Mat
n-dimensional dense array class
Definition: mat.hpp:791
cv::Mat::copyTo
void copyTo(OutputArray m) const
Copies the matrix to another one.
cv::CommandLineParser
Designed for command line parsing.
Definition: utility.hpp:796
cv::createTrackbar
int createTrackbar(const String &trackbarname, const String &winname, int *value, int count, TrackbarCallback onChange=0, void *userdata=0)
Creates a trackbar and attaches it to the specified window.
cv
"black box" representation of the file storage associated with a file on disk.
Definition: affine.hpp:51
imgproc.hpp
MAX
#define MAX(a, b)
Definition: cvdef.h:457
cv::Mat::create
void create(int rows, int cols, int type)
Allocates new array data if needed.
cv::EVENT_LBUTTONUP
@ EVENT_LBUTTONUP
indicates that left mouse button is released.
Definition: highgui.hpp:210
cv::bitwise_not
void bitwise_not(InputArray src, OutputArray dst, InputArray mask=noArray())
Inverts every bit of an array.
cv::gapi::mask
GMat mask(const GMat &src, const GMat &mask)
Applies a mask to a matrix.
cv::normalize
static Vec< _Tp, cn > normalize(const Vec< _Tp, cn > &v)
cv::Mat::depth
int depth() const
Returns the depth of a matrix element.
utility.hpp
cv::ellipse
void ellipse(InputOutputArray img, Point center, Size axes, double angle, double startAngle, double endAngle, const Scalar &color, int thickness=1, int lineType=LINE_8, int shift=0)
Draws a simple or thick elliptic arc or fills an ellipse sector.
cv::COLOR_GRAY2BGR
@ COLOR_GRAY2BGR
Definition: imgproc.hpp:544
videoio.hpp
cv::Rect_::x
_Tp x
x coordinate of the top-left corner
Definition: types.hpp:453
cv::LINE_AA
@ LINE_AA
antialiased line
Definition: imgproc.hpp:807
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.