python 判断多边形顺逆时针

计算面积,用面积的正负判断方向,如果面积是正,则是逆时针,面积是负则是顺时针。

在计算几何里,我们知道,△ABC的面积就是“向量AB”和“向量AC”两个向量叉积的绝对值的一半。其正负表示三角形顶点是在右手系还是左手系(面积是有向面积(有正负)), 负 则是左手系,反之,右手系。

需要注意的是在屏幕坐标中,Y是向下的,所以在屏幕坐标系中看到的顺时针既是在Y轴向上的直角坐标系中看到的逆时针方向。

# -*- coding: utf-8 -*-#
# -------------------------------------------------------------------------------
# Name:         python判断多变形是顺时针还是逆时针
# Author:       yunhgu
# Date:         2022/4/24 9:16
# Description: 
# -------------------------------------------------------------------------------
from PIL import Image, ImageDraw


def calculate_polygon_area(points_list):
    n = len(points_list)
    if n < 3:
        return 0.0
    area = 0
    for i in range(n):
        x = points_list[i][0]
        y = points_list[i][1]
        area += x * points_list[(i + 1) % n][1] - y * points_list[(i + 1) % n][0]
    return area * 0.5


def show_point(points_list, image_name):
    image = Image.new("RGB", (100, 100), color='white')
    draw = ImageDraw.Draw(image)
    draw.line(points_list, fill="green", width=1)
    for index, point in enumerate(points_list):
        x, y, r = point[0], point[1], 2
        draw.text((x, y), str(index), fill="red")
        draw.ellipse((x - r, y - r, x + r, y + r), fill='blue')
    image.save(image_name)


if __name__ == '__main__':
    points = [(5, 5), (10, 50), (40, 40), (30, 35), (5, 5)]
    for point_list in [points, points[::-1]]:
        area = calculate_polygon_area(point_list)
        order = "顺时针" if area > 0 else "逆时针"
        print(f"{point_list}:{area}:{order}")
        show_point(point_list, f"{order}.jpg")

image

image
image

posted @ 2022-04-24 09:56  不能说的秘密  阅读(766)  评论(0编辑  收藏  举报