PIL 不使用多处理绘制

时间:2021-04-28 10:21:38

标签: python python-imaging-library python-multiprocessing

在尝试制作一个程序来生成 mandelbrot 集的图像时,我试图通过将图像分成块以使用多处理处理来加快处理时间,但它不会在 PIL 中绘制到图像。我认为数据正在被正确处理,只是没有与全局图像交互。

from PIL import Image, ImageDraw
from mandelbrot import mandelbrot, MAX_ITER
import time
import threading
import multiprocessing
from numpy import floor
# Image size (pixels)
WIDTH = 150*2
HEIGHT = 150*2
t = time.time()


# End_Point = [-0.5,0]
# End_Zoom = 1.5
End_Point = [-4.556239E-2, -6.824076E-1]
End_Zoom = 4.167107E-5
End_Value = [End_Point[0]-End_Zoom, End_Point[0]+End_Zoom, -(End_Point[1])-End_Zoom, -(End_Point[1])+End_Zoom]


palette = []

im = Image.new('HSV', (WIDTH, HEIGHT), (0, 0, 0))
draw = ImageDraw.Draw(im)

def threadDraw(xPos, yPos,GridNumber):
    
    xStart = int(floor(xPos*WIDTH/GridNumber))
    xEnd = int(floor((xPos+1)*WIDTH/GridNumber))
    yStart = int(floor(yPos*HEIGHT/GridNumber))
    yEnd = int(floor((yPos+1)*HEIGHT/GridNumber))
    
    for x in range(xStart, xEnd):
        mapping[x] = []
        for y in range(yStart, yEnd):
            # Convert pixel coordinate to complex number
            c = complex(End_Value[0] + (x / WIDTH) * (End_Value[1] - End_Value[0]),
                        End_Value[2] + (y / HEIGHT) * (End_Value[3] - End_Value[2]))
            # Compute the number of iterations
            m = mandelbrot(c)
            # The color depends on the number of iterations
            hue = int(255 * m / MAX_ITER)
            saturation = 255
            value = 255 if m < MAX_ITER else 0
            # Plot the point 
            draw.point([x, y], (hue, saturation, value))
            #mapping[x].append([hue, saturation, value])
Division = 2
threads = []
if __name__ == '__main__':
    multiprocessing.freeze_support()
    for z in range(int(Division/2)):
            for l in range(int(Division/2)):
                threads.append(multiprocessing.Process(target=threadDraw, args=(z,l,Division/2)))
    starttime = time.time()
    for x in threads:    
        x.start()
    for x in threads:
        x.join()

    print('Time taken = {} seconds'.format(time.time() - starttime))
    drawImage()
    im = im.convert('RGB')
    im.show()
    

1 个答案:

答案 0 :(得分:0)

这里的重要区别在于进程和线程之间。两者都不是直接适合的,但差异具有关键意义。

python 中的线程有一个主要限制,即 GIL。库文档会告诉你它是否发布了 GIL。如果是这样,您可以使用线程;如果没有(或不说),线程将无效(比单线程慢)。根据您的评论,该库似乎没有。

进程是隔离的;没有全局变量。您必须自己将切片传回主进程,可能使用队列或磁盘上的文件,然后自己将它们拼接在一起。