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

后端 未结 4 1907
不思量自难忘°
不思量自难忘° 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:39

    This is a modification of Joe Kington's answer above. The following is how to do this if your image contains an alpha channel as well.

    import numpy as np
    import Image
    
    im = Image.open('fig1.png')
    im = im.convert('RGBA')
    data = np.array(im)
    
    r1, g1, b1 = 0, 0, 0 # Original value
    r2, g2, b2, a2 = 255, 255, 255, 255 # Value that we want to replace it with
    
    red, green, blue, alpha = data[:,:,0], data[:,:,1], data[:,:,2], data[:,:,3]
    mask = (red == r1) & (green == g1) & (blue == b1)
    data[:,:,:4][mask] = [r2, g2, b2, a2]
    
    im = Image.fromarray(data)
    im.save('fig1_modified.png')
    

    It took me a long time to figure out how to get it to work. I hope that it helps someone else.

提交回复
热议问题