Ask Your Question
0

Center of rectangles and centroid [closed]

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

Kenny Karnama gravatar image

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

edit retag flag offensive 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

Comments

opencv problem? off topics

LBerger gravatar imageLBerger ( 2018-04-09 02:24:29 -0500 )edit

2 answers

Sort by ยป oldest newest most voted
1

answered 2018-04-10 04:20:41 -0500

hoang anh tuan gravatar image

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

See it for more information

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'])

edit flag offensive delete link more
1

answered 2018-04-09 00:30:04 -0500

rwong gravatar image

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.

edit flag offensive delete link more

Question Tools

1 follower

Stats

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

Seen: 2,098 times

Last updated: Apr 10 '18