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')
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')
如果您的计算机上有
numpy
可用,请尝试执行以下操作:它将使用多一点(3倍)的内存,但它应该相当快(约5倍,但更大的图像更多)更快。
还要注意,如果您只有RGB(而不是RGBA)图像,那么上面的代码比需要的稍微复杂一些。然而,这个例子将只剩下alpha波段,而更简单的版本则没有。
这是对以上乔·金顿回答的修改。以下是如果图像也包含alpha通道时如何执行此操作。
我花了很长时间才弄明白如何使它工作。我希望它能帮助别人。
我刚想出一个解决办法:
虽然putpixel速度不快,但对我来说似乎足够快了。
相关问题 更多 >
编程相关推荐