2

我正在尝试在边界框中绘制一个点,它将代表该框的中心点。我已经计算了中心点,但它只在 CMD 中输出,我不会在图像上看到这个点。

我在 Visual Studio 2010 C++ 上使用 OpenCV2.4.3

 for(int i= 0; i < boundRect.size(); i++ )
       {
            //BoundingBox Area
            boundingBoxArea.clear();
            boundingBoxArea.push_back(Point2f(boundRect[i].x, boundRect[i].y));
            boundingBoxArea.push_back(Point2f(boundRect[i].x + boundRect[i].width, boundRect[i].y));
            boundingBoxArea.push_back(Point2f(boundRect[i].x + boundRect[i].width, boundRect[i].y + boundRect[i].height));
            boundingBoxArea.push_back(Point2f(boundRect[i].x, boundRect[i].y + boundRect[i].height));

            double area0 = contourArea(boundingBoxArea);

            cout << "area of bounding box no." << i << " = " << area0 << endl;

            //Bounding Box Centroid
            area0 = (boundRect[i].x + boundRect[i].width)/2, (boundRect[i].y + boundRect[i].height)/2;

            cout<<"Rectangle " <<i<< " Centroid possition is at: " "=" <<area0<<endl;
            cout<<""<<endl;
            cout<<""<<endl;
     }

以上是我很好用的代码,只有一小部分,但有一部分负责边界框的计算

4

3 回答 3

3

oh, you already calculated the area, and now you're trying to assing the center(Point) to that ? oh, no. replace your last lines with:

//Bounding Box Centroid
Point center = Point((boundRect[i].x + boundRect[i].width)/2, (boundRect[i].y + boundRect[i].height)/2);

// print it:
cout<<"Rectangle " <<i<< " Centroid position is at: " << center.x << " " << center.y << endl;

also, your boundingBoxArea is wrong. take the original boundingRect[i] instead (for calculating the area), please!

于 2013-02-19T22:48:51.803 回答
1

选择

使用 Moments,您的代码也可能如下所示(java,未测试):

..
MatOfPoint contour = new MatOfPoint();
Rect box = boundRect[i];
//Points order doesn't matter
contour.fromArray(new Point[]{new Point(box.x, box.y), //top-left
                  new Point(box.x + box.width, box.y), // top-right
                  new Point(box.x,  box.y + box.height)}); //bottom-left
                  new Point(box.x + box.width, box.y + box.height), //bottom right
int Cx = (int)Math.round(M.get_m10()/M.get_m00());
int Cy = (int)Math.round(M.get_m01()/M.get_m00());
..
double area0 = Imgproc.contourArea(contour);
..

背景

图像时刻可帮助您计算一些特征,例如物体的质心、物体的面积等。查看图像时刻上的维基百科页面

import cv2
import numpy as np

img = cv2.imread('star.jpg',0)
ret,thresh = cv2.threshold(img,127,255,0)
contours,hierarchy = cv2.findContours(thresh, 1, 2)

cnt = contours[0]
M = cv2.moments(cnt)
print M

质心由关系Cx=M10/M00Cy=M01/M00给出。

Cx = int(M['m10']/M['m00'])
Cy = int(M['m01']/M['m00'])

请参阅此处的OpenCV 教程。

于 2015-09-24T13:06:51.063 回答
0

好吧,伙计们,我自己解决了自己的问题让我感到自豪,呵呵:D

我发布了它自己的方程式是错误的,因为我将 x & width 和 y & 除错了 x & y 给出的偏移量是错误的。所以我改变了代码,所以我只划分 width/2 和 height/2

解决方案的最终成分是使用 cv::circle(); 我用来绘制中心点的函数。

希望有一天这能帮助一些人:D

谢谢@berak

最后结果:

在此处输入图像描述

于 2013-02-20T00:20:55.840 回答