python - ValueError:形状不匹配
问题描述
我正在尝试 K-means 图像压缩,但出现此错误
File "C:/Users/[user]/PycharmProjects/project/CompressMe.py", Line23, in <module>
final[pixel_centroids == cluster_no] = cluster_centers[cluster_no]
ValueError: shape mismatch: value array of shape (4,) could not be broadcast to indexing result of shape (267049,3)
我的代码:
import numpy as np
from PIL import Image
from sklearn.cluster import KMeans
import matplotlib.pyplot as mpimg
import matplotlib.pyplot as plt
import os
img = Image.open('Capture.png')
img_np = np.asarray(img)
pixels = img_np.reshape(img_np.shape[0] * img_np.shape[1], img_np.shape[2])
model = KMeans(n_clusters = 32)
model.fit(pixels)
pixel_centroids = model.labels_
cluster_centers = model.cluster_centers_
final = np.zeros((pixel_centroids.shape[0], 3))
for cluster_no in range(32):
final[pixel_centroids == cluster_no] = cluster_centers[cluster_no]
comp_image = final.reshape(img_np.shape[0], img_np.shape[1], 3)
comp_image = Image.fromarray(np.uint8(comp_image))
comp_image.save('Capture_compressed.png')
img1 = mpimg.imread('Capture.png')
img2 = mpimg.imread('Capture_compressed.png')
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(20,20))
ax1.imshow(img1)
ax1.set_title('Original image')
ax2.imshow(img2)
ax2.set_title('Compressed image')
plt.show()
print('size of original image: ', int(os.stat('Capture.png').st_size / 1024), 'kB')
print('size of compressed image:', int(os.stat('Capture_compressed.png').st_size / 1024), 'kB')
解决方案
当您初始化“最终”数组时,您将 png 输出通道的数量硬编码为 3,这可能与输入不同。更正以下行:
final = np.zeros((pixel_centroids.shape[0], img_np.shape[2]))
和
comp_image = final.reshape(img_np.shape[0], img_np.shape[1], img_np.shape[2])
推荐阅读
- plugins - 来自相关实体的插件更新字段
- image - 如何使扭曲的纹理看起来更平滑?
- android - 从数据库加载数据时 RecyclerView 闪烁
- jboss - 应用程序在 eap 6.4 上停止工作,但启用/禁用数据源,重新加载然后工作
- java - java Spring使用classpath时在哪里设置application.yml的来源;当前使用子模块
- c# - 我正在尝试读取 txt 文件并读取第一列以获取第二列
- javascript - 如何区分查询并获取最后数据日期?(解析服务器)
- go - 在本地运行 Go Tour 时出错:找不到游览文件:找不到 go-tour 内容;检查 $GOROOT 和 $GOPATH
- go - 无法在 Go Chi 路由器中读取“request.Body”
- python - 如何通过不同的 dict 将 df 扩展为列?