且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在图像文件中将特定的RGB颜色像素更改为另一种颜色

更新时间:2023-01-28 21:37:02

如果您的计算机上有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')

它将使用多一点(3倍)的内存,但是它应该快得多(〜5倍,但对于更大的图像,更多).

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.