You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于K-means聚类的GeoTIFF灰度图像压缩算法实现咨询

GeoTIFF图像处理与K-means聚类实践

我来帮你把这个图像处理流程和代码整理得清晰易用,完全贴合你的需求:

1. 数据预处理步骤

  • 原始GeoTIFF灰度图像对应的二维数组尺寸为 (4377, 6172)
  • 先截取数组的前1024×1024区域(总计 1024*1024=1048576 个数值),作为压缩算法的输入数据
  • 经过压缩算法处理后,得到包含4个数值的 finalmatrix 列表变量

2. K-means聚类算法实现代码

接下来针对 finalmatrix 中的数值应用K-means聚类,我把完整可运行的代码整理好了,你可以直接参考使用:

import numpy as np
from osgeo import gdal
from sklearn import cluster
import matplotlib.pyplot as plt

# 1. 读取GeoTIFF图像(替换为你的实际文件路径)
dataset = gdal.Open('your_geotiff_image.tif')
if dataset is None:
    raise FileNotFoundError("找不到指定的GeoTIFF文件,请检查路径是否正确")

# 2. 获取图像二维数组并截取前1024x1024区域
img_array = dataset.ReadAsArray()
cropped_array = img_array[:1024, :1024]

# 3. 替换为你的压缩算法逻辑,生成finalmatrix
# 示例:假设压缩后得到4个数值的列表
# finalmatrix = your_custom_compression_function(cropped_array)
finalmatrix = [15.3, 42.1, 14.8, 41.7]  # 仅为示例,替换为实际压缩结果

# 4. 转换数据格式以适配sklearn的K-means要求
finalmatrix_np = np.array(finalmatrix).reshape(-1, 1)

# 5. 执行K-means聚类(聚类数可根据需求调整,这里设为2)
kmeans_model = cluster.KMeans(n_clusters=2, random_state=42)
cluster_labels = kmeans_model.fit_predict(finalmatrix_np)
cluster_centers = kmeans_model.cluster_centers_

# 6. 可选:可视化聚类结果,直观查看分组情况
plt.figure(figsize=(8, 4))
plt.scatter(range(len(finalmatrix)), finalmatrix, c=cluster_labels, cmap='coolwarm', s=100)
plt.scatter(range(len(cluster_centers)), cluster_centers.flatten(), c='black', marker='X', s=200, label='聚类中心')
plt.title('压缩后数值的K-means聚类结果')
plt.xlabel('数值索引')
plt.ylabel('灰度数值')
plt.legend()
plt.show()

代码小提示

  • 务必把代码中的 your_geotiff_image.tif 替换成你实际的GeoTIFF文件路径
  • 压缩算法部分需要你替换成自己的实现逻辑,代码里用注释标注了位置
  • K-means的聚类数 n_clusters 可以根据你的业务需求调整,示例中设为2
  • 可视化部分是可选功能,能帮你直观看到数值的聚类分组效果

内容的提问来源于stack exchange,提问作者Akshay Parmar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:18:36