我正在尝试在边界框中绘制一个圆点,它将代表该框的中心点。 我已经计算了中心点,但它只在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;
}
上面的代码我只使用了一小部分,但是负责计算边界框的部分
答案 0 :(得分:2)
//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](用于计算面积),
答案 1 :(得分: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);
..
<强>背景强>
图像时刻可帮助您计算某些功能,如对象的质心,对象的区域等。查看图像时刻的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 / M00 和 Cy = M01 / M00 。
Cx = int(M['m10']/M['m00'])
Cy = int(M['m01']/M['m00'])
请参阅OpenCV教程here。
答案 2 :(得分:0)
好的家伙我设法自己解决了自己的问题让我感到自豪嘿嘿:D
我发布了自己的方程式错误,因为我将x&amp;宽度和y&amp;由x和amp;给出的偏移是错误的你错了。所以我更改了代码,以便我只划分宽度/ 2和高度/ 2
解决方案的最终成分是使用cv :: circle();我用来画中心点的功能。
希望希望有些人可以帮助某些人:Dthx to @berak
最终结果: