我正在使用
Python Imaging Library通过查找表来定义颜色关系来对黑白图像进行着色。查找表只是一个256元素的RGB元组列表:
>>> len(colors)
256
>>> colors[0]
(255, 237, 237)
>>> colors[127]
(50, 196, 33)
>>>
我的第一个版本使用了getpixel()和putpixel()方法:
for x in range(w):
for y in range(h):
pix = img.getpixel((x,y))
img.putpixel((x,y), colors[pix[0]])
这太可怕了一个配置文件报告指出了putpixel和getpixel方法作为罪魁祸首。有一点调查(即阅读文档),我发现“注意这种方法比较慢”。 re:putpixel。 (实际运行时间:putpixel为53s,1024×1024图像为50像素)
根据文档中的建议,我使用im.load()和直接像素访问:
pixels = img.load()
for x in range(w):
for y in range(h):
pix = pixels[x, y]
pixels[x, y] = colors[pix[0]]
处理速度提高了一个数量级,但仍然很慢:处理1024×1024图像的大约3.5秒。
对PIL文档的更全面的研究似乎表明Image.point()正是为了这个目的:
im.point(table) => image
im.point(function) => image
Returns a copy of the image where each pixel has been mapped through the given table. The table should contains 256 values per band in the image. If a function is used instead, it should take a single argument. The function is called once for each possible pixel value, and the resulting table is applied to all bands of the image.
我花了一些时间在界面上闯入,但是看起来不太合适。原谅我的无知,但PIL的文档是curt,我没有太多的图像处理经验。我已经google了一些,并提出了几个例子,但没有任何使用“点击”为我。所以,最后我的问题:
> Image.point()是这个工作的正确工具吗?
> Image.point()期望什么格式/结构表?
有人可以粗略地列举一个例子吗?到目前为止,我尝试过的每一次迭代都是直线黑色的形象。