OPENCV color target Tracking

Source: Internet
Author: User
Tags abs arrays integer min ranges scalar vmin

OPENCV color target Tracking

using namespace CV;
using namespace Std;
-----------------------------------"global variable Declaration"-----------------------------------------
Description: Declaring global variables
//-------------------------------------------------------------------------------------------------
Mat image;
BOOL Backprojmode = false;
BOOL SelectObject = false;
int trackobject = 0;
bool Showhist = true;
Point origin;
Rect selection;
int vmin = ten, Vmax = n, smin = 30;
--------------------------------"Onmouse () callback function"------------------------------------
Description: Mouse Action callback
//-------------------------------------------------------------------------------------------------
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)
{
Case Cv_event_lbuttondown:
Origin = point (x, y);
Selection = Rect (x,y,0,0);
SelectObject = true;
Break
Case Cv_event_lbuttonup:
SelectObject = false;
if (selection.width > 0 && selection.height > 0)
Trackobject =-1;
Break
}
}
--------------------------------the Help () function----------------------------------------------
Description: Output Help information
//-------------------------------------------------------------------------------------------------
static void Showhelptext ()
{
cout << "\n\n\t\t\t is very grateful for the purchase of the" OpenCV3 Programming Primer "book. \ n "
<< "\n\n\t\t\t This is the 8th supporting sample program for this book, version OpenCV2 \ n"
<< "\n\n\t\t\t is currently using the OpenCV version:" << cv_version
<< "\ n----------------------------------------------------------------------------";
cout << "\n\n\t This demo shows the tracking (tracking) technology based on mean drift \ n"
"\ t please use the mouse box to select a Color object, the tracking operation \ n";
cout << "\n\n\t operation instructions: \ n"
"\t\t to initialize trace \ n with the mouse box selected"
"\t\tesc-Exit program \ n"
"\T\TC-stop tracking \ n"
"\T\TB-on/off-projected view \ n"
"\t\th-Show/Hide-object histogram \ n"
"\T\TP-Pause video \ n";
}
Const char* keys =
{
"{1| | 0 | Camera Number} "
};
-----------------------------------the main () function--------------------------------------------
Description: The entry function of the console application, our program starts here
//-------------------------------------------------------------------------------------------------
int main (int argc, const char** argv)
{
Showhelptext ();
Videocapture cap;
Rect Trackwindow;
int hsize = 16;
Float hranges[] = {0,180};
Const float* phranges = hranges;
Cap.open (0);
if (!cap.isopened ())
{
cout << "Cannot initialize camera \ n";
}
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 ($, +, 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 (_vmin, _vmax), mask);
int ch[] = {0, 0};
Hue.create (Hsv.size (), hsv.depth ());
Mixchannels (&AMP;HSV, 1, &hue, 1, CH, 1);
if (Trackobject < 0)
{
Mat ROI (hue, selection), Maskroi (mask, selection);
Calchist (&roi, 1, 0, Maskroi, hist, 1, &hsize, &phranges);
Normalize (hist, hist, 0, 255, Cv_minmax);
Trackwindow = Selection;
Trackobject = 1;
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, CV_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);
}
}
Calcbackproject (&hue, 1, 0, Hist, backproj, &phranges);
Backproj &= Mask;
Rotatedrect Trackbox = Camshift (Backproj, Trackwindow,
Termcriteria (Cv_termcrit_eps | Cv_termcrit_iter, 10, 1));
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, CV_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;
}

Let's take a look at the mouse callback function

(1) Onmouse

Function prototypes: void Onmouse (int event, int x, int y, int, void*).

Within this function, you must set up some basic information. For example, the initial position of the mouse, the end position, determine the size and location of the rect rectangle information. Finally wait for the mouse button to trigger, passing parameters x and Y are the position coordinates of the mouse click.

Use switch to determine how the event has several mouse triggers. Also set the key switch. Here is the SelectObject, which is usually pressed to true, when released to false. It is a good idea to add the IF condition each time the key is triggered, to determine if the rect is really triggered or if the location of the trigger matches the requirement.



(2) Createtrackbar Slide bar

cv_exports int Createtrackbar (const string& trackbarname, const string& Winname,
int* value, int count,
Trackbarcallback onchange=0,
void* userdata=0);

The first two parameters specify the name of the slider and the name of the sliding bar's secondary window, respectively. When the slider bar is created, the slider is created at the top or bottom of the window. Additionally, the slider does not obscure the image in the window.


