Tutorials and Code Examples
Back to all Tutorials and Code Examples
OpenCV Object Tracking Based on Pixel Color
This example provides a quick overview of how to track an object in OpenCV using pixel values. The algorithm is far more efficient than using cvGet2D(). Instead the IplImage imageData matrix is accessed directly and pixels are read pixel by pixel.
Download the .c file.
The binary output from img. The binary object is built pixel by pixel based upon trackbar input values (IplImage imgBG).
Click image for a larger view.
The blue ball is the target ball (IplImage img).
Click image for a larger view.
#include <iostream>
#include <windows.h>
#include <commctrl.h>
#include <iostream>
int bPos,bThreshold,rPos,rThreshold,gPos,gThreshold;
void onMouse(int event, int x, int y, int flags, void* param)
{
IplImage* img = (IplImage*) param;
if(img->origin)
{
y=img->height-y;
}
if(event==CV_EVENT_LBUTTONDOWN)
{
}
}
void TrackBlue_Onchange()
{
bThreshold = bPos;
}
void TrackRed_Onchange()
{
rThreshold = rPos;
}
void TrackGreen_Onchange()
{
gThreshold = gPos;
}
int main(void)
{
IplImage *img=0,*imgBG=0;
CvCapture *capture = cvCaptureFromCAM(2);
int x,y,r,g,b;
char* WindowName = "Image Window";
for(;;)
{
//Create Controls & Windows
cvCreateTrackbar("Blue",WindowName,&bPos,255,TrackBlue_Onchange);
cvCreateTrackbar("Red",WindowName,&rPos,255,TrackRed_Onchange);
cvCreateTrackbar("Green",WindowName,&gPos,255,TrackGreen_Onchange);
cvSetMouseCallback(WindowName, onMouse, (void*) img);
cvNamedWindow(WindowName, CV_WINDOW_AUTOSIZE);
cvNamedWindow("Norm", CV_WINDOW_AUTOSIZE);
img=cvQueryFrame(capture);
imgBG=cvCreateImage(cvGetSize(img), 8, 1);
uchar *imgBGData = (uchar *)imgBG->imageData;
for(y=0; yheight; y++)
{
uchar* ptr=(uchar*)(img->imageData+y*img->widthStep);
for(x=0; xwidth; x++)
{
//0 is Dark, 255 is bright
//GET
b=ptr[3*x];
g=ptr[3*x+1];
r=ptr[3*x+2];
//SET
if(b>bThreshold && rwidthStep+x*imgBG->nChannels]=255;
}else{
imgBGData[y*imgBG->widthStep+x*imgBG->nChannels]=0;
}
/*
if(r>100)//R
{
ptr[3*x]=0;//B
ptr[3*x+1]=0;//G
ptr[3*x+2]=0;//R
}
if(g>100)//G
{
ptr[3*x]=0;//B
ptr[3*x+1]=0;//G
ptr[3*x+2]=0;//R
}
*/
}
}
cvErode(imgBG,imgBG,0,10);
cvDilate(imgBG,imgBG,0,10);
double minVal,maxVal;
CvPoint minLoc,maxLoc;
cvMinMaxLoc(imgBG,&minVal,&maxVal,&minLoc,&maxLoc,0);
printf("minVal: %f,maxVal: %f,maxLoc x: %i,maxLoc y: %i\n",minVal,maxVal,maxLoc.x,maxLoc.y);
if(maxLoc.x>0 && maxLoc.y>0)
{
cvRectangle(img,maxLoc,cvPoint(maxLoc.x+80,maxLoc.y+80),cvScalar(125,255,0,0),1,1,0);
}
cvShowImage(WindowName,imgBG);
cvShowImage("Norm",img);
int cIn = cvWaitKey(15);
if(cIn == 27)
{
break;
}
}
cvReleaseImage(&img);cvReleaseImage(&imgBG);
cvReleaseCapture(&capture);
cvDestroyWindow(WindowName);cvDestroyWindow("Norm");
return EXIT_SUCCESS;
}
----
|