私は自分自身で OpenCV を学んでいて、今日、次のコードを書いて、コンピューターのウェブカメラ フィードを横切って転がるボールを追跡し、その重心に灰色の円で塗りつぶされた円を (試みて) 描画します。
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
Point getBlobCentroid(Mat blobImage);
int main()
{
Mat bGround, fGround, diff;
Point p = (500, 280);
VideoCapture cap(0);
while (true)
{
cap >> fGround; //assign frame from camera to newest image
cvtColor(fGround, fGround, CV_BGR2GRAY); //convert to grayscale
bGround.create(fGround.size(), fGround.type());
absdiff(bGround, fGround, diff); //subtract current frame from old frame
threshold(diff, diff, 50, 255, CV_THRESH_BINARY); //convert to binary
erode(diff, diff, NULL, Point(-1,-1), 3, 0, BORDER_DEFAULT);
imshow("Thresholded", diff);
circle(fGround, getBlobCentroid(diff), 6, 127, -1, 8, 16);
imshow("Natural Image with Tracking", fGround);
fGround.copyTo(bGround); //move forward in time
waitKey(1);
}
return 0;
}
Point getBlobCentroid(Mat blobImage)
{
int rowSum=0, colSum=0, count = 1;
for(int i=0; i<blobImage.rows; i++)
{
for (int j=0; j<blobImage.cols; j++)
{
if (blobImage.at<uchar>(i,j) == 255)
{
rowSum+=i;
colSum+=j;
count++;
}
}
}
Point centroid = (rowSum, colSum)/count;
return centroid;
}
ただし、添付の画像から明らかなように、円は画面の上部から離れることはありません。つまり、centroid.y コンポーネントは常にゼロです。計算の一連のステップを画面に書き込んだところ、検索や、rowSum や count への追加などの作業が行われているように見えますが、それらはゼロではありません。ただし、重心を計算したり、円で呼び出したりするとすぐに、それはうまくいきません。さらに奇妙なことに、円 Point p = (285, 285) の一定の中心を作成し、それを引数として使用しようとしましたが、それもうまくいきませんでした。ヘルプ?ありがとう!
-トニー