二分-k均值聚类算法进行图像分割完整代码
时间: 2023-07-08 19:13:19 浏览: 105
FCM-Kmeans.zip_K._图像处理kmeans_模糊C均值聚类_模糊k聚类_聚类
以下是使用Python实现二分-k均值聚类算法进行图像分割的完整代码:
``` python
import numpy as np
from PIL import Image
def load_image(filename):
img = Image.open(filename)
return np.array(img)
def save_image(filename, data):
img = Image.fromarray(np.uint8(data))
img.save(filename)
def kmeans(data, k, max_iter=100):
centers = np.random.randint(256, size=(k,))
for i in range(max_iter):
clusters = [[] for _ in range(k)]
for x in data:
distances = np.abs(centers - x)
idx = np.argmin(distances)
clusters[idx].append(x)
new_centers = [np.mean(cluster) for cluster in clusters]
if np.allclose(new_centers, centers):
break
centers = new_centers
return centers, clusters
def bisecting_kmeans(data, k, max_iter=100):
clusters = [data]
while len(clusters) < k:
max_sse = -1
for i, cluster in enumerate(clusters):
centers, subclusters = kmeans(cluster, 2, max_iter)
sse = 0
for subcluster in subclusters:
distances = np.abs(subcluster - centers[0])
sse += np.sum(distances ** 2)
if sse > max_sse:
max_sse = sse
max_idx = i
max_centers = centers
max_subclusters = subclusters
clusters.pop(max_idx)
clusters.extend(max_subclusters)
return clusters
if __name__ == '__main__':
img = load_image('input.jpg')
data = img.reshape(-1, 3)
clusters = bisecting_kmeans(data, 4)
for i, cluster in enumerate(clusters):
centers, _ = kmeans(cluster, 1)
distances = np.abs(cluster - centers[0])
mask = np.argmin(distances, axis=1) == 0
data[mask] = centers[0]
img = data.reshape(img.shape)
save_image('output.jpg', img)
```
该代码使用PIL库读取和保存图像,numpy库进行数组操作。首先,将输入图像转换成数据数组。然后使用二分-k均值聚类算法将数据分成四个簇。接下来,对于每个簇,使用k均值聚类算法将其压缩为一个点,并使用该点将簇中所有像素点赋值为该点的颜色。最后,将数据数组转换回图像并保存输出图像。
注意,这里默认输入图像为RGB格式,如果输入图像为其他格式,需要根据实际情况进行修改。
阅读全文