Change specific RGB color pixels to another color, in image file

后端 未结 4 1890
不思量自难忘°
不思量自难忘° 2020-12-06 10:53

I would like to change a single color with Python.

If a fast solution with PIL exists, I would prefer this solution.

At the moment, I use

c         


        
4条回答
  •  南方客
    南方客 (楼主)
    2020-12-06 11:47

    This solution uses glob to edit all pngs in a folder, removing a color and swapping it out with another, but uses RGBA.

    import glob
    from PIL import Image
    
    old_color = 255, 0, 255, 255
    new_color = 0, 0, 0, 0
    
    for path in glob.glob("*.png"):
        if "__out" in path:
            print "skipping on", path
            continue
    
        print "working on", path
    
        im = Image.open(path)
        im = im.convert("RGBA")
        width, height = im.size
        colortuples = im.getcolors()
    
        pix = im.load()
        for x in xrange(0, width):
            for y in xrange(0, height):
                if pix[x,y] == old_color:
                    im.putpixel((x, y), new_color)
    
        im.save(path+"__out.png")
    

    It's a modification of https://stackoverflow.com/a/6483549/541208

提交回复
热议问题