我目前正在制作一个跟踪4个桨的程序,有3种不同的颜色 . 凭借我现在的知识,以及如何降低运行项目的计算成本,我无法理解如何最好地继续进行 . 本文末尾列出了步骤的代码示例 .
该程序包含一个名为Controllers的类文件,它具有简单的get和set函数,用于X和Y位置,以及哪些HSV值用于阈值处理 .
处于未优化状态的程序现在执行以下操作:
从网络摄像头读取图像
将图像转换为HSV颜色空间
使用OpenCV的inRange函数以及一些先前定义的HSV最大/最小值,对HSV图像进行3次阈值处理,每个彩色画笔对应一个阈值 . 这节省了单独的Mat数组 .
(This step is problematic for me) - 对三个阈值图像中的每一个执行侵蚀和扩张 .
将图像传递给一个函数,该函数使用Moments创建描述轮廓的点矢量,然后使用矩计算X和Y位置,该位置保存为对象并推回到这些桨对象的矢量中 .
此时技术上的所有工作都可以工作,但是执行形态操作所需的资源每次循环通过从网络摄像头读取图像的while循环正在大大减慢程序 . (应用2次迭代的侵蚀,3次扩张3 640次*以可接受的帧速率拍摄480张图像 . )
Threshold Images for different paddles
inRange(HSV, playerOne.getHSVmin(), playerOne.getHSVmax(), threshold1);
inRange(HSV, playerTwo.getHSVmin(), playerTwo.getHSVmax(), threshold2);
inRange(HSV, powerController.getHSVmin(), powerController.getHSVmax(), threshold3);
Perform morphological operations
morphOps(threshold1);
void morphOps(Mat &thresh)
{
//Create a structuring element to be used for morph operations.
Mat structuringElement = getStructuringElement(MORPH_RECT, Size(3,3));
Mat dilateElement = getStructuringElement(MORPH_RECT, Size(6, 6));
//Perform the morphological operations, using two/three iterations because the noise is horrible.
erode(thresh, thresh, structuringElement, Point(-1, -1), 3);
dilate(thresh, thresh, dilateElement, Point(-1, -1), 2);
}
Track the image
trackFilteredObject(playerOne, threshold1, cameraFeed);
trackFilteredObject(playerTwo, threshold2, cameraFeed);
trackFilteredObject(powerController, threshold3, cameraFeed);
void trackFilteredObject(Controllers theControllers, Mat threshold, Mat HSV, Mat &cameraFeed)
{
vector players;
Mat temp;
threshold.copyTo(temp);
//these vectors are needed to save the output of findCountours
vector< vector > contours;
vector hierarchy;
//Find the contours of the image
findContours(temp, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE);
//Moments are used to find the filtered objects.
double refArea = 0;
bool objectFound = false;
if (hierarchy.size() > 0)
{
int numObjects = hierarchy.size();
//If there are more objects than the maximum number of objects we want to track, the filter may be noisy.
if (numObjects < MAX_NUM_OBJECTS)
{
for (int i = 0; i >= 0; i = hierarchy[i][0])
{
Moments moment = moments((Mat)contours[i]);
double area = moment.m00;
//If the area is less than min area, then it is probably noise
if (area > MIN_AREA)
{
Controllers player;
player.setXPos(moment.m10 / area);
player.setYPos(moment.m01 / area);
player.setType(theControllers.getType());
player.setColor(theControllers.getColor());
players.push_back(player);
objectFound = true;
}
else objectFound = false;
}
//Draw the object location on screen if an object is found
if (objectFound)
{
drawObject(players, cameraFeed);
}
}
}
}
我的想法是,我希望能够隔离每个对象,并使用X和Y位置作为三角形的点,并使用该信息来计算箭头射击的角度和功率 . 所以我想知道是否有更好的方法来隔离彩色桨并消除噪音,这不需要我对每种颜色执行这些形态学操作 .