使用其他颜色更改所有像素的颜色 [英] Change the color of all pixels with another color

查看:266
本文介绍了使用其他颜色更改所有像素的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用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 尝试做如下操作:

import numpy as np
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')

但它应该是相当大(〜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.

这篇关于使用其他颜色更改所有像素的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