Python Pillow - 顏色識別



在影像處理和分析的背景下,識別顏色是指識別、分類和提取不同影像上的顏色資訊的過程。它涉及分析畫素資料以確定影像中特定的顏色或顏色模式。

Python Pillow 庫為此目的提供了有價值的工具。本教程探討了兩個基本函式,即getcolors()getdata(),它們在有效分析影像中存在的顏色資訊方面起著至關重要的作用。

使用 getcolors() 函式識別顏色

getcolors() 函式返回影像中使用的顏色列表,顏色以影像的模式表示。例如,在 RGB 影像中,該函式返回一個包含紅色、綠色和藍色顏色值的元組。對於基於調色盤 (P) 的影像,它返回調色盤中顏色的索引。使用此函式的語法如下:

Image.getcolors(maxcolors=256)

其中,maxcolors 引數用於指定要檢索的最大顏色數。它返回一個未排序的元組列表,每個元組包含出現次數和相應的顏色畫素值。如果超過此 maxcolors 限制,則該方法返回 None(預設限制:256 種顏色)。

示例

此示例使用Image.getcolors() 函式識別影像中最常見的顏色。它從影像中提取前 10 種最常見的顏色,並建立一個調色盤來視覺化和顯示這些顏色及其各自的計數。

from PIL import Image, ImageDraw

# Open an image
input_image = Image.open('Images/colorful-shapes.jpg')

# Get the palette of the top 10 most common colors
palette = sorted(input_image.getcolors(maxcolors=100000), reverse=True)[:10]

cols = 2
rows = ((len(palette) - 1) // cols) + 1
cellHeight = 70
cellWidth = 200
imgHeight = cellHeight * rows
imgWidth = cellWidth * cols

result_image = Image.new("RGB", (imgWidth, imgHeight), (0, 0, 0))
draw = ImageDraw.Draw(result_image)

for idx, (count, color) in enumerate(palette):
   y0 = cellHeight * (idx // cols)
   y1 = y0 + cellHeight
   x0 = cellWidth * (idx % cols)
   x1 = x0 + (cellWidth // 4)
   
   draw.rectangle([x0, y0, x1, y1], fill=color, outline='black')
   draw.text((x1 + 1, y0 + 10), f"Count: {count}", fill='white')

# Display the input image
input_image.show('Input Image')

# Display the color chart
result_image.show('Output identified Colors')

輸入影像

colorful shapes

輸出識別的顏色

color chart
需要注意的是,當影像中的顏色數量大於 maxcolors 引數時,getcolors() 函式返回 None。它主要適用於“RGB”影像,這可能並非適用於所有用例。

對於需要更多靈活性或處理不同顏色模式的影像的情況,結合使用Image.getdata() 函式和其他 Python 庫可能更方便。

使用 getdata() 函式識別顏色

getdata() 函式是 Pillow Image 模組中的另一個函式,它允許使用者訪問影像的內容作為包含畫素值的序列物件。序列物件是扁平化的,這意味著每一行的值都直接跟在零行的值之後,依此類推。雖然此方法返回的序列物件是 Pillow 的內部資料型別,但它只能支援某些序列操作,例如 Python 列表,以便更方便地進行操作和列印。以下是函式的語法:

Image.getdata(band=None)

引數band 用於指定要返回的波段(預設值:所有波段)。要檢索單個波段,請提供索引值(例如,從“RGB”影像中獲取“R”波段,則提供 0)。該函式返回一個類似序列的物件,可以將其轉換為更熟悉的資料結構以進行進一步處理。

示例

這是一個示例,它使用 Image.getdata() 函式識別影像中的顏色並計算每種顏色的出現次數。

from PIL import Image
from collections import defaultdict

# Open an imagefrom PIL import Image
from collections import defaultdict

# Open an image
im = Image.open('Images/sea1.jpg')

# Create a defaultdict to store color counts
colors = defaultdict(int)

# Iterate through the image pixels and count each color
for pixel in im.getdata():
    colors[pixel] += 1

# Sort the colors by count in descending order
ordered_colors = sorted(colors.items(), key=lambda x: x[1], reverse=True)

# Print the top 10 colors and their counts
for color, count in ordered_colors[:10]:
    print(f"Color: {color}, Count: {count}")
from PIL import Image
from collections import defaultdict

# Open an image
im = Image.open('Images/sea1.jpg')

# Create a defaultdict to store color counts
colors = defaultdict(int)

# Iterate through the image pixels and count each color
for pixel in im.getdata():
    colors[pixel] += 1

# Sort the colors by count in descending order
ordered_colors = sorted(colors.items(), key=lambda x: x[1], reverse=True)
# Print the top 10 colors and their counts
for color, count in ordered_colors[:10]:
    print(f"Color: {color}, Count: {count}")

im = Image.open('Images/sea1.jpg')

# Create a defaultdict to store color counts
colors = defaultdict(int)

# Iterate through the image pixels and count each color
for pixel in im.getdata():
   colors[pixel] += 1

# Sort the colors by count in descending order
ordered_colors = sorted(colors.items(), key=lambda x: x[1], reverse=True)

# Print the top 10 colors and their counts
for color, count in ordered_colors[:10]:
   print(f"Color: {color}, Count: {count}")

輸出

Color: (255, 255, 255), Count: 82
Color: (0, 33, 68), Count: 73
Color: (0, 74, 139), Count: 71
Color: (0, 78, 144), Count: 69
Color: (0, 77, 143), Count: 62
Color: (0, 63, 107), Count: 59
Color: (0, 34, 72), Count: 56
Color: (0, 36, 72), Count: 52
Color: (0, 30, 58), Count: 51
Color: (1, 26, 56), Count: 51

示例

下面的示例使用 Image.getdata() 函式和 Python collections 庫來識別影像中最常見的顏色並計算該顏色的出現次數。

from PIL import Image
from collections import Counter

# Open an image
image = Image.open('Images/Road.jpg')

# Get a Counter dictionary of colors and their frequencies
colors = Counter(image.getdata())

# Get a set of unique colors
unique_colors = set(colors)

# Get the number of unique colors
num_unique_colors = len(unique_colors)

# Get the color with the highest frequency
most_frequent_color = max(colors, key=colors.get)

print(f"Unique Colors: {num_unique_colors}")
print(f"Most Frequent Color: {most_frequent_color} with a frequency of {colors[most_frequent_color]}")

輸出

Unique Colors: 18323
Most Frequent Color: (26, 27, 31) with a frequency of 5598
廣告