python - 如何在 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)
谢谢
解决方案
首先,添加: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 所必需的。
推荐阅读
- c# - 在编码的 UI 测试中断言 div 中的所有 li
- java - JDBC postgresql 9.4 和 jboss-eap-7.0 错误 IJ030027:正在破坏无效的连接
- perl - Perl - 使用 Perl 模块实现 Perl 脚本
- javascript - 如何从 Web 应用程序打开 Google Maps 移动应用程序
- java - Sukili如何关闭应用程序的所有窗口?
- android - Android Gradle 构建错误 - 配置“:classpath”的工件
- .net - xunit runner 未在 Azure DevOps 构建管道中发现测试用例
- node.js - 在电子应用程序中处理“无法获取本地颁发者证书”的正确方法
- ios - 使用 Alamofire '~> 5.0.0-beta.3' 从 multipart-from-data 上传图像
- dotnetbrowser - 无头使用它并单击按钮/链接