| [Python] 纯文本查看 复制代码 # 导入数学模块
import math
# 导入matplotlib库,用于绘图
import matplotlib.pyplot as plt
# 定义一个三维坐标类
class Point3D:
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z
# 定义一个二维坐标类
class Point2D:
    def __init__(self, x, y):
        self.x = x
        self.y = y
# 定义一个投影矩阵类
class ProjectionMatrix:
    def __init__(self, a, b, c, d):
        # 投影矩阵是一个 3x4 的矩阵,形如:
        # | a b c d |
        # | e f g h |
        # | i j k l |
        # 这里只需要输入前四个元素,后八个元素默认为 0 0 0 0 1 0 0 1
        self.a = a
        self.b = b
        self.c = c
        self.d = d
    # 定义一个乘法运算符,用于将投影矩阵乘以三维坐标,得到二维坐标
    def __mul__(self, point):
        # 根据矩阵乘法的规则,计算二维坐标的 x 和 y 坐标
        x = self.a * point.x + self.b * point.y + self.c * point.z + self.d
        y = point.z + 1
        # 返回一个二维坐标对象
        return Point2D(x, y)
# 定义一个测试函数,用于生成一些三维坐标,并将它们转换为二维坐标,打印出来,并绘制出散点图
def test():
    # 创建一个投影矩阵对象,参数可以自己调整
    matrix = ProjectionMatrix(0.5, -0.5, 0.5, 0)
    # 创建一个空列表,用于存储三维坐标对象
    points_3d = []
    # 用循环生成一些三维坐标对象,这里以圆柱体为例,可以自己修改形状和范围
    for z in range(-10, 10):
        for angle in range(0, 360, 10):
            # 计算圆柱体上的点的 x 和 y 坐标,半径为 5
            x = 5 * math.cos(math.radians(angle))
            y = 5 * math.sin(math.radians(angle))
            # 创建一个三维坐标对象,并添加到列表中
            point = Point3D(x, y, z)
            points_3d.append(point)
    # 创建一个空列表,用于存储二维坐标对象
    points_2d = []
    # 用循环遍历三维坐标列表,将每个三维坐标乘以投影矩阵,得到二维坐标,并添加到列表中
    for point in points_3d:
        point_2d = matrix * point
        points_2d.append(point_2d)
    # 打印出二维坐标的列表
    print_points(points_2d)
    # 绘制出二维坐标的散点图
    plot_points(points_2d)
# 定义一个打印函数,用于打印出二维坐标的列表
def print_points(points_2d):
    # 用循环遍历二维坐标列表,打印出每个坐标
        for point in points_2d:
          print(f"({point.x}, {point.y})")
# 定义一个绘图函数,用于绘制出二维坐标的散点图
def plot_points(points_2d):
    # 创建一个空列表,用于存储二维坐标的 x 值
    x_values = []
    # 创建一个空列表,用于存储二维坐标的 y 值
    y_values = []
    # 用循环遍历二维坐标列表,将每个坐标的 x 和 y 值分别添加到对应的列表中
    for point in points_2d:
        x_values.append(point.x)
        y_values.append(point.y)
    # 调用matplotlib库的scatter函数,用散点图的方式绘制出二维坐标
    plt.scatter(x_values, y_values)
    # 调用matplotlib库的show函数,显示出图像
    plt.show()
# 调用测试函数,运行代码
if __name__ == '__main__':
  test()
 |