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

求助:将多边形/多面体坐标转为QuPath可用GeoJSON格式

解决方案:CSV转QuPath兼容GeoJSON(处理孔洞与多面体)

直接用shapely解析WKT几何,再映射为QuPath要求的GeoJSON结构是最省心的方式,不用自己手动拆分坐标串,避免孔洞和多面体的嵌套逻辑出错。

核心步骤

  1. 解析WKT几何:用shapely.wkt.loads直接读取CSV中的POLYGON/MULTIPOLYGON字段,自动识别外环、孔洞(内环)和多面体的子结构。
  2. 映射为QuPath GeoJSON格式:
    • 单个Polygon:GeoJSON的coordinates是[外环坐标列表, 内环1坐标列表, ...]
    • MultiPolygon:coordinates是嵌套数组,每个元素对应一个子Polygon的[外环, 内环...]结构
  3. 导出GeoJSON:按QuPath要求,每个几何对象要包含type、coordinates,可额外添加properties(比如标注名称、类别)

完整脚本示例

import pandas as pd
from shapely.wkt import loads
import json

def convert_geometry_to_qupath_geojson(geom):
    if geom.geom_type == 'Polygon':
        # 提取外环和所有内环(孔洞)
        coords = [list(geom.exterior.coords)]
        coords.extend([list(interior.coords) for interior in geom.interiors])
        return {'type': 'Polygon', 'coordinates': coords}
    elif geom.geom_type == 'MultiPolygon':
        multi_coords = []
        for poly in geom.geoms:
            poly_coords = [list(poly.exterior.coords)]
            poly_coords.extend([list(interior.coords) for interior in poly.interiors])
            multi_coords.append(poly_coords)
        return {'type': 'MultiPolygon', 'coordinates': multi_coords}
    else:
        raise ValueError(f"不支持的几何类型:{geom.geom_type}")

# 读取CSV(假设几何字段名为'geometry')
df = pd.read_csv('your_file.csv')

# 转换所有几何并生成GeoJSON Feature集合
features = []
for idx, row in df.iterrows():
    wkt_geom = row['geometry']
    try:
        geom = loads(wkt_geom)
        geojson_geom = convert_geometry_to_qupath_geojson(geom)
        # 可添加自定义属性,比如标注名称
        feature = {
            'type': 'Feature',
            'geometry': geojson_geom,
            'properties': {'name': row.get('name', f'Annotation_{idx}')}
        }
        features.append(feature)
    except Exception as e:
        print(f"处理行{idx}失败:{e}")

# 生成最终的GeoJSON文件
qupath_geojson = {
    'type': 'FeatureCollection',
    'features': features
}

with open('qupath_output.geojson', 'w', encoding='utf-8') as f:
    json.dump(qupath_geojson, f, indent=2)

注意事项

  • 如果你的CSV坐标是图像坐标系(左上角为原点,y轴向下),无需调整;如果是常规地理坐标系(y轴向上),需要翻转y坐标,可在提取坐标时修改:
    # 翻转y坐标示例
    def flip_y(coords, image_height):
        return [(x, image_height - y) for x, y in coords]
    
  • 确保安装依赖:pip install pandas shapely

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 23:55:53