Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

The typical way of calculating the center / centroid of a rectangle is

cv::Rect2d rect = ...;
cv::Point2d center = rect.tl() + 0.5 * cv::Point2d(rect.size());

// alternatively
double centerX = rect.x + 0.5 * rect.width;
double centerY = rect.y + 0.5 * rect.height;

If the rectangle has integer coordinates, there may be situations where one has to be careful with precise definitions. For example, if a rectangle with integer coordinates has a width that is an even number, then the rectangle can be evenly divided into a left-half and a right-half, but the line that divides the two (i.e. the line which must pass through the centroid) falls between two integer coordinates, which makes it (some integer plus 0.5). It is up to you how to handle this situation.

There are some other situations that require subtracting one from the rectangle's size (width and height):

cv::Rect rect = ...; // integer-coordinates
// you may sometimes see implementations like this
double centerX = rect.x + 0.5 * (rect.width - 1);
double centerY = rect.y + 0.5 * (rect.height - 1);

I don't remember off-hand why this is sometimes needed. It depends on the particular use-case. The reason can be explained using a diagram.

If you can provide more details, or a simple drawing illustrating what you want to accomplish, I can provide a better answer.