Python ValueError:形状不匹配

Python ValueError:形状不匹配,python,numpy,k-means,Python,Numpy,K Means,我正在尝试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

我正在尝试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)

在初始化“final”数组时,将png输出通道的数量硬编码为3,这可能与输入不同。更正以下行:

final=np.zero((像素质心形状[0],图像质心形状[2]))


comp\u image=final.reformate(img\u np.shape[0]、img\u np.shape[1]、img\u np.shape[2])

您好,请不要发布代码/错误的屏幕截图。我已经为您设置了错误格式,并删除了屏幕截图。
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')