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

huangapple go评论72阅读模式
英文:

Python - Image Colors Extrapolation - KMeans error

问题

我找到了关于如何编写一个使用OpenCV和Kmeans来从图像中外推顶部颜色并使用Matplot在饼图中绘制它们的Python脚本的教程。

以下是代码部分:

```python
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

# 定义一个将颜色转换为HEX格式的函数
def RGB2HEX(color):
    return "#{:02x}{:02x}{:02x}".format(int(color[0]), int(color[1]), int(color[2]))

# 定义一个函数以从OpenCV中读取图像并将其转换为RGB格式
def get_image(image_path):
    image = cv2.imread(image_path)
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    return image

# 定义一个方法来从图像中提取顶部颜色并通过Matplot绘制它们
def get_colors(image, number_of_colors, show_chart):
    
    # 调整图像大小(可选),然后将输入图像重新整形为二维数组
    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)
    
    # 使用KMeans算法通过拟合和预测函数创建颜色簇,以提取并映射到标签变量
    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_
    # 通过迭代键来排序颜色
    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)
    
    # 返回提取的RGB颜色
    return rgb_colors

# 调用该方法并传递图像路径
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会启动,但立即崩溃,而没有绘制任何内容。

有什么建议吗?

谢谢!

在互联网上搜索过,但没有找到解决方案。


<details>
<summary>英文:</summary>

i have found this tutorial on how to write a python script that uses OpenCV and Kmeans for extrapolating the top colors from an image and plot them in a pie chart using Matplot.

The code is the following:


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(color1), int(color2))

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)


The problem is that when i run the script, taking a sample image in input, the following warning occurs:


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(


While usually i expect that a warning should not block the script execution, matplot is launched but then it crashes immediately without plotting anything at all.

Any suggestions?

Thanks!



Tried to search on internet, but nothing came through.

</details>


# 答案1
**得分**: 0

以下是翻译好的部分:

问题可能与警告信息无关。
我们应该在`plt.pie(...)`后简单地调用[plt.show()][1]来显示图形。

---

用于测试的示例图像[jp.png][2]:
[![输入图像描述][3]][3]

---

更新后的代码示例:

&lt;!-- language: lang-python --&gt;

```python
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

# 定义一个将颜色转换为HEX格式的函数
def RGB2HEX(color):
    return "#{:02x}{:02x}{:02x}".format(int(color[0]), int(color[1]), int(color[2]))

# 定义一个函数以从OpenCV中读取并将图像转换为RGB
def get_image(image_path):
    image = cv2.imread(image_path)
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    return image

# 定义一个从图像中提取顶部颜色并通过Matplot绘制它们的方法
def get_colors(image, number_of_colors, show_chart):

    # 调整图像的大小(不是必需的),然后将输入图像重塑为二维数组
    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)

    # 使用KMeans算法通过fit和predict函数创建颜色集群,以提取并映射到标签变量
    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_
    # 通过迭代键来按顺序排列颜色
    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()

    # 返回提取的RGB颜色
    return rgb_colors

# 调用该方法并传递图像路径
#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/

输出图形:
Python – 图像颜色外推 – KMeans 错误

英文:

The issue is probably unrelated to the warning message.
We should simply call plt.show() after plt.pie(...) for displaying the figure.


Sample image for testing jp.png:
Python – 图像颜色外推 – KMeans 错误


Updated code sample:

<!-- language: lang-python -->

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 &quot;#{:02x}{:02x}{:02x}&quot;.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(&#39;.\sample.jpg&#39;), 8, True)
get_colors(get_image(&#39;.\jp.png&#39;), 8, True)  # https://pyimagesearch.com/2014/05/26/opencv-python-k-means-color-clustering/

Output figure:
Python – 图像颜色外推 – KMeans 错误

huangapple
  • 本文由 发表于 2023年6月5日 15:29:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76404302.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定