Changing pixel color Python

先附上效率較差的解法:
https://stackoverflow.com/questions/13167269/changing-pixel-color-python

from PIL import Image
picture = Image.open("/path/to/my/picture.jpg")

# Get the size of the image
width, height = picture.size()

# Process every pixel
for x in width:
   for y in height:
       current_color = picture.getpixel( (x,y) )
       picture.putpixel( (x,y), new_color)

效率較差原因在loop 裡一一使用 getpixel() 進行讀取與寫入,如果資料量小,沒什麼差別,反之資料量大,就有明顯的效能問題。


較佳解法:

import numpy as np
from PIL import Image

def changeColor(im, original_value, target_value):
    data = np.array(im)

    r1, g1, b1 = original_value
    r2, g2, b2 = target_value

    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)

使用批次處理,效果就會好很多,完整的程式碼可以在這裡取得:
https://github.com/max32002/MaxFontScripts/blob/master/change_color.py


相關文章

取代圖片中顏色
https://codereview.max-everyday.com/change-color-in-image/

相關文章

寫留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *