返回

从 np.uint8 数组生成 QuPath GeoJSON:实现组织掩模轻松转换

python

从 np.uint8 数组生成 QuPath GeoJSON

引言

组织病理学研究经常需要在不同软件之间转换组织掩模(标注的组织区域)。本文旨在解决将 np.uint8 数组转换为 QuPath 可导入的 GeoJSON 格式的问题。

背景

掩模本质上是一组以 np.uint8 数组存储的形状,其中正值表示组织,0 表示背景。将这些数组转换为 GeoJSON 可让 QuPath 分析组织分布。

转换过程

1. 提取 np.uint8 数组

从 H5 文件中提取掩模数组。可以使用 Python h5py 库轻松完成此操作。

2. 转换为 GeoJSON 点

将数组中的每个正值转换为一个 GeoJSON 点的坐标。

3. 组装 GeoJSON 特征

将点组织到一个 FeatureCollection 中,每个特征表示一个组织区域。

QuPath 的 GeoJSON 格式

QuPath 接受的 GeoJSON 格式与标准略有不同。每个特征必须包含一个 polygon 几何类型,以及其他属性,如分类和颜色。

代码示例

以下 Python 代码演示了如何将 np.uint8 数组转换为 GeoJSON:

import h5py
import json

# 从 H5 文件加载数组
necrosis_dataset = h5_file["wsi_masks"]["predicted_region_mask_l1_5"]
necrosis_numpy_array = necrosis_dataset[:, :]

# 转换为 GeoJSON 点
coordinates = [row.tolist() for row in necrosis_numpy_array]

# 组装 GeoJSON 特征
geojson = {
    "type": "FeatureCollection",
    "features": [
        {
            "type": "Feature",
            "geometry": {
                "type": "Point",
                "coordinates": coordinates
            }
        }
    ]
}

# 转换为 QuPath 格式
qupath_geojson = {
    "type": "Feature",
    "id": "PathDetectionObject",
    "geometry": {
        "type": "Polygon",
        "coordinates": [[[17738.72, 42238], [17737.94, 42240.13], [17738.39, 42242.34], [17737.21, 42244.28], [17737.19, 42246.54], [17739.74, 42250.23], [17743.86, 42248.63], [17743.7, 42246.37], [17745.05, 42242.08], [17748.38, 42239.13], [17747.76, 42238.25], [17738.72, 42238]]]
    },
    "properties": {
        "isLocked": false,
        "measurements": [],
        "classification": {
            "name": "Other",
            "colorRGB": -377282
        }
    }
}

# 导出 GeoJSON 文件
with open("output.geojson", "w") as file:
    json.dump(qupath_geojson, file)

结论

通过将 np.uint8 数组转换为 QuPath GeoJSON 格式,可以轻松地在不同程序之间共享组织掩模。本指南提供了详细的说明和代码示例,可帮助您顺利完成此过程。

常见问题解答

  • 什么是 np.uint8 数组?

np.uint8 数组是一种存储像素值的数据结构,其中正值表示组织,0 表示背景。

  • 为什么要将 np.uint8 数组转换为 GeoJSON?

GeoJSON 是一种常见的地理数据格式,可用于在不同的软件之间共享注释和掩模。

  • QuPath 中的 GeoJSON 格式与标准 GeoJSON 有何不同?

QuPath GeoJSON 要求每个特征具有 polygon 几何类型,并包含其他属性,如分类和颜色。

  • 如何导出 GeoJSON 文件?

您可以使用 Python json 库或文本编辑器将 GeoJSON 数据保存到文件中。

  • 如何导入 GeoJSON 文件到 QuPath?

在 QuPath 中,右键单击图像窗口并选择“导入注释”以导入 GeoJSON 文件。