Find Centroid of a rectangular mask
10 views (last 30 days)
Show older comments
Bankim Chandra Yadav
on 29 Jul 2016
Commented: Bankim Chandra Yadav
on 8 Sep 2016
Four coordinates of a rectangle are given. I need to find the centroid of the area enclosed by the polygon.
Either provide the pixel values and coordinate values of all the pixels enclosed by the polygon OR Provide the centroid of the polygon directly. Please help me out.
0 Comments
Accepted Answer
Image Analyst
on 29 Jul 2016
You don't need MATLAB for that, but if you insist. Assuming the x coordinates and y coordinates are in separate arrays....
xCentroid = mean(x);
yCentroid = mean(y);
If you want a digital image pixel value, then round to the nearest row and column:
grayLevel = grayImage(round(yCentroid), round(xCentroid));
3 Comments
Image Analyst
on 29 Jul 2016
In MATLAB, that's called the weighted centroid - like a center of mass. That is weighted by the pixel values. The plain centroid is just based on the shape alone (of the binary image) and doesn't care at all about pixel values. To compute the centroid of weighted centroid, get a binary image, for example using poly2mask()), then call regionprops. Attached is a demo. If it answers your question, you can "Accept this answer" and vote for it.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/184239/image.png)
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!