所以我正在编写这个程序来创建曼德布罗集的图片,并且我一直在逐步改进它。现在,产生的每个进程都会将一些数据写入一个临时文件,稍后将使用该文件将图片放在一起。然而,现在临时文件比实际图片本身大很多,我对如何使它们更小没有任何想法。如何有效地将整数数据写入文件并将其取回?我打算最终使它非常可扩展,因此我需要能够为像素索引编写任意长的整数,但颜色数据始终是最大值为 255 的三个整数。这是我的代码:
import multiprocessing
def pixproc(y0, yn, xsteps, ysteps, fname):
XMIN, YMIN = -2., -1.
XLEN, YLEN = 3, 2
with open(fname, 'w') as f:
for y in xrange(y0, yn):
print y
for x in xrange(xsteps):
c=complex(XMIN + XLEN*(1.*x/xsteps),
YMIN + YLEN*(1.*y/ysteps))
k=c
for i in xrange(256):
k = k*k + c
if abs(k)>2: break
if 0<i<32:
#print 'Success!', i
print >>f, x, y, 8*i, 0, 0 #This is that part of
if 32<=i<255: #my code that I am trying
#print 'Success!', i #to improve. The rest of
print >>f, x, y, 255, i, i #the code is given for context
return #and isn't relevant to my question
def main(xsteps, ysteps):
pool = multiprocessing.Pool()
n = multiprocessing.cpu_count()
step = height / n
fnames = ["temp" + str(i) for i in xrange(n)]
for i in xrange(n):
pool.apply_async(pixproc,
(step*i,
step*(i+1),
xsteps,
ysteps,
fnames[i]))
pool.close()
pool.join()
return fnames
if __name__=="__main__":
from PIL import Image
import sys
width, height = map(int, sys.argv[1:])
picname = "mandelbrot1.png"
fnames = main(width, height)
im = Image.new("RGB", (width, height))
pp = im.load()
for name in fnames:
with open(name) as f:
for line in f:
line = map(int, line.rstrip('\n').split(' '))
pp[line[0], line[1]] = line[2], line[3], line[4]
im.save(picname)
当我尝试制作 3000x2000 的图片时,实际图片为 672 KB,但临时文件都接近 30 MB!有人可以建议一种将数据存储在文件中的更好方法吗?(重要的部分在函数 pixproc 中)