KMEANS压缩图片代码演示
时间: 2023-09-21 08:12:54 浏览: 52
抱歉,我无法进行代码演示,但我可以提供 KMEANS 压缩图片的大致步骤:
1. 读取图片并将其转换为 RGB 矩阵。
2. 初始化 K 个聚类中心,可以随机选择 K 个像素点作为聚类中心。
3. 对于每个像素点,计算其与 K 个聚类中心的距离,将其归入距离最近的聚类中心所属的簇。
4. 对于每个簇,重新计算其聚类中心。
5. 重复步骤 3 和 4 直到聚类中心不再发生变化或者达到预设的迭代次数。
6. 将每个像素点替换为其所属簇的聚类中心的颜色值,生成压缩后的图片。
需要注意的是,KMEANS 压缩图片的效果取决于聚类中心的选择,不同的初始化方法会导致不同的结果。
相关问题
Kmeans方法压缩图片的代码演示
好的,这里是Kmeans方法压缩图片的代码演示。首先,我们需要导入一些必要的库,包括numpy、matplotlib和sklearn。然后,我们读入一张图片,将其转化为二维数组,然后将其展平为一维数组。
```
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.utils import shuffle
from PIL import Image
# 读取图片
img = Image.open('test.jpg')
# 将图片转化为二维数组
img_array = np.array(img)
# 将二维数组展平为一维数组
rows, cols, dim = tuple(img_array.shape)
image_array = np.reshape(img_array, (rows * cols, dim))
# 将数据归一化
image_array = image_array / 255.0
```
接下来,我们需要使用Kmeans算法对这些数据进行聚类。在这里,我们选择将图片压缩为16种颜色。我们使用sklearn库中的KMeans函数完成聚类,并将聚类结果存储在labels数组中。
```
# 使用KMeans聚类算法
n_colors = 16
kmeans = KMeans(n_clusters=n_colors, random_state=0).fit(image_array)
labels = kmeans.predict(image_array)
```
接下来,我们需要重新构建图片,将每个像素的颜色替换为其所在聚类的中心颜色。最后,我们将压缩后的图片展示出来。
```
# 重新构建图片
d = kmeans.cluster_centers_[labels]
compressed_image = np.reshape(d, (rows, cols, dim))
# 展示图片
fig, axes = plt.subplots(1, 2, figsize=(12, 6))
ax = axes.ravel()
ax[0].imshow(img)
ax[0].set_title("Original Image")
ax[1].imshow(compressed_image)
ax[1].set_title(f"Compressed Image, {n_colors} colors")
plt.tight_layout()
plt.show()
```
这样,我们就完成了Kmeans方法压缩图片的代码演示。完整代码如下:
```
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.utils import shuffle
from PIL import Image
# 读取图片
img = Image.open('test.jpg')
# 将图片转化为二维数组
img_array = np.array(img)
# 将二维数组展平为一维数组
rows, cols, dim = tuple(img_array.shape)
image_array = np.reshape(img_array, (rows * cols, dim))
# 将数据归一化
image_array = image_array / 255.0
# 使用KMeans聚类算法
n_colors = 16
kmeans = KMeans(n_clusters=n_colors, random_state=0).fit(image_array)
labels = kmeans.predict(image_array)
# 重新构建图片
d = kmeans.cluster_centers_[labels]
compressed_image = np.reshape(d, (rows, cols, dim))
# 展示图片
fig, axes = plt.subplots(1, 2, figsize=(12, 6))
ax = axes.ravel()
ax[0].imshow(img)
ax[0].set_title("Original Image")
ax[1].imshow(compressed_image)
ax[1].set_title(f"Compressed Image, {n_colors} colors")
plt.tight_layout()
plt.show()
```
c++ Kmeans图像压缩代码
以下是使用 OpenCV 库实现 Kmeans 图像压缩的示例代码:
```c++
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main()
{
// 读取原始图像
Mat img = imread("lena.jpg");
// 将图像转为一维数组
Mat samples = img.reshape(1, img.cols * img.rows);
// 设置 Kmeans 参数
int K = 16; // 分为 16 类
TermCriteria criteria(TermCriteria::EPS + TermCriteria::MAX_ITER, 10, 1.0);
int attempts = 3;
int flags = KMEANS_PP_CENTERS;
// 运行 Kmeans 算法
Mat labels, centers;
kmeans(samples, K, labels, criteria, attempts, flags, centers);
// 将每个像素点的值替换为其所属质心值
Mat new_img(img.size(), img.type());
for (int i = 0; i < img.rows; i++) {
for (int j = 0; j < img.cols; j++) {
int idx = labels.at<int>(i * img.cols + j);
new_img.at<Vec3b>(i, j) = centers.at<Vec3f>(idx);
}
}
// 显示压缩后的图像
imshow("compressed image", new_img);
waitKey(0);
return 0;
}
```
需要注意的是,Kmeans 是一种随机算法,每次运行的结果可能不同。因此,为了得到更好的压缩效果,可以多次运行 Kmeans 算法,选择最优的结果。