如何删除边框和一些白色像素?

时间:2015-08-10 17:17:44

标签: python python-imaging-library pillow

我有下一个生成图像的代码:

...
fig = plt.figure(figsize=size,dpi=dpi)
ax = fig.add_axes([0, 0, 1, 1])

# remove top and right spines
ax.spines['right'].set_color('none')
ax.spines['left'].set_color('none')
ax.spines['top'].set_color('none')
ax.spines['bottom'].set_color('none')
# turn off ticks
ax.xaxis.set_ticks_position('none')
ax.yaxis.set_ticks_position('none')
ax.xaxis.set_ticklabels([])
ax.yaxis.set_ticklabels([])

plt.imshow(bt, cmap='g_cm')
plt.set_cmap('g_cm') # Grayscale
plt.savefig(outfilename) 

在此之后,我使用下一个代码来设置透明背景(白色 - 255,255,255)。

...
img = Image.open(filename) 
img = img.convert("RGBA")
pixdata = img.load()
if pixdata[x,y] == (255,255,255,255):
        pixdata[x,y] = (255,255,255,0)

我可以将透明度应用于背景,但图像的几个区域保持边框((灰暗))和一些边框外的像素是白色的。

如何删除这些边框和白色像素?

谢谢

2 个答案:

答案 0 :(得分:0)

如果你想说的是一些几乎没有白色但不太完美的像素没有被替换,你可能想要制作大多数白色透明的东西,而不仅仅是纯白色像素。

请尝试以下操作:

img = Image.open(filename) 
img = img.convert("RGBA")
pixdata = img.load()
if sum(pixdata[x, y][:3]) > 240 * 3:
        pixdata[x, y] = (255, 255, 255, 0)

答案 1 :(得分:0)

要删除具有特定阈值的白色像素,您可以使用库ImageChops

<强>代码

'''
Created on Aug 12, 2015

@author: physicalattraction
'''

from PIL import Image, ImageChops, ImageDraw

def create_image():
    # Image initialization
    W, H = 800, 600
    img = Image.new('RGBA', (W, H), (255, 255, 255))
    draw = ImageDraw.Draw(img)

    # Create rugged edge that should become transparent 
    r = 25
    draw.rectangle([r, r, W - r, H - r], fill=(254, 254, 254), outline=None)

    # Create image that should not become transparent
    r = 100
    draw.rectangle([r, r, W - r, H - r], fill=(255, 0, 0), outline=None)

    img.save('img/bg_removal_original.png')

    return img

def remove_white_background_naive(img):
    W, H = img.size
    for x in range(W):
        for y in range(H):
            if img.getpixel((x, y)) == (255, 255, 255, 255):
                # Make transparent.
                # Now making grey to easier show on screen that it works.
                img.putpixel((x, y), (128, 128, 128))  


    img.save('img/bg_removal_naive.png')

def remove_white_background_with_chops(img):
    fuzz = 2.5  # Choose a value greater than 0. Play around for optimal results.
    bg = Image.new(img.mode, img.size, img.getpixel((0, 0)))
    diff = ImageChops.difference(img, bg)
    diff = ImageChops.add(diff, diff, fuzz, -100)

    W, H = img.size
    for x in range(W):
        for y in range(H):
            if diff.getpixel((x, y)) == (0, 0, 0, 0):
                # Make transparent.
                # Now making grey to easier show on screen that it works.
                img.putpixel((x, y), (128, 128, 128))

    img.save('img/bg_removal_with_chops.png')

if __name__ == '__main__':
    img = create_image()
    remove_white_background_naive(img)
    remove_white_background_with_chops(img)

<强>结果

原件: Original

朴素: Naive

使用ImageChops: With ImageChops