首页 > 解决方案 > 如何在 Python 中将 julia 集图像保存为 png?

问题描述

这个指向 mpi 文档的链接将 Julia 集保存为 .pgm

有什么方法可以更改此代码以将图像另存为 .png 文件?

from mpi4py.futures import MPIPoolExecutor

x0, x1, w = -2.0, +2.0, 640*2
y0, y1, h = -1.5, +1.5, 480*2
dx = (x1 - x0) / w
dy = (y1 - y0) / h

c = complex(0, 0.65)

def julia(x, y):
    z = complex(x, y)
    n = 255
    while abs(z) < 3 and n > 1:
        z = z**2 + c
        n -= 1
    return n

def julia_line(k):
    line = bytearray(w)
    y = y1 - k * dy
    for j in range(w):
        x = x0 + j * dx
        line[j] = julia(x, y)
    return line

if __name__ == '__main__':

    with MPIPoolExecutor() as executor:
        image = executor.map(julia_line, range(h))
        with open('julia.pgm', 'wb') as f:
            f.write(b'P5 %d %d %d\n' % (w, h, 255))
            for line in image:
                f.write(line)

谢谢

标签: python

解决方案


首先,添加:import matplotlib.pyplot as plt

删除该行下方的所有内容image = executor.map(...)并将其替换为:

plt.imsave("julia.png", image)

我很确定你会这样做,但请注意我还没有运行你的代码!

更新

好的,所以我仔细查看了代码,我猜测“图像”变量是代表图像中每一行的字节数组元组。尝试:

image = np.array([list(l) for l in image])

就在 plt.imsave(...) 行之前。这会将每个字节数组转换为一个列表,然后将它们打包到一个外部列表中。您现在还需import numpy as np要这样做,因为我相信这是将嵌套列表转换为 matplotlib 可以保存的漂亮 ndarray 所必需的。


推荐阅读