Center of gravity of a polygon

后端 未结 7 933
遥遥无期
遥遥无期 2020-12-02 16:13

I am trying to write a PHP function that will calculate the center of gravity of a polygon.

I\'ve looked at the other similar questions but I can\'t seem to find a s

7条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-02 16:33

    Here is my implementation in Python, based off the C++ implementation from Joseph. I think it is clearer than the other python answer.

    def find_centroid(polygon):
        """ Computes the centroid (a.k.a. center of gravity) for a non-self-intersecting polygon.
    
        Parameters
        ----------
        polygon : list of two-dimensional points (points are array-like with two elements)
            Non-self-intersecting polygon (orientation does not matter).
    
        Returns
        -------
        center_of_gravity : list with 2 elements
            Coordinates (or vector) to the centroid of the polygon.
        """
        offset = polygon[0]
        center_of_gravity = [0.0, 0.0]
        double_area = 0.0
        for ii in range(len(polygon)):
            p1 = polygon[ii]
            p2 = polygon[ii-1]
            f = (p1[0]-offset[0])*(p2[1]-offset[1]) - (p2[0]-offset[0])*(p1[1]-offset[1])
            double_area += f
            center_of_gravity[0] += (p1[0] + p2[0] - 2*offset[0]) * f
            center_of_gravity[1] += (p1[1] + p2[1] - 2*offset[1]) * f
        center_of_gravity[0] = center_of_gravity[0] / (3*double_area) + offset[0]
        center_of_gravity[1] = center_of_gravity[1] / (3*double_area) + offset[1]
        return center_of_gravity
        # If you want to return both the CoG and the area, comment the return above
        return center_of_gravity, abs(double_area/2)
    

提交回复
热议问题