Python - 图像颜色外推 - KMeans 错误

问题描述 投票:0回答:1

我找到了这个教程,介绍如何编写一个 python 脚本,该脚本使用 OpenCV 和 Kmeans 从图像中推断出顶部颜色,并使用 Matplot 将它们绘制在饼图中。

代码如下:

from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
import numpy as np
import cv2
from collections import Counter
from skimage.color import rgb2lab, deltaE_cie76
import os

# Define a function that will convert the colours in HEX
def RGB2HEX(color):
    return "#{:02x}{:02x}{:02x}".format(int(color[0]), int(color[1]), int(color[2]))

# Define an image path in order to read it from OpenCV and convert in RGB
def get_image(image_path):
    image = cv2.imread(image_path)
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    return image

# Define a method for extracting the top colors from an image and plot them through Matplot
def get_colors(image, number_of_colors, show_chart):
    
    # Resize the image (not required) then reshape the input images in a two dimensional array
    modified_image = cv2.resize(image, (600, 400), interpolation = cv2.INTER_AREA)
    modified_image = modified_image.reshape(modified_image.shape[0]*modified_image.shape[1], 3)
    
    # Use the KMeans algorithm that creates clusters of colors through a fit and predict funciont in order to extract and map into lables variables
    clf = KMeans(n_clusters = number_of_colors)
    labels = clf.fit_predict(modified_image)
    
    counts = Counter(labels)
    counts = dict(sorted(counts.items()))
    
    center_colors = clf.cluster_centers_
    # Order the colors by iterating through the keys
    ordered_colors = [center_colors[i] for i in counts.keys()]
    hex_colors = [RGB2HEX(ordered_colors[i]) for i in counts.keys()]
    rgb_colors = [ordered_colors[i] for i in counts.keys()]

    plt.figure(figsize = (8, 6))
    plt.pie(counts.values(), labels = hex_colors, colors = hex_colors)
    
    # Retunr the RGB colors extracted
    return rgb_colors

# Call the method and pass the image path
get_colors(get_image('.\sample.jpg'), 8, True)

问题是,当我运行脚本并在输入中获取示例图像时,会出现以下警告:

PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\sklearn\cluster\_kmeans.py:870: FutureWarning: The default value of `n_init` will change from 10 to 'auto' in 1.4. Set the value of `n_init` explicitly to suppress the warning
  warnings.warn(

虽然通常我希望警告不应阻止脚本执行,但 matplot 已启动,但随后它立即崩溃,根本没有绘制任何内容。

有什么建议吗?

谢谢!

尝试在互联网上搜索,但没有结果。

python opencv k-means
1个回答
0
投票

该问题可能与警告消息无关。
我们应该简单地在 plt.pie(...) 之后调用

plt.show()
来显示图形。


用于测试的示例图像jp.png


更新的代码示例:

from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
import numpy as np
import cv2
from collections import Counter
from skimage.color import rgb2lab, deltaE_cie76
import os

# Define a function that will convert the colours in HEX
def RGB2HEX(color):
    return "#{:02x}{:02x}{:02x}".format(int(color[0]), int(color[1]), int(color[2]))

# Define an image path in order to read it from OpenCV and convert in RGB
def get_image(image_path):
    image = cv2.imread(image_path)
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    return image

# Define a method for extracting the top colors from an image and plot them through Matplot
def get_colors(image, number_of_colors, show_chart):
    
    # Resize the image (not required) then reshape the input images in a two dimensional array
    modified_image = cv2.resize(image, (600, 400), interpolation = cv2.INTER_AREA)
    modified_image = modified_image.reshape(modified_image.shape[0]*modified_image.shape[1], 3)
    
    # Use the KMeans algorithm that creates clusters of colors through a fit and predict funciont in order to extract and map into lables variables
    clf = KMeans(n_clusters = number_of_colors)
    labels = clf.fit_predict(modified_image)
    
    counts = Counter(labels)
    counts = dict(sorted(counts.items()))
    
    center_colors = clf.cluster_centers_
    # Order the colors by iterating through the keys
    ordered_colors = [center_colors[i] for i in counts.keys()]
    hex_colors = [RGB2HEX(ordered_colors[i]) for i in counts.keys()]
    rgb_colors = [ordered_colors[i] for i in counts.keys()]

    plt.figure(figsize = (8, 6))
    plt.pie(counts.values(), labels = hex_colors, colors = hex_colors)
    plt.show()
    
    # Retunr the RGB colors extracted
    return rgb_colors

# Call the method and pass the image path
#get_colors(get_image('.\sample.jpg'), 8, True)
get_colors(get_image('.\jp.png'), 8, True)  # https://pyimagesearch.com/2014/05/26/opencv-python-k-means-color-clustering/

输出图:

© www.soinside.com 2019 - 2024. All rights reserved.