K-Means聚类图像

使用K-Means聚类图像像素颜色

import cv2
import numpy as np
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt

def kmeans_image_clustering(image_path, num_clusters=8):
    # 读取图像
    img = cv2.imread(image_path)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

    # Reshape图像为一维数组
    pixels = img.reshape((-1, 3))

    # 使用K-Means聚类
    kmeans = KMeans(n_clusters=num_clusters)
    kmeans.fit(pixels)

    # 获取聚类中心
    centers = np.array(kmeans.cluster_centers_, dtype=np.uint8)

    # 将每个像素分配到最近的聚类中心
    segmented_img = centers[kmeans.labels_].reshape(img.shape)

    # 显示原始图像和聚类结果
    plt.subplot(1, 2, 1)
    plt.imshow(img)
    plt.title('Original Image')

    plt.subplot(1, 2, 2)
    plt.imshow(segmented_img)
    plt.title('Segmented Image')

    plt.show()

# 使用示例
kmeans_image_clustering('path_to_your_image.jpg', num_clusters=4)

基于图像颜色直方图的K-Means聚类:

import cv2
import numpy as np
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt

def color_histogram_kmeans(image_path, num_clusters=8):
    # 读取图像
    img = cv2.imread(image_path)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

    # 计算颜色直方图
    hist = cv2.calcHist([img], [0, 1, 2], None, [8, 8, 8], [0, 256, 0, 256, 0, 256])

    # 将直方图归一化
    hist = hist / hist.sum()

    # 使用K-Means聚类
    kmeans = KMeans(n_clusters=num_clusters)
    kmeans.fit(hist.reshape(-1, 1))

    # 获取聚类中心
    centers = np.array(kmeans.cluster_centers_, dtype=np.uint8)

    # 将每个像素分配到最近的聚类中心
    labels = kmeans.predict(hist.reshape(-1, 1))
    segmented_img = centers[labels].reshape(img.shape)

    # 显示原始图像和聚类结果
    plt.subplot(1, 2, 1)
    plt.imshow(img)
    plt.title('Original Image')

    plt.subplot(1, 2, 2)
    plt.imshow(segmented_img)
    plt.title('Segmented Image')

    plt.show()

# 使用示例
color_histogram_kmeans('path_to_your_image.jpg', num_clusters=4)

你可能感兴趣的:(kmeans,聚类,算法)