[英]Using Pillow Image.tobytes to flip the image and swap the color channels
[英]Identify the color values of an image with a color palette using PIL/Pillow
我正在嘗試使用 PIL/枕頭識別圖像的已用調色板的顏色。 我嘗試了以下方法:
image[x,y]
:這只會給我相應像素的索引號(即1
)image.getpixel((x,y))
:同樣,這只會給我相應像素的索引號(即1
)image.getcolors()
:這會給我像素數和它們對應的索引號(即[(2, 1), (2, 0)]
)image.palette
:返回“PIL.ImagePalette.ImagePalette 對象”image.getpalette()
:返回一個大數組(對我來說似乎是)不相關的整數(即[0, 0, 255, 255, 0, 0, 2, 2, 2, 3, 3 ,3 ...]
)作為絕對后備,我可以轉換圖像模式,然后獲取顏色值,但如果可能的話,我寧願不這樣做。
使用此示例圖像(2x2 像素圖像,使用 GIMP 創建的 2 種顏色的索引模式,頂部兩個像素是紅色 (255,0,0),底部兩個像素是藍色 (0,0,255)),我期待以下內容:
image.getpalette()
1: (255,0,0)
0: (0,0,255)
編輯:我最接近的是:
image.palette.getdata()
:這給了我('RGB;L', b'\\x00\\x00\\xff\\xff\\x00\\x00')
。 有什么辦法可以將它映射到索引號。 我認為,這里每三個字節將映射到一個索引號。
您可以像這樣獲取和排列調色板:
import numpy as np
from PIL import Image
# Open image
im = Image.open('a.png')
# Get palette and reshape into 3 columns
palette = np.array(im.getpalette(),dtype=np.uint8).reshape((256,3))
然后只需打印palette
。
[[ 0 0 255] <--- first entry is blue
[255 0 0] <--- second is red
[ 2 2 2] <--- grey padding to end
[ 3 3 3]
[ 4 4 4]
[ 5 5 5]
[ 6 6 6]
...
...
[253 253 253]
[254 254 254]
[255 255 255]]
如果要計算顏色以及每種顏色的數量,請執行以下操作:
# Convert Image to RGB and make into Numpy array
na = np.array(im.convert('RGB'))
# Get used colours and counts of each
colours, counts = np.unique(na.reshape(-1,3), axis=0, return_counts=1)
這給出了colours
:
array([[ 0, 0, 255],
[255, 0, 0]], dtype=uint8)
並counts
:
array([2, 2])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.