opencv Python -图像颜色外推-K均值错误

c8ib6hqw  于 2023-06-06  发布在  Python
关注(0)|答案(1)|浏览(321)

我找到了这个教程,它讲述了如何编写一个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启动后立即崩溃,根本没有绘制任何内容。
有什么建议吗?
谢谢!
我试着在互联网上搜索,但没有任何结果。

bfrts1fy

bfrts1fy1#

此问题可能与警告消息无关。
我们应该在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/

输出数字:

相关问题