如何获取作为函数调用结果绘制的图像并将其绘制到图像网格?
我有一个函数,用于输出使用 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()
这将返回图像的垂直线。我该如何做类似的事情,但将每个图像输出到 3x3 图像网格?
I have a function that I use to output a photo that has had its pixels clustered using KMeans. I can input the k value as an argument, and it will fit the model and output the new image.
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');
I want to write a loop to output the images for k=2 through k=10:
k_values = np.arange(2, 11)
for k in k_values:
print('k = ' + str(k))
cluster_image(k)
show()
This returns a vertical line of images. How do I do something like this, but output each image to a 3x3 grid of images?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果允许您修改
cluster_image
的签名,我会做:If you are allowed to modify the signature of
cluster_image
, I would do: