PIL Best Way To Replace Color?

后端 未结 6 1945
时光取名叫无心
时光取名叫无心 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 20:50

    Using numpy and PIL:

    This loads the image into a numpy array of shape (W,H,3), where W is the width and H is the height. The third axis of the array represents the 3 color channels, R,G,B.

    import Image
    import numpy as np
    
    orig_color = (255,255,255)
    replacement_color = (0,0,0)
    img = Image.open(filename).convert('RGB')
    data = np.array(img)
    data[(data == orig_color).all(axis = -1)] = replacement_color
    img2 = Image.fromarray(data, mode='RGB')
    img2.show()
    

    Since orig_color is a tuple of length 3, and data has shape (W,H,3), NumPy broadcasts orig_color to an array of shape (W,H,3) to perform the comparison data == orig_color. The result in a boolean array of shape (W,H,3).

    (data == orig_color).all(axis = -1) is a boolean array of shape (W,H) which is True wherever the RGB color in data is original_color.

提交回复
热议问题