Finding the center of mass on a 2D bitmap

前端 未结 3 1875
萌比男神i
萌比男神i 2020-12-31 13:54

I\'m coding a game, and I\'d like to be able to find the center of mass of an arbitrary shape on a black and white bitmap such as this:

 012345678
0.XX......
1..X         


        
3条回答
  •  死守一世寂寞
    2020-12-31 14:21

    How about this algorithm (psuedo-code) based on a boolean matrix like in your example :

    xSum = 0
    ySum = 0
    points = 0
    
    for point in matrix
        if point is marked
            xSum += pointX
            ySum += pointY
            points++
    
    return (xSum/points, ySum/points)
    

    Nothing too complicated, calculate where X is the most present, same for Y, divide by number of points you counted, and you got the center of mass. You can further complicate this by giving certain points different weight in the averaging, but this should be your main direction.


    This question got me thinking about an expansion to this question which I could not find a good answer to. I posted the question here: Finding clusters of mass in a matrix/bitmap

提交回复
热议问题