如何获取作为函数调用结果绘制的图像并将其绘制到图像网格中?

How do I take an image that is plotted as a result of a function call and plot to a grid of images?

我有一个函数可以用来输出使用 KMeans 聚类像素的照片。我可以输入 k 值作为参数,它将拟合模型并输出新图像。

def cluster_image(k, img=img):
  img_flat = img.reshape(img.shape[0]*img.shape[1], 3)
  kmeans = KMeans(n_clusters = k, random_state = 42).fit(img_flat)
  new_img = img_flat.copy()
  
  for i in np.unique(kmeans.labels_):
    new_img[kmeans.labels_ == i, :] = kmeans.cluster_centers_[i]
  
  new_img = new_img.reshape(img.shape)

  return plt.imshow(new_img), plt.axis('off');

我想写一个循环来输出 k=2 到 k=10 的图像:

k_values = np.arange(2, 11)
for k in k_values:
  print('k = ' + str(k))
  cluster_image(k)
  show()

这 returns 一条竖线图像。我如何做这样的事情,但将每个图像输出到 3x3 图像网格?

如果允许你修改cluster_image的签名,我会这样做:

def cluster_image(k, ax, img=img):
    img_flat = img.reshape(img.shape[0]*img.shape[1], 3)
    kmeans = KMeans(n_clusters = k, random_state = 42).fit(img_flat)
    new_img = img_flat.copy()

    for i in np.unique(kmeans.labels_):
        new_img[kmeans.labels_ == i, :] = kmeans.cluster_centers_[i]

    new_img = new_img.reshape(img.shape)
    ax.imshow(new_img)
    ax.axis('off')

fig, axs = plt.subplots(3, 3)
axs = axs.flatten()
k_values = np.arange(2, 11)
for i, k in enumerate(k_values):
    print('k = ' + str(k))
    cluster_image(k, axs[i], img=img)