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)

  • 14
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值