import os
import numpy as np
from PIL import Image
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
os.environ['LOKY_MAX_CPU_COUNT'] = '4'
def loadData(filePath): # 加载图像并进行预处理,将像素值归一化到0-1之间。
try:
img = Image.open(filePath) # 打开图像文件
except FileNotFoundError:
raise FileNotFoundError(f"文件路径 {filePath} 不存在,请检查路径。")
img = img.convert('RGB') # 确保图像是RGB格式
data = []
m, n = img.size # 获取图像的尺寸
for i in range(m): # 将每个像素点的RGB颜色处理到0-1
for j in range(n):
x, y, z = img.getpixel((i, j))
data.append([x / 256.0, y / 256.0, z / 256.0]) # 范围内并存入data
return np.array(data), m, n # 以数组的形式返回data,以及图像尺寸
def createSegmentedImage(labels, centers, row, col): # 根据聚类结果创建分割后的图像。
segmented_img = Image.new('RGB', (row, col))
for i in range(row):
for j in range(col):
cluster_idx = labels[i * col + j]
color = tuple((centers[cluster_idx] * 256).astype(int))
segmented_img.putpixel((i, j), color)
return segmented_img
def segmentImage(filePath, n_clusters): # 利用K-means聚类算法对图像像素点颜色进行聚类,实现简单的图像分割。
imgData, row, col = loadData(filePath)
# 加载KMeans聚类算法
km = KMeans(n_clusters=n_clusters)
km.fit(imgData)
# 获取每个像素所属的类别
labels = km.labels_
centers = km.cluster_centers_
# 读取原始图像
original_img = Image.open(filePath)
# 创建分割后的图像
segmented_img = createSegmentedImage(labels, centers, row, col)
# 使用subplot同时显示原图和分割后的图像
plt.figure(figsize=(12, 6))
plt.subplot(1, 2, 1)
plt.imshow(original_img)
plt.title('Original Image')
plt.axis('off')
plt.subplot(1, 2, 2)
plt.imshow(segmented_img)
plt.title('Segmented Image')
plt.axis('off')
plt.show()
if __name__ == "__main__":
path = 'D:/Python/Pythonproject/Pythonproject1/K_means_10.jpg'
n_clusters = 3 # 设置聚类的数量
segmentImage(path, n_clusters)
整图分割~
最新推荐文章于 2025-04-09 10:30:59 发布