使用anoth更改所有像素的颜色

2024-05-16 03:04:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用Python换一种颜色。

如果存在使用PIL的快速解决方案,我更喜欢这个解决方案。

现在,我用

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

Tags: convertpilpng颜色解决方案blackbackgroundmyimage
3条回答

如果您的计算机上有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波段,而更简单的版本则没有。

这是对以上乔·金顿回答的修改。以下是如果图像也包含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')

我花了很长时间才弄明白如何使它工作。我希望它能帮助别人。

我刚想出一个解决办法:

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速度不快,但对我来说似乎足够快了。

相关问题 更多 >