如何在h5格式人群密度图中完成聚类及质心可视化
人群密度图聚类与质心标注实现方案
实现逻辑说明
- 首先将密度矩阵转换为带权重的人群坐标样本,过滤低密度背景噪声
- 可根据需求选择KMeans/KMedoids/DBSCAN算法完成聚集人群聚类:
- KMeans:计算速度快,返回的是均值质心,适合已知聚集块数量的场景
- KMedoids:返回的中心点是真实存在的人群坐标(medoid),更符合实际业务意义
- DBSCAN:不需要提前指定聚类数量,可自动识别所有聚集块,过滤离散噪声点
- 最后通过matplotlib将质心标记叠加到密度图上即可完成可视化
完整实现代码
import sys import numpy as np import h5py import matplotlib.pyplot as plt from sklearn.cluster import KMeans # 如果要使用KMedoids需要先安装scikit-learn-extra:pip install scikit-learn-extra # from sklearn_extra.cluster import KMedoids # 1. 读取H5密度矩阵 with h5py.File('/content/img001001.h5', 'r') as hf: h5_matrix = hf.get('density')[:] print(f"密度矩阵维度:{h5_matrix.shape}") # 输出格式为(高度, 宽度) # 2. 预处理:提取带权重的人群坐标 # 设定密度阈值,过滤无人群的背景噪声点 density_threshold = 0.1 y_coords, x_coords = np.where(h5_matrix > density_threshold) weights = h5_matrix[y_coords, x_coords] # 构造样本矩阵,每行是一个点的(x,y)坐标 samples = np.column_stack((x_coords, y_coords)) # 3. 聚类计算质心/中心点 # 这里以KMeans为例,提前指定聚集块数量n_clusters,可根据实际场景调整 n_clusters = 5 # 替换为你实际的聚集块数量 kmeans = KMeans(n_clusters=n_clusters, random_state=42) labels = kmeans.fit_predict(samples, sample_weight=weights) centroids = kmeans.cluster_centers_ # 如果使用KMedoids获取真实中心点,替换上面聚类部分代码即可: # kmedoids = KMedoids(n_clusters=n_clusters, random_state=42) # labels = kmedoids.fit_predict(samples, sample_weight=weights) # centroids = kmedoids.cluster_centers_ # 如果使用DBSCAN自动识别聚类数量,不需要提前指定n_clusters: # from sklearn.cluster import DBSCAN # db = DBSCAN(eps=10, min_samples=20).fit(samples, sample_weight=weights) # labels = db.labels_ # # 过滤噪声点(label为-1)后计算每个类的质心 # centroids = [] # for label in set(labels): # if label == -1: # continue # class_samples = samples[labels == label] # class_weights = weights[labels == label] # centroid = np.average(class_samples, axis=0, weights=class_weights) # centroids.append(centroid) # centroids = np.array(centroids) # 4. 可视化叠加质心 plt.figure(figsize=(12, 8)) # 绘制原始密度图 plt.imshow(h5_matrix, cmap='jet') # 绘制质心,用红色圆点标记,大小可调 plt.scatter(centroids[:, 0], centroids[:, 1], c='red', s=100, marker='o', edgecolors='white', label='聚集质心') plt.legend() plt.axis('off') plt.show()
结果准确性验证方法
- 可通过轮廓系数评估聚类效果,轮廓系数越接近1说明聚类效果越好
- 可视化后对比原始密度图的聚集块位置和质心位置匹配度,调整聚类参数(如聚类数量、DBSCAN的eps/min_samples、密度阈值等)优化结果
- 可给不同聚类块叠加不同颜色的半透明遮罩,更直观判断聚类是否准确
内容的提问来源于stack exchange,提问作者FRANCESCO SAVERIO TROCCOLI
相关产品推荐
相关产品推荐

