<p>我会这样做,从依赖关系开始:</p>
<pre><code>from multiprocessing import Pool
import numpy as np
from PIL import Image
# and some for testing
from random import random
from time import sleep
</code></pre>
<p>首先,我定义了一个将图像分成“块”的函数,就像您所说的那样:</p>
^{pr2}$
<p>它是一个懒惰的迭代器,所以这可以持续一段时间。在</p>
<p>然后定义我的worker函数:</p>
<pre><code>def dumb_func(cc):
(y0,y1), (x0,x1) = cc
# convert to floats for ease of processing
chunk = image[y0:y1,x0:x1] / 255.
# random slow down for testing
# sleep(random() ** 6)
res = chunk ** 2
# convert back to bytes for efficiency
return cc, (res * 255).astype(np.uint8)
</code></pre>
<p>为了提高效率,我确保源数组尽可能地接近原始格式,并以相同的格式发送回去(如果显然要处理其他像素格式,这可能需要一些修改)。在</p>
<p>然后我把它放在一起:</p>
<pre><code>if __name__ == '__main__':
source = Image.open('tmp.jpeg')
image = np.asarray(source)
print("loaded", image.shape, image.dtype)
with Pool() as pool:
resit = pool.imap_unordered(
dumb_func, chunkit(*image.shape[:2]))
output = np.empty_like(image)
for cc, res in resit:
(y0,y1), (x0,x1) = cc
output[y0:y1,x0:x1] = res
im = Image.fromarray(output, 'RGB')
im.save('out.jpeg')
</code></pre>
<p>这将在几秒钟内处理一个15像素的图像,其中大部分都花在加载/保存图像上。它可能在数组步进和缓存友好性方面更聪明,但希望能有所帮助!在</p>
<p>注意:我认为这段代码依赖于cpythonunix风格的进程分叉语义,以确保在进程之间有效地共享映像。不知道如果你把它放在别的东西上会发生什么</p>