问题描述
我想用 Python 更改单一颜色.
I would like to change a single color with Python.
如果存在使用 PIL 的快速解决方案,我更喜欢这个解决方案.
If a fast solution with PIL exists, I would prefer this solution.
目前,我使用
convert -background black -opaque '#939393' MyImage.png MyImage.png
推荐答案
如果 numpy
在您的机器上可用,请尝试执行以下操作:
If numpy
is available on your machine, try doing something like:
import numpy as np
from PIL import Image
im = Image.open('fig1.png')
data = np.array(im)
r1, g1, b1 = 0, 0, 0 # Original value
r2, g2, b2 = 255, 255, 255 # Value that we want to replace it with
red, green, blue = data[:,:,0], data[:,:,1], data[:,:,2]
mask = (red == r1) & (green == g1) & (blue == b1)
data[:,:,:3][mask] = [r2, g2, b2]
im = Image.fromarray(data)
im.save('fig1_modified.png')
它会使用多一点 (3x) 的内存,但它应该会更快(~5x,但对于更大的图像更多).
It will use a bit (3x) more memory, but it should be considerably (~5x, but more for bigger images) faster.
另请注意,如果您只有 RGB(而不是 RGBA)图像,则上面的代码比需要的代码稍微复杂一些.但是,此示例将单独保留 alpha 波段,而更简单的版本则不会.
Also note that the code above is slightly more complicated than it needs to be if you only have RGB (and not RGBA) images. However, this example will leave the alpha band alone, whereas a simpler version wouldn't have.
这篇关于在图像文件中将特定的 RGB 颜色像素更改为另一种颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!