k-means实现图片压缩的代码
时间: 2023-10-26 22:08:37 浏览: 42
以下是用k-means算法实现图片压缩的Python代码:
```python
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from PIL import Image
# 加载图片
img = Image.open('test.jpg')
img_array = np.array(img)
# 获取图片的尺寸和像素值
height, width, depth = img_array.shape
pixels = img_array.reshape((height * width, depth))
# 设置聚类的数量
n_clusters = 16
# 进行k-means聚类
kmeans = KMeans(n_clusters=n_clusters, random_state=0).fit(pixels)
new_pixels = kmeans.cluster_centers_[kmeans.labels_]
# 将像素值转换回图片形式
new_img_array = new_pixels.reshape((height, width, depth))
new_img = Image.fromarray(np.uint8(new_img_array))
# 显示原图片和压缩后的图片
fig, ax = plt.subplots(1, 2, figsize=(8, 4))
ax[0].imshow(img)
ax[0].set_title('Original Image')
ax[1].imshow(new_img)
ax[1].set_title('Compressed Image ({0} colors)'.format(n_clusters))
plt.show()
```
在上面的代码中,首先我们加载了一张图片,然后将其转换为一个二维数组,其中每一行代表一像素的RGB值。接着,我们通过设定聚类数量,使用k-means算法对这些像素进行聚类,并将每个像素的RGB值替换为所属聚类的质心。最后,我们将新的像素值转换回图片形式,并显示原始图片和压缩后的图片。