OpenCV: Using the Camshift algorithm to track color targets

Source: Internet
Author: User
Tags vmin

<span style= "FONT-SIZE:14PX;" > #include <opencv\cv.h> #include <opencv\highgui.h> #include <stdio.h> #include <ctype.h> Iplimage *image = 0, *HSV = 0, *hue = 0, *mask = 0, *backproject = 0, *histimg = 0; Cvhistogram *hist = 0;int Backproject_mode = 0;int Select_object = 0;int Track_object = 0;int show_hist = 1; Cvpoint origin; Cvrect selection; Cvrect Track_window;  Cvbox2d Track_box;     Tracking return area box, with angle cvconnectedcomp track_comp;int hdims = 48; Divide the number of hist, the higher the more accurate float hranges_arr[] = {0,180};float* Hranges = hranges_arr;int Vmin = ten, Vmax = max, smin = 30;void on_    Mouse (int event, int x, int y, int flags) {if (!image) return;    if (image->origin) y = image->height-y;        if (select_object) {selection.x = MIN (x,origin.x);        SELECTION.Y = MIN (Y,ORIGIN.Y);        Selection.width = selection.x + cv_iabs (x-origin.x);        Selection.height = selection.y + cv_iabs (Y-ORIGIN.Y); selection.x = MAX (selection.x, 0);        SELECTION.Y = MAX (selection.y, 0);        Selection.width = MIN (Selection.width, image->width);        Selection.height = MIN (Selection.height, image->height);        Selection.width-= selection.x;    Selection.height-= SELECTION.Y;        } switch (event) {Case cv_event_lbuttondown:origin = cvpoint (x, y);        Selection = Cvrect (x,y,0,0);        Select_object = 1;    Break        Case cv_event_lbuttonup:select_object = 0; if (selection.width > 0 && selection.height > 0) track_object =-1; #ifdef _DEBUG printf ("        \ n # Mouse selection area "); printf ("\ n X =%d, Y =%d, Width =%d, Height =%d", selection.x, SELECTION.Y, Selection.width, selection.    height); #endif break;    }}cvscalar Hsv2rgb (float hue) {int rgb[3], p, sector;    static const int sector_data[][3]= {{0,2,1}, {1,2,0}, {1,0,2}, {2,0,1}, {2,1,0}, {0,1,2}};    Hue *= 0.033333333333333333333333333333333f; Sector = Cvfloor (hue);    p = Cvround (255* (hue-sector)); P ^= Sector & 1?    255:0;    Rgb[sector_data[sector][0]] = 255;    RGB[SECTOR_DATA[SECTOR][1]] = 0;    RGB[SECTOR_DATA[SECTOR][2]] = p; #ifdef _DEBUG printf ("\ n # Convert HSV to RGB");    printf ("\ hue =%f", hue); printf ("\ R =%d, G =%d, B =%d", rgb[0],rgb[1],rgb[2]), #endif return Cvscalar (rgb[2], rgb[1], rgb[0],0);}    int main (int argc, char** argv) {cvcapture* capture = 0;    iplimage* frame = 0; if (argc = = 1 | |        (argc = = 2 && strlen (argv[1]) = = 1 && isdigit (argv[1][0])))    Capture = Cvcapturefromcam (argc = = 2? Argv[1][0]-' 0 ': 0);    else if (argc = = 2) capture = Cvcapturefromavi (argv[1]);        if (!capture) {fprintf (stderr, "Could not initialize capturing...\n");    return-1;  } printf ("Hot 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 "" to initialize tracking, select the object with mouse\n ");    Cvnamedwindow ("Histogram", 1);    Cvnamedwindow ("Camshiftdemo", 1); Cvsetmousecallback ("Camshiftdemo", (cvmousecallback) on_mouse, NULL);    On_mouse Custom Event Cvcreatetrackbar ("Vmin", "Camshiftdemo", &vmin, 256, 0);    Cvcreatetrackbar ("Vmax", "Camshiftdemo", &vmax, 256, 0);    Cvcreatetrackbar ("Smin", "Camshiftdemo", &smin, 256, 0); for (;;)        {int I, bin_w, C;        frame = Cvqueryframe (capture);        if (!frame) break;            if (!image) {//allocates all buffers image = Cvcreateimage (Cvgetsize (frame), 8, 3);            Image->origin = frame->origin;            HSV = Cvcreateimage (Cvgetsize (frame), 8, 3);            Hue = Cvcreateimage (Cvgetsize (frame), 8, 1);            Mask = Cvcreateimage (Cvgetsize (frame), 8, 1);            Backproject = Cvcreateimage (Cvgetsize (frame), 8, 1); hist = CvcreaTehist (1, &hdims, Cv_hist_array, &hranges, 1);            Calculate Histogram histimg = Cvcreateimage (Cvsize (320,200), 8, 3);        Cvzero (HISTIMG);        } cvcopy (frame, image, 0);  Cvcvtcolor (image, HSV, CV_BGR2HSV);            Color space conversion from BGR to HSV if (track_object) {int _vmin = vmin, _vmax = Vmax;   Cvinranges (HSV, Cvscalar (0,smin,min (_vmin,_vmax), 0), Cvscalar (180,256,max (_vmin,_vmax), 0), mask);  Get a mask of two values Cvsplit (HSV, Hue, 0, 0, 0);                ? Only hue Hue component if (Track_object < 0) {float max_val = 0.f;  Cvsetimageroi (hue, selection); Set the selection region to Roi Cvsetimageroi (mask, selection); Set the selection region to Roi cvcalchist (&hue, hist, 0, mask);  Calculate Histogram cvgetminmaxhistvalue (hist, 0, &max_val, 0, 0); Only the maximum value//zoom bin to the interval [0,255] Cvconvertscale (Hist->bins, Hist->bins, Max_val? 255./MAX_val:0., 0);  Cvresetimageroi (hue);                Removal of ROI Cvresetimageroi (mask);                Track_window = Selection;                Track_object = 1;                Cvzero (HISTIMG);  Bin_w = histimg->width/hdims; Hdims: Number of bars Bin_w: Width//histogram for (i = 0; i < hdims; i++) {int                    val = Cvround (cvgetreal1d (hist->bins,i) *histimg->height/255);                    Cvscalar color = Hsv2rgb (i*180.f/hdims); Cvrectangle (Histimg, Cvpoint (i*bin_w,histimg->height), Cvpoint ((i+1) *bin_w,histimg-&gt                ; height-val), Color,-1, 8, 0);            }} cvcalcbackproject (&hue, Backproject, hist);            Cvand (Backproject, Mask, backproject, 0); Call the Camshift algorithm module Cvcamshift (backproject, Track_window, Cvtermcriteria (cv_termcrit_eps |            Cv_termcrit_iter, 1), &track_comp, &track_box);            Track_window = Track_comp.rect; if (Backproject_mode) Cvcvtcolor (backproject, image, CV_GRAY2BGR);            Use Backproject grayscale image if (image->origin) track_box.angle =-track_box.angle;        Cvellipsebox (image, Track_box, Cv_rgb (255,0,0), 3, CV_AA, 0); } if (Select_object && selection.width > 0 && selection.height > 0) {Cvsetimagero            I (image, selection);            Cvxors (image, Cvscalarall (255), image, 0);        Cvresetimageroi (image);        } cvshowimage ("Camshiftdemo", image);        Cvshowimage ("Histogram", histimg);        c = Cvwaitkey (10);  if (c = =) break;            ESC exit Loop Switch (c) {case ' B ': Backproject_mode ^= 1;        Break            Case ' C ': track_object = 0;    Cvzero (HISTIMG);        Break            Case ' h ': show_hist ^= 1;            if (!show_hist) Cvdestroywindow ("histogram");            else Cvnamedwindow ("histogram", 1);        Break        Default:;    }} cvreleasecapture (&capture);    Cvdestroywindow ("Camshiftdemo"); return 0;} </span>

Operation Result:




OpenCV: Using the Camshift algorithm to track color targets

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.