The subsequent two is value, which is an integer pointer, and when the slider is dragged, OpenCV automatically creates the value represented by the current position to the integer pointed to by the pointer, and the other parameter count is an integer value, which is the maximum value that the slider can represent.


The last parameter is a pointer to a callback function that is automatically called when the slider is dragged. This is similar to the callback function implementation for mouse events. The callback function must be in the Cvtrackbarcallback format, defined as follows:

void (*callback) (int position)

This callback function is not necessary, so if you do not need a callback function, you can set the parameter to NULL, there is no callback function, when the slider is dragged, the only effect is to change the pointer value of the integer value pointed to.


Highgui also provides two functions to read and set the value of the slider bar, but only if you have to know the name of the slider bar.

int Cvgettrackbarpos (const char* trackbar_name,const char * window_name);

void Cvsettrackbarpos (const char* trackbar_name, const char * window_name,int POS);


(3) InRange

Checks whether the array element is between two arrays
void Cvinrange (const cvarr* SRC, const cvarr* lower, const cvarr* Upper, cvarr* DST);
Src
First array of original
Lower
An array of bottom bounds including the input
Upper
Not included in the upper boundary line array
Dst
The output array must be of type 8u or 8s.
The Cvinrange function checks the input array for a range, for a single-channel array:
DST (i) =lower (i) 0 <= src (i) 0 < Upper (i) 0
For a two-channel array:
DST (i) =lower (i) 0 <= src (i) 0 < Upper (i) 0 &&
Lower (i) 1 <= src (i) 1 < Upper (i) 1
And so on
If SRC (i) within the range of DST (i) is set to 0xFF (each bit is ' 1 ') otherwise 0. All arrays except the output array must be the same size (or ROI size) of the same type.


(4) Copies specified channels from input arrays to the specified channels of output arrays.
C + +: void mixchannels (const mat* src, int nsrc, mat* dst, int ndst, const int* fromTo, size_t npairs)
Parameters:
Src–input array or vector of matrices. All the matrices must has the same size and the same depth.
Nsrc–number of matrices in Src.
Dst–output array or vector of matrices. All the matrices must is allocated. Their size and depth must be the same as in src[0].
Ndst–number of matrices in DST.
Fromto–array of index pairs specifying which channels is copied and where. FROMTO[K*2] is a 0-based index of the input channel in SRC. FROMTO[K*2+1] is a index of the output channel in DST. The continuous channel numbering is used:the first input image channels be indexed from 0 tosrc[0].channels ()-1, the SE Cond input image channels is indexed from Src[0].channels () tosrc[0].channels () + src[1].channels ()-1, and so on. The same scheme is used for the output image channels. As a special case, when fromto[k*2] was negative, the corresponding output channel is filled with zero.
Npairs–number of index pairs in fromTo.


(5) Calchist function to calculate the histogram of the image.
The function prototypes of C + + are as follows:

void Calchist (const mat* arrays, int narrays, const int* channels, Inputarray mask,

Outputarray hist, int dims, const int* histsize, const float** ranges,

BOOL Uniform=true, bool accumulate=false);

Parameter explanation:
Arrays The input image can be a pointer to multiple images, and all images must have the same depth (cv_8u or cv_32f). At the same time, a picture can have multiple channes.
Narrays. The number of images entered.
Channels An array of channes used to calculate the histogram. For example, the input is 2 pairs of images, the first image has 0,1,2 a total of three channel, the second image has only 1 channel, then the input is a total of 4 channes, if int channels[3] = {3, 2, 0}, Then the histogram is calculated using the first channel of the second pair of images and the 2nd and No. 0 channels of the first pair of images.
Mask Mask. If mask is not empty, then it must be a 8-bit (cv_8u) array, and its size is the same size as arrays[i], and a point with a value of 1 will be used to calculate the histogram.
hist The computed histogram
dims The dimension of the computed histogram.
Histsize. The number of histograms on each dimension. Simply think of the histogram as a vertical bar, that is, the number of vertical bars on each dimension.
Ranges The range used for the statistics. Like what
Float rang1[] = {0, 20};
Float rang2[] = {30, 40};
const FLOAT *rangs[] = {rang1, rang2}; Then the values for the 0,20 and 30,40 ranges are counted.
Uniform Whether the width of each vertical bar is equal.
Accumulate. Accumulation flag. If It is set, the histogram are not cleared in the beginning
When it was allocated. This feature enables-compute a single histogram from several
Sets of arrays, or to update the histogram in time. is cumulative. If true, Hist will not be emptied first at the next calculation. This place I understand, do not know whether there is a mistake.





Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.