# Center of rectangles and centroid [closed]

Hi guys, i want to ask simple question, is center of rectangles in opencv center attribute of rect same with centroid ? thanks.

edit retag reopen merge delete

### Closed for the following reason question is off-topic or not relevant by Kenny Karnama close date 2018-04-14 10:58:15.756026

Sort by » oldest newest most voted

Image moments help you to calculate some features like center of mass of the object, area of the object etc.

Suppose you have a contour cnt that is found from cv2.findContours()

M = cv2.moments(cnt)

From this moments, you can extract useful data like area, centroid etc. Centroid is given by the relations:

cx = int(M['m10']/M['m00'])

cy = int(M['m01']/M['m00'])

more 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.

more

Official site

GitHub

Wiki

Documentation

## Stats

Asked: 2018-04-08 00:52:17 -0500

Seen: 5,837 times

Last updated: Apr 10 '18