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

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

    If numpy is available on your machine, try doing something like:

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

    It will use a bit (3x) more memory, but it should be considerably (~5x, but more for bigger images) faster.

    Also note that the code above is slightly more complicated than it needs to be if you only have RGB (and not RGBA) images. However, this example will leave the alpha band alone, whereas a simpler version wouldn't have.

提交回复
热议问题