Python: find area of polygon from xyz coordinates

后端 未结 5 1133
你的背包
你的背包 2020-12-28 18:07

I\'m trying to use the shapely.geometry.Polygon module to find the area of polygons but it performs all calculations on the xy plane. This is fine

5条回答
  •  礼貌的吻别
    2020-12-28 18:29

    Same as @Tom Smilack's answer, but in javascript

    //determinant of matrix a
    function det(a) {
      return a[0][0] * a[1][1] * a[2][2] + a[0][1] * a[1][2] * a[2][0] + a[0][2] * a[1][0] * a[2][1] - a[0][2] * a[1][1] * a[2][0] - a[0][1] * a[1][0] * a[2][2] - a[0][0] * a[1][2] * a[2][1];
    }
    //unit normal vector of plane defined by points a, b, and c
    function unit_normal(a, b, c) {
      let x = math.det([
        [1, a[1], a[2]],
        [1, b[1], b[2]],
        [1, c[1], c[2]]
      ]);
      let y = math.det([
        [a[0], 1, a[2]],
        [b[0], 1, b[2]],
        [c[0], 1, c[2]]
      ]);
      let z = math.det([
        [a[0], a[1], 1],
        [b[0], b[1], 1],
        [c[0], c[1], 1]
      ]);
      let magnitude = Math.pow(Math.pow(x, 2) + Math.pow(y, 2) + Math.pow(z, 2), 0.5);
      return [x / magnitude, y / magnitude, z / magnitude];
    }
    // dot product of vectors a and b
    function dot(a, b) {
      return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
    }
    // cross product of vectors a and b
    function cross(a, b) {
      let x = (a[1] * b[2]) - (a[2] * b[1]);
      let y = (a[2] * b[0]) - (a[0] * b[2]);
      let z = (a[0] * b[1]) - (a[1] * b[0]);
      return [x, y, z];
    }
    
    // area of polygon poly
    function area(poly) {
      if (poly.length < 3) {
        console.log("not a plane - no area");
        return 0;
      } else {
        let total = [0, 0, 0]
        for (let i = 0; i < poly.length; i++) {
          var vi1 = poly[i];
          if (i === poly.length - 1) {
            var vi2 = poly[0];
          } else {
            var vi2 = poly[i + 1];
          }
          let prod = cross(vi1, vi2);
          total[0] = total[0] + prod[0];
          total[1] = total[1] + prod[1];
          total[2] = total[2] + prod[2];
        }
        let result = dot(total, unit_normal(poly[0], poly[1], poly[2]));
    
        return Math.abs(result/2);
      }
    
    }

提交回复
热议问题