颜色图不随 imshow() 改变
Color map not changing with imshow()
我正在将 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,这就是我希望的输出:
您可以使用 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()
我正在将 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,这就是我希望的输出:
您可以使用 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()