• python 对图像进行聚类分析


    1. import cv2
    2. import numpy as np
    3. from sklearn.cluster import KMeans
    4. import time
    5. # 中文路径读取
    6. def cv_imread(filePath, cv2_falg=cv2.COLOR_BGR2RGB):
    7. cv_img = cv2.imdecode(np.fromfile(filePath, dtype=np.uint8), cv2_falg)
    8. return cv_img
    9. # 自定义装饰器计算时间
    10. def compute_time(func):
    11. def compute(*args, **kwargs):
    12. st = time.time()
    13. result = func(*args, **kwargs)
    14. et = time.time()
    15. print('消费时间 %.6f s' % (et - st))
    16. return result
    17. return compute
    18. @compute_time
    19. def kmeans_img(image, num_clusters, show=False):
    20. # 如果图像是灰度图(单通道),将其转换为三通道
    21. if len(image.shape) == 2:
    22. image = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB)
    23. # 将图像的形状进行调整以便进行 K 均值聚类,提高训练速度
    24. pixels = cv2.resize(image.copy(), None, fx=0.05, fy=0.05, interpolation=cv2.INTER_LINEAR)
    25. pixels = np.float32(pixels.reshape((-1, 3)))
    26. segmented_pixels = np.float32(image.reshape((-1, 3)))
    27. # 初始化 KMeans 模型并拟合数据
    28. kmeans = KMeans(n_clusters=num_clusters)
    29. kmeans.fit(pixels)
    30. # 获取每个像素所属的簇标签
    31. labels = kmeans.predict(segmented_pixels)
    32. # 根据簇标签,将图像像素值转换为簇中心值
    33. segmented_image = kmeans.cluster_centers_[labels]
    34. segmented_image = np.uint8(segmented_image.reshape(image.shape))
    35. if show:
    36. plt.figure(figsize=(10, 5))
    37. plt.subplot(1, 2, 1)
    38. plt.title('Original Image')
    39. plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
    40. plt.axis('off')
    41. plt.subplot(1, 2, 2)
    42. plt.title('Segmented Image')
    43. plt.imshow(segmented_image)
    44. plt.axis('off')
    45. plt.tight_layout()
    46. plt.show()
    47. return segmented_image
    1. image_path =r"C:\Users\pc\Pictures\test\快.png"
    2. image = cv_imread(image_path)
    3. kmeans_img(image,4, show=True)

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

    1. def kmeans_img(image, num_clusters, show=True):
    2. # 如果图像是灰度图(单通道),将其转换为三通道
    3. if len(image.shape) == 2:
    4. image = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB)
    5. # image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    6. print(image.shape)
    7. # 将图像的形状进行调整以便进行 K 均值聚类
    8. pixels = image.reshape((-1, 3))
    9. pixels = np.float32(pixels)
    10. # 设定 kmeans 参数并运行算法
    11. criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 0.2)
    12. _, labels, centers = cv2.kmeans(pixels, num_clusters, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
    13. # 将图像像素值转换为簇中心值
    14. centers = np.uint8(centers)
    15. segmented_image = centers[labels.flatten()]
    16. segmented_image = segmented_image.reshape(image.shape)
    17. if show:
    18. # 显示原始图像和分割后的图像
    19. plt.figure(figsize=(10, 5))
    20. plt.subplot(1, 2, 1)
    21. plt.title('Original Image')
    22. plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
    23. plt.axis('off')
    24. plt.subplot(1, 2, 2)
    25. plt.title('Segmented Image')
    26. plt.imshow(segmented_image)
    27. plt.axis('off')
    28. plt.tight_layout()
    29. plt.show()
    30. return segmented_image

  • 相关阅读:
    一篇文章彻底搞懂熵、信息熵、KL散度、交叉熵、Softmax和交叉熵损失函数
    ssm技术
    北京大学计算机考研资料汇总
    自动化测试用例设计-软件测试基本概念解析
    【软件测试】单元测试、集成测试、系统测试有什么区别?
    经典算法——冒泡排序
    黑马C++ 01 基础 —— 数据类型、运算符、循环
    Statistical Hypothesis Testing
    构建银行人工智能用户画像和自动营销体系
    批量寄件教程
  • 原文地址:https://blog.csdn.net/weixin_46707493/article/details/134480285