【问题标题】:Remove background colour from image using Python/PIL使用 Python/PIL 从图像中删除背景颜色
【发布时间】:2014-02-08 15:24:26
【问题描述】:

我一直在努力解决这个问题,但确实遇到了麻烦,因此非常感谢您的帮助。

使用下面的代码,我想将具有指定 RGB 值的特征更改为白色,并将图像中的所有其他特征更改为黑色(即基本上从图像中提取特征。不幸的是,虽然我可以制作我的特征想要“提取”很好,当我尝试删除背景颜色时(我一直在尝试使用

mask2 = ((red != r1) & (green != g1) & (blue != b1))
data[:,:,:4][mask2] = [rb, gb, bb, ab]

但这似乎选择了除了红色 == r1 或绿色 == g1 等的像素之外的任何像素,给我留下了一个非常“嘈杂”的背景图像。)有谁知道用指定的 RGB 值,还是重新着色背景像素的更好方法?

谢谢

import numpy as np
from PIL import Image

im = Image.open('/home/me/nh09sw.tif')
im = im.convert('RGBA')
data = np.array(im)

r1, g1, b1 = 246, 213, 139 # Original value
rw, gw, bw, aw = 255, 255, 255, 255 # Value that we want to replace features with
rb, gb, bb, ab = 0, 0, 0, 255 #value we want to use as background colour

red, green, blue, alpha = data[:,:,0], data[:,:,1], data[:,:,2], data[:,:,3]

mask = ((red == r1) & (green == g1) & (blue == b1))
data[:,:,:4][mask] = [rw, gw, bw, aw]

im = Image.fromarray(data)

im.save('/home/me/nh09sw_recol.tif')

【问题讨论】:

    标签: python image python-2.7 python-imaging-library


    【解决方案1】:

    使用 np.all() 沿第三个轴进行比较。

    import numpy as np
    from PIL import Image
    
    im = Image.open('my_file.tif')
    im = im.convert('RGBA')
    data = np.array(im)
    # just use the rgb values for comparison
    rgb = data[:,:,:3]
    color = [246, 213, 139]   # Original value
    black = [0,0,0, 255]
    white = [255,255,255,255]
    mask = np.all(rgb == color, axis = -1)
    # change all pixels that match color to white
    data[mask] = white
    
    # change all pixels that don't match color to black
    ##data[np.logical_not(mask)] = black
    new_im = Image.fromarray(data)
    new_im.save('new_file.tif')
    

    【讨论】:

    猜你喜欢
    • 2020-06-03
    • 1970-01-01
    • 1970-01-01
    • 2021-06-05
    • 2020-12-05
    • 1970-01-01
    • 2021-12-19
    • 1970-01-01
    • 2019-02-08
    相关资源
    最近更新 更多