Python - 将图像中的非黑色像素去除(转换为白色)

4

我有一个png文件,想要删除所有非黑色像素(将非黑色像素转换为白色)。如何在Python中轻松实现?谢谢!


3
http://en.wikipedia.org/wiki/Python_Imaging_Library - jeremy
2个回答

4
这是使用PIL的一种方法:

这里提供了使用 PIL 的一种方法:

from PIL import Image

# Separate RGB arrays
im = Image.open(file(filename, 'rb'))
R, G, B = im.convert('RGB').split()
r = R.load()
g = G.load()
b = B.load()
w, h = im.size

# Convert non-black pixels to white
for i in range(w):
    for j in range(h):
        if(r[i, j] != 0 or g[i, j] != 0 or b[i, j] != 0):
            r[i, j] = 255 # Just change R channel

# Merge just the R channel as all channels
im = Image.merge('RGB', (R, R, R))
im.save("black_and_white.png")

3
为什么不直接转换为L,对其进行阈值处理,使得所有>0的像素变为1,然后再转回来呢?这样更简单,而且可能会快上一个数量级,因为它是在C中执行了大型缓慢循环,而不是在Python中执行。 - abarnert
请问,如果想将黑色更改为透明或白色,需要进行哪些更改? - ganesh

2
我用Homebrew在我的Mac上实现了这个,但我不知道您使用的是哪个操作系统,因此我不能给您更具体的说明,但以下是您需要采取的一般步骤(如果您还没有完成):
1)安装libjpeg(如果您要处理.jpeg文件,则pil不包含此文件)
2)安装pil (http://www.pythonware.com/products/pil/ 或通过Homebrew或macports等方式(如果您使用的是Mac))
3)如有必要,请将pil与Python链接
4)使用此代码:
from PIL import Image

img = Image.open("/pathToImage") # get image
pixels = img.load() # create the pixel map

for i in range(img.size[0]): # for every pixel:
    for j in range(img.size[1]):
        if pixels[i,j] != (0,0,0): # if not black:
            pixels[i,j] = (255, 255, 255) # change to white

img.show()

如果你在某个地方卡住了,随时欢迎留言提问。


您正在将所有黑色像素转换为白色。他需要将所有非黑色像素转换为白色。 - Kiefer Aguilar
哦,糟糕,我可能读错了,我会尽快修复。 - Joohwan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接