资源简介
基于颜色的目标追踪源码,可以识别颜色后进行追踪 ,有进一步优化的空间
代码片段和文件信息
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%% %%%%%%
%%%%%% 欢迎到www.opencvchina.com下载源代码和资料 %%%%%%
%%%%%% %%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
*/
/*
* Code written by Lya (GeckoGeek.fr)
*/
#include “opencv/highgui.h“
#include “opencv/cv.h“
#include
#include
#include
// Maths methods
#define max(a b) ((a) > (b) ? (a) : (b))
#define min(a b) ((a) < (b) ? (a) : (b))
#define abs(x) ((x) > 0 ? (x) : -(x))
#define sign(x) ((x) > 0 ? 1 : -1)
// Step mooving for object min & max
#define STEP_MIN 5
#define STEP_MAX 100
IplImage *image;
// Position of the object we overlay
CvPoint objectPos = cvPoint(-1 -1);
// Color tracked and our tolerance towards it
int h = 0 s = 0 v = 0 tolerance = 10;
/*
* Transform the image into a two colored image one color for the color we want to track another color for the others colors
* From this image we get two datas : the number of pixel detected and the center of gravity of these pixel
*/
CvPoint binarisation(IplImage* image int *nbPixels) {
int x y;
CvScalar pixel;
IplImage *hsv *mask;
IplConvKernel *kernel;
int sommeX = 0 sommeY = 0;
*nbPixels = 0;
// Create the mask &initialize it to white (no color detected)
mask = cvCreateImage(cvGetSize(image) image->depth 1);
// Create the hsv image
hsv = cvCloneImage(image);
cvCvtColor(image hsv CV_BGR2HSV);
// We create the mask
cvInRangeS(hsv cvScalar(h - tolerance -1 s - tolerance 0) cvScalar(h + tolerance -1 s + tolerance 255) mask);
// Create kernels for the morphological operation
kernel = cvCreateStructuringElementEx(5 5 2 2 CV_SHAPE_ELLIPSE);
// Morphological opening (inverse because we have white pixels on black background)
cvDilate(mask mask kernel 1);
cvErode(mask mask kernel 1);
// We go through the mask to look for the tracked object and get its gravity center
for(x = 0; x < mask->width; x++) {
for(y = 0; y < mask->height; y++) {
// If its a tracked pixel count it to the center of gravity‘s calcul
if(((uchar *)(mask->imageData + y*mask->widthStep))[x] == 255) {
sommeX += x;
sommeY += y;
(*nbPixels)++;
}
}
}
// Show the result of the mask image
cvShowImage(“GeckoGeek Mask“ mask);
// We release the memory of kernels
cvReleaseStructuringElement(&kernel);
// We release the memory of the mask
cvReleaseImage(&mask);
// We release the memory of the hsv image
cvReleaseImage(&hsv);
// If there is no pixel we return a center outside the image else we return the center of gravity
if(*nbPixels > 0)
return cvPoint((int)(sommeX / (*nbPixels)) (int)(sommeY / (*nbPixels)));
else
ret
- 上一篇:根据原图和二值图得到分割彩图
- 下一篇:进程的同步-吃水果问题
评论
共有 条评论