2013-02-19 164 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