详解Python PIL getpalette()方法

  • Post category:Python

Python PIL getpalette()方法详解

PIL(getpalette)方法返回模式“P”(调色板模式)的图像调色板中的颜色值序列。 返回的序列可以传递给putpalette()方法,以更改调色板。

语法

以下是getpalette()方法的语法:

Image.getpalette()

返回值

该方法返回大小为768的整数元组(r,g,b)元组,其中r,g,b为调色板的颜色值。

其中,元组中的前256个元素是红色的色度值,接下来的256个元素是绿色的色度值,最后的256个元素是蓝色的色度值。 因此,如果您想将第n种颜色设置为RGB(r,g,b)表示,则颜色值将存储在以下索引处:

index = n * 3
red = palette[index]
green = palette[index+1]
blue = palette[index+2]
RGB = (red,green,blue)

参数

该方法没有任何参数

示例

示例1

from PIL import Image
import numpy as np

# Open image using Image module
im = Image.open(r"C:\Users\System-Pc\Desktop\image.jpg")
im.show()

# Get the palette
palette = im.getpalette()

# Print the palette
print(palette)

示例2

我们首先创建一个P模式(调色板模式)的随机图像,然后我们将为每种颜色生成RGB颜色值,并将其放入调色板中。

from PIL import Image
import numpy as np

# Create a new image
im = Image.new("P", (300, 300))

# Generate random pixels
pixels = np.random.randint(0, 256, size=(300, 300)) % 8

# Create a color palette
palette = [(i, i, i) for i in range(256)]
palette += [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0), (255, 0, 255), (0, 255, 255),(255,255,255)]
print(palette)
palette = [item for color in palette for item in color]

# Assign the color palette to the image
im.putpalette(palette)

# Put the pixels
im.putdata(pixels.ravel())

# Show image
im.show()

# Get the palette
getpalette = im.getpalette()
print(getpalette)

以上就是getpalette()方法的详解,希望对你有所帮助。