PIL Best Way To Replace Color?

后端 未结 6 1952
时光取名叫无心
时光取名叫无心 2020-12-04 20:06

I am trying to remove a certain color from my image however it\'s not working as well as I\'d hoped. I tried to do the same thing as seen here Using PIL to make all white pi

6条回答
  •  清歌不尽
    2020-12-04 21:04

    This is part of my code, the result would like: source

    target

    import os
    import struct
    from PIL import Image
    def changePNGColor(sourceFile, fromRgb, toRgb, deltaRank = 10):
        fromRgb = fromRgb.replace('#', '')
        toRgb = toRgb.replace('#', '')
    
        fromColor = struct.unpack('BBB', bytes.fromhex(fromRgb))
        toColor = struct.unpack('BBB', bytes.fromhex(toRgb))
    
        img = Image.open(sourceFile)
        img = img.convert("RGBA")
        pixdata = img.load()
    
        for x in range(0, img.size[0]):
            for y in range(0, img.size[1]):
                rdelta = pixdata[x, y][0] - fromColor[0]
                gdelta = pixdata[x, y][0] - fromColor[0]
                bdelta = pixdata[x, y][0] - fromColor[0]
                if abs(rdelta) <= deltaRank and abs(gdelta) <= deltaRank and abs(bdelta) <= deltaRank:
                    pixdata[x, y] = (toColor[0] + rdelta, toColor[1] + gdelta, toColor[2] + bdelta, pixdata[x, y][3])
    
        img.save(os.path.dirname(sourceFile) + os.sep + "changeColor" + os.path.splitext(sourceFile)[1])
    
    if __name__ == '__main__':
        changePNGColor("./ok_1.png", "#000000", "#ff0000")
    

提交回复
热议问题