跳轉到內容

Python 影像庫/編輯畫素

來自華夏公益教科書,開放的書籍,開放的世界

使用 PIL,您可以輕鬆地訪問和更改儲存在影像畫素中的資料。要獲取畫素圖,請呼叫load()在影像上。然後可以透過將畫素圖索引為陣列來檢索畫素資料。

pixelMap = img.load() #create the pixel map
pixel = pixelMap[0,0] #get the first pixel's value

當您更改畫素資料時,它會在其來源影像中被更改(因為畫素圖只是對資料的引用而不是副本)。

結果影像

以下程式碼片段演示瞭如何根據畫素的索引更改影像中的畫素值

from PIL import Image

# PIL accesses images in Cartesian co-ordinates, so it is Image[columns, rows]
img = Image.new( 'RGB', (250,250), "black") # create a new black image
pixels = img.load() # create the pixel map

for i in range(img.size[0]):    # for every col:
    for j in range(img.size[1]):    # For every row
        pixels[i,j] = (i, j, 100) # set the colour accordingly

img.show()
華夏公益教科書