2013-02-19 155 views
0

我想在边界框中绘制一个点,表示该框的中心点。 我已经计算了中心点,但它只能在CMD中输出,并且我不会将此点显示在图像上。OpenCV绘图边界框CenterPoint

我与OpenCV2.4.3工作的Visual Studio 2010的C++

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; 
    } 

以上是我用得好只是一小部分,但是,负责包围盒计算的一部分代码

回答

2

哦,你已经计算出了这个区域,现在你正在试图将中心(Point)分配给那个?不好了。用你的最后一行代替:

//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; 

另外,你的boundingBoxArea是错误的。请改用原始的boundingRect [i](用于计算面积),请!

+0

看起来这实际上现在允许我使用Circle()函数来绘制我的点/中心点 – Tomazi 2013-02-19 23:16:32

+0

但是,中心点会在边界框外绘制,所以此代码存在更多问题:D – Tomazi 2013-02-19 23:19:06

+0

再次发现;)boundingBoxArea是错误的,请使用初始boundRect代替 – berak 2013-02-19 23:34:11

0

确定家伙,我设法解决我自己我自己的问题让我感到骄傲嘿嘿:d

我发布了一个等式它的自我是错的,因为我分割两X &宽度和y &与错误的是由x &给出的抵消错误。所以我改变了代码,所以我只划分宽度/ 2和高度/ 2

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

希望这可以帮助一些人有一天:d

THX到@berak

最终结果:

enter image description here

1

替代

使用矩,你的代码也可能看起来如下(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); 
.. 

背景

图像矩帮助您计算像物体的质量中心的一些功能,对象等方面退房wikipedia页图像矩

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教程here