JavaRush /Java Blog /Random EN /Finding the center of an irregular figure on a plane
Level 26

Finding the center of an irregular figure on a plane

Published in the Random EN group
Hi all. I'm solving a simple problem right now. The condition sounds something like this:
Given a matrix (two-dimensional array), in which each element represents a pixel. Pixels can be red, black, or some other color. It is necessary to implement a search for the red-eye effect in the image. If the center of the black pixels coincides with the center of the red pixels, then we have found a red eye.
It is assumed that the boundaries of the range of red pixels are wider than the boundaries of the range of black pixels. Also, options are not considered if the image contains red and black pixels outside the “eye”. Everything outside the “eye” will be a different color. I planned to implement it using (approximately) this algorithm. Two loops, one nested within the other. One goes through X, the other goes through Y. As soon as we find the red pixel, we fix its coordinates as the initial ones and look for the final coordinates. As soon as it turns out that red pixels no longer appear, we fix the last red pixel that we came across as the final coordinates of the range of red pixels. Same with black pixels. Then we divide the ranges in half and find the centers. Such an algorithm will work quite well with figures of more or less regular shape (circle). And here I decided to complicate my task)) Namely, to understand how to improve the algorithm for irregular shapes. For example, if a person has some vision problems (due to which the shape of the eye may be incorrect), or the photo was taken at an angle, or some other situations... A quick search brought me to Wikipedia articles about the center of mass and barycenter . But there is so much scary and terrible language there that I decided to put it aside for now and ask the community how you would implement this? :)