首页 > 解决方案 > 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')

标签: pythonnumpyk-means

解决方案


当您初始化“最终”数组时,您将 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])


推荐阅读