【问题标题】:Color map not changing with imshow()颜色图不随 imshow() 改变
【发布时间】:2021-06-20 00:10:44
【问题描述】:

我正在将 KMeans 应用于图像,但是当我尝试使用 cmap 更改颜色时,它什么也没做。我该怎么办?

im = io.imread("image.jpg") / 255
x, y, z = im.shape
im_2D = im.reshape(x*y, z)
kmeans = KMeans(n_clusters=3, random_state=0)
kmeans.fit(im_2D)
im_clustered = kmeans.cluster_centers_[kmeans.labels_].reshape(x, y, z)

fig, ax = plt.subplots(1, 2)
ax[0].imshow(im)
ax[0].set_title("Original")
ax[1].imshow(im_clustered, cmap="jet")
ax[1].set_title("Segmented using k=3")
plt.show()

编辑:

这是使用上面代码的输出:

如果使用jet cmap,这就是我想要的输出:

【问题讨论】:

  • @DavidG 我不确定你的意思。我尝试了其他的,但那些也没有改变任何东西。
  • 我没有发现两者有任何区别(有或没有cmap)。你能告诉我们预期的输出吗?
  • @MaheryRanaivoson 我已经添加了当前输出和预期输出
  • @JohanC 是的,这行得通。

标签: python python-3.x matplotlib scikit-image


【解决方案1】:

您可以使用ax[1].imshow(kmeans.labels_.reshape(x, y), cmap='jet')。 当前的 im_clustered 包含 rgb 值。要应用颜色图,您需要标量值。

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
from sklearn.cluster import KMeans

with cbook.get_sample_data('ada.png') as image_file:
    im = plt.imread(image_file)
x, y, z = im.shape
im_2D = im.reshape(x * y, z)
kmeans = KMeans(n_clusters=3, random_state=0)
kmeans.fit(im_2D)
kmeans.cluster_centers_ = np.clip(kmeans.cluster_centers_, 0, 1)
im_clustered = kmeans.cluster_centers_[kmeans.labels_].reshape(x, y, z)

fig, ax = plt.subplots(1, 3, figsize=(10, 4))
for ax_i in ax:
    ax_i.axis('off')ax[0].imshow(im)
ax[0].set_title("Original")
ax[1].imshow(im_clustered, cmap="jet")
ax[1].set_title("Segmented using k=3")
ax[2].imshow(kmeans.labels_.reshape(x, y), cmap="jet")
ax[2].set_title("Segmented, k=3, jet cmap")
plt.show()

【讨论】:

    猜你喜欢
    • 2016-08-05
    • 2018-06-23
    • 1970-01-01
    • 2016-07-27
    • 1970-01-01
    • 2019-07-08
    • 1970-01-01
    • 2021-04-21
    • 1970-01-01
    相关资源
    最近更新 更多