用另一种颜色更改所有像素的颜色

时间:2011-06-26 10:56:12

标签: python image-processing colors imagemagick python-imaging-library

我想用Python改变一种颜色。

如果存在PIL的快速解决方案,我更倾向于这个解决方案。

目前,我使用

convert -background black -opaque '#939393' MyImage.png MyImage.png

4 个答案:

答案 0 :(得分:18)

如果您的计算机上有numpy,请尝试执行以下操作:

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倍,但对于更大的图像更多)更快。

另请注意,如果您只有RGB(而非RGBA)图像,上面的代码会比它需要的稍微复杂一些。但是,这个例子将单独保留alpha波段,而更简单的版本则不会。

答案 1 :(得分:4)

我刚刚想出了这个解决方案:

import Image
im = Image.open("MyImage.png")
width, height = im.size
colortuples = im.getcolors()
mycolor1 = min(colortuples)[1]
mycolor2 = max(colortuples)[1]
pix = im.load()
for x in range(0, width):
    for y in range(0, height):
        if pix[x,y] == mycolor1:
            im.putpixel((x, y), mycolor2)
im.save('MyImage.png')

尽管putpixel并不快,但对我来说似乎足够快。

答案 2 :(得分:3)

这是Joe Kington上面回答的修改。如果您的图像也包含Alpha通道,则以下是如何执行此操作。

import numpy as np
import Image

im = Image.open('fig1.png')
im = im.convert('RGBA')
data = np.array(im)

r1, g1, b1 = 0, 0, 0 # Original value
r2, g2, b2, a2 = 255, 255, 255, 255 # Value that we want to replace it with

red, green, blue, alpha = data[:,:,0], data[:,:,1], data[:,:,2], data[:,:,3]
mask = (red == r1) & (green == g1) & (blue == b1)
data[:,:,:4][mask] = [r2, g2, b2, a2]

im = Image.fromarray(data)
im.save('fig1_modified.png')

我花了很长时间才弄清楚如何让它发挥作用。我希望它可以帮助别人。

答案 3 :(得分:0)

此解决方案使用glob编辑文件夹中的所有png,删除颜色并将其与另一个交换,但使用RGBA。

import glob
from PIL import Image

old_color = 255, 0, 255, 255
new_color = 0, 0, 0, 0

for path in glob.glob("*.png"):
    if "__out" in path:
        print "skipping on", path
        continue

    print "working on", path

    im = Image.open(path)
    im = im.convert("RGBA")
    width, height = im.size
    colortuples = im.getcolors()

    pix = im.load()
    for x in xrange(0, width):
        for y in xrange(0, height):
            if pix[x,y] == old_color:
                im.putpixel((x, y), new_color)

    im.save(path+"__out.png")

它是https://stackoverflow.com/a/6483549/541208

的修改
相关问题