python 对图像进行聚类分析

复制代码
import cv2
import numpy as np
from sklearn.cluster import KMeans
import time

# 中文路径读取
def cv_imread(filePath, cv2_falg=cv2.COLOR_BGR2RGB):   
    cv_img = cv2.imdecode(np.fromfile(filePath, dtype=np.uint8), cv2_falg)    
    return cv_img

# 自定义装饰器计算时间
def compute_time(func):
    def compute(*args, **kwargs):
        st = time.time()
        result = func(*args, **kwargs)
        et = time.time()
        print('消费时间 %.6f s' % (et - st))
        return result

    return compute



@compute_time
def kmeans_img(image,  num_clusters, show=False):
    # 如果图像是灰度图(单通道),将其转换为三通道
    if len(image.shape) == 2:
        image = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB)
    
    # 将图像的形状进行调整以便进行 K 均值聚类,提高训练速度
    pixels = cv2.resize(image.copy(), None, fx=0.05, fy=0.05, interpolation=cv2.INTER_LINEAR)
    pixels = np.float32(pixels.reshape((-1, 3)))
    
    segmented_pixels = np.float32(image.reshape((-1, 3)))

    # 初始化 KMeans 模型并拟合数据
    kmeans = KMeans(n_clusters=num_clusters)
    kmeans.fit(pixels)

    # 获取每个像素所属的簇标签
    labels = kmeans.predict(segmented_pixels)

    # 根据簇标签,将图像像素值转换为簇中心值
    segmented_image = kmeans.cluster_centers_[labels]
    segmented_image = np.uint8(segmented_image.reshape(image.shape))
    
    if show:
        plt.figure(figsize=(10, 5))

        plt.subplot(1, 2, 1)
        plt.title('Original Image')
        plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
        plt.axis('off')

        plt.subplot(1, 2, 2)
        plt.title('Segmented Image')
        plt.imshow(segmented_image)
        plt.axis('off')

        plt.tight_layout()
        plt.show()
    
    return segmented_image

image_path =r"C:\Users\pc\Pictures\test\快.png"
image = cv_imread(image_path)
kmeans_img(image,4, show=True)

使用opencv内设的kmeans函数:直接原图进行训练,然后获取每个像素点的类,速度慢。上述方法对图像进行一个缩放后,训练模型,然后用模型再预测原图的每个像素点,速度快。

复制代码
def kmeans_img(image, num_clusters, show=True):
    # 如果图像是灰度图(单通道),将其转换为三通道
    if len(image.shape) == 2:
        image = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB)
    # image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    print(image.shape)
    # 将图像的形状进行调整以便进行 K 均值聚类
    pixels = image.reshape((-1, 3))
    pixels = np.float32(pixels)


    # 设定 kmeans 参数并运行算法
    criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 0.2)

    _, labels, centers = cv2.kmeans(pixels, num_clusters, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)

    # 将图像像素值转换为簇中心值
    centers = np.uint8(centers)
    segmented_image = centers[labels.flatten()]
    segmented_image = segmented_image.reshape(image.shape)
    
    if show:
        # 显示原始图像和分割后的图像
        plt.figure(figsize=(10, 5))

        plt.subplot(1, 2, 1)
        plt.title('Original Image')
        plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
        plt.axis('off')

        plt.subplot(1, 2, 2)
        plt.title('Segmented Image')
        plt.imshow(segmented_image)
        plt.axis('off')

        plt.tight_layout()
        plt.show()
    return segmented_image
相关推荐
jndingxin10 小时前
OpenCV CUDA模块设备层-----反向二值化阈值处理函数thresh_binary_inv_func()
人工智能·opencv·计算机视觉
jndingxin11 小时前
OpenCV CUDA模块设备层-----在 GPU 上执行类似于 std::copy 的操作函数warpCopy()
人工智能·opencv·计算机视觉
晓131311 小时前
OpenCV篇——项目(二)OCR文档扫描
人工智能·python·opencv·pycharm·ocr
jndingxin11 小时前
OpenCV CUDA模块设备层-----在GPU 上高效地执行两个 uint 类型值的最大值比较函数vmax2()
人工智能·opencv·计算机视觉
luofeiju18 小时前
RGB下的色彩变换:用线性代数解构色彩世界
图像处理·人工智能·opencv·线性代数
Echo``10 天前
12.OpenCV—基础入门
开发语言·c++·人工智能·qt·opencv·计算机视觉
jndingxin10 天前
OpenCV CUDA模块设备层-----线程块内初始化连续内存区域 的设备端工具函数blockYota()
人工智能·opencv·计算机视觉
AI technophile10 天前
OpenCV计算机视觉实战(12)——图像金字塔与特征缩放
人工智能·opencv·计算机视觉
无证驾驶梁嗖嗖11 天前
[特殊字符] OpenCV opencv_world 模块作用及编译实践完整指南
opencv
从零开始学习人工智能11 天前
相机标定与3D重建技术通俗讲解
opencv·算法