去除图片浅色背景(PIL实现)

基本思路:在二值化的基础上修改。首先灰度化,然后大于阈值的像素(浅色背景),设为255,小于阈值的像素,保留原样。阈值可以试出来,不同的图片,适合的阈值不一样。

源码:

from PIL import Image


def testImg(file,threshold):
    loadpath = "./image/"
    img = Image.open(loadpath+file)
    img.show()
    img = img.convert("L")
    img.show()
    img = binarizing(img, threshold)
    img.show()

def binarizing(img,threshold): #input: gray image
    pixdata = img.load()
    w, h = img.size
    for y in range(h):
        for x in range(w):
            if pixdata[x, y] < threshold:
                pass
            else:
                pixdata[x, y] = 255
    return img

if __name__ == "__main__":
    fileList = ["GettingStarted.png", "Balance.png"]
    for file in fileList:
        testImg(file, 175)

 

Before:


After: