[Python] 借助 Pillow 和 NumPy 生成与斐波那契数列有关的图案

94 阅读4分钟

背景

受到下图的启发(图片来源),我想到可以借助 Pillow\text{Pillow} 来生成类似的图案(为了降低难度,就不展示其中的圆周和数字了)。而这里又涉及矩阵的拼接操作,如果用 NumPy\text{NumPy} 来处理矩阵操作,会事半功倍。

330px-Fibonacci_Spiral.svg.webp

最终的效果展示如下(我不确定上传的图片的分辨率是否会变低,我本地可以看到更清晰的效果)

fib.png

在我本地,将图片放大后,可以看到有两个 11 像素的方块 ⬇️ image.png

正文

现在人工智能非常强大,即使有些细节没有想清楚,也可以让它们帮我们来进行完善。

核心逻辑

斐波那契数列的生成

斐波那契数列的生成比较直观,可以自己实现,然后让人工智能来优化,或者直接让人工智能来完成也行。(因为我觉得这部分逻辑属于“重要但简单”的那种,可以不必亲力亲为)

矩阵拼接

我们需要将不同大小的矩阵进行拼接,我在下图中标出了部分矩阵的边长 ⬇️

image.png

我们需要不断将新的矩阵拼接到现有矩阵的旁边(上下左右 里的某一侧)。

为了方便理解,我选择了4个连续的步骤,制作了下方的4张截图来进行说明。

将要拼接大小为 2×22 \times 2 的矩阵时
image.png
将要拼接大小为 3×33 \times 3 的矩阵时
image.png
将要拼接大小为 5×55 \times 5 的矩阵时
image.png
将要拼接大小为 8×88 \times 8 的矩阵时
image.png

如果不想自己查阅 NumPy\text{NumPy}api\text{api} 文档,可以借助人工智能。下图展示了我使用 trae 的过程 (完整的回答比较长,图里只截取了开头的部分,我问的问题不止这些,就不赘述了)⬇️

image.png image.png

像素处理

Pillow\text{Pillow}Tutorial 中介绍了很多相关知识。trae 帮我优化代码后,使用了 fromarray 这个方法。(我自己写的代码里,用的是 Image.new 这个方法)

颜色的选择

我最初是想用 红黄绿蓝 这四种常见的颜色来填充矩阵,但是效果不太好,局部的效果如下 ⬇️

image.png

这样的图片,给人看的话,可能会让人感觉代码有 bug 😂。我想了想,因为拼接矩阵以四步为周期,所以这四个颜色会在固定的方位(以上图为例,红色总是用于填充位于下方的矩阵)。于是我就把颜色改成了五种(其实就是加了橙色),这样就可以避免“一个颜色总是出现在相同的方位”的问题。相关的代码片段如下 ⬇️

COLORS = ["r", "o", "y", "g", "b"]
COLOR_MAP = {
    "r": (255, 0, 0),  # red
    "o": (255, 165, 0),  # orange
    "y": (255, 255, 0),  # yellow
    "g": (0, 255, 0),  # green
    "b": (0, 0, 255),  # blue
}

如果您想使用四种颜色的那个版本,那么将对应的代码片段替换为下方这个版本即可

# 注意:本文所提供的“完整的代码”里用的不是这段代码
COLORS = ["r", "y", "g", "b"]
COLOR_MAP = {
    "r": (255, 0, 0),  # red
    "y": (255, 255, 0),  # yellow
    "g": (0, 255, 0),  # green
    "b": (0, 0, 255),  # blue
}

完整的代码

经过 trae 的优化,最终版本的完整代码如下 ⬇️

import numpy as np
from PIL import Image

FIB_COUNT = 13
COLORS = ["r", "o", "y", "g", "b"]
COLOR_MAP = {
    "r": (255, 0, 0),  # red
    "o": (255, 165, 0),  # orange
    "y": (255, 255, 0),  # yellow
    "g": (0, 255, 0),  # green
    "b": (0, 0, 255),  # blue
}


def generate_fibonacci(count):
    result = [0] * count
    result[0] = 1
    if count > 1:
        result[1] = 1
        for i in range(2, count):
            result[i] = result[i - 1] + result[i - 2]
    return result


def build_fib_board():
    color_matrix = None
    for index, fib in enumerate(generate_fibonacci(FIB_COUNT)):
        square = np.full(
            (fib, fib), COLORS[index % len(COLORS)]
        )
        if color_matrix is None:
            color_matrix = square
            continue
        if index % 4 == 1:
            color_matrix = np.concatenate((color_matrix, square), axis=1)
        elif index % 4 == 2:
            color_matrix = np.concatenate((square, color_matrix), axis=0)
        elif index % 4 == 3:
            color_matrix = np.concatenate((square, color_matrix), axis=1)
        else:
            color_matrix = np.concatenate((color_matrix, square), axis=0)
    return color_matrix


def build_image(color_matrix):
    height, width = color_matrix.shape
    rgb = np.zeros((height, width, 3), dtype=np.uint8)
    for code, color in COLOR_MAP.items():
        rgb[color_matrix == code] = color
    return Image.fromarray(rgb)


def main():
    color_matrix = build_fib_board()
    img = build_image(color_matrix)
    img.show()
    img.save('fib.png')


if __name__ == "__main__":
    main()

请将以上代码保存为 main.py\text{main.py}。使用如下的命令可以运行 main.py\text{main.py}

python3 main.py

运行之后,您本地应该会生成一个名为 fib.png\text{fib.png} 的图片文件。

参考资料