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

如何获取多标签阈值图像目标坐标 Cellpose分割结果单细胞坐标提取

从Cellpose分割标签图提取单细胞像素坐标的方法

首先明确:你拿到的4通道分割图是RGBA格式的可视化结果,不是CMYK图,图中每个独立的纯色连通块就对应一个分割出的单细胞,不需要做色彩空间转换,直接按以下步骤提取即可。
Cellpose分割标签示例图

  • 前置依赖安装
    用到opencv-python和numpy两个库,没装的话先执行安装:
    pip install opencv-python numpy
    
  • 方法1:连通域快速提取(适合色块无粘连的场景)
    步骤和代码如下:
    1. 读取图像时保留全部4通道信息,过滤纯黑背景
      import cv2
      import numpy as np
      
      # 替换成你的标签图路径
      img = cv2.imread("seg_label.png", cv2.IMREAD_UNCHANGED)
      # 提取非背景区域:Cellpose可视化的背景是纯黑(RGB=0,0,0)
      non_bg_mask = ~np.all(img[:, :, :3] == 0, axis=2)
      
    2. 对非背景区域做8邻域连通域标记,每个独立色块会被分配唯一ID
      label_num, label_map, stats, centroids = cv2.connectedComponentsWithStats(
          non_bg_mask.astype(np.uint8), 
          connectivity=8
      )
      
    3. 遍历所有标记结果(跳过ID=0的背景),提取每个细胞的像素坐标
      cell_result = []
      for cell_id in range(1, label_num):
          # 拿到当前细胞所有像素的(y, x)坐标
          y_coords, x_coords = np.where(label_map == cell_id)
          cell_result.append({
              "cell_id": cell_id,
              "pixel_coords": np.stack([y_coords, x_coords], axis=1),
              "cell_area": stats[cell_id, cv2.CC_STAT_AREA],
              "centroid": centroids[cell_id]
          })
      
  • 方法2:颜色编码提取(适合存在轻微色块粘连的场景,准确率更高)
    Cellpose给每个细胞分配的可视化颜色是唯一的,可以直接把每个像素的RGBA值编码为唯一标签ID,不需要依赖连通域判断,避免粘连区域识别错误:
    # 将4通道RGBA值编码为32位唯一整数,每个颜色对应唯一ID
    encoded_label = (
        img[:, :, 0].astype(np.uint32) 
        | (img[:, :, 1].astype(np.uint32) << 8)
        | (img[:, :, 2].astype(np.uint32) << 16)
        | (img[:, :, 3].astype(np.uint32) << 24)
    )
    # 把背景区域ID设为0
    encoded_label[~non_bg_mask] = 0
    
    cell_result = []
    # 遍历所有非0的唯一ID,对应每个独立细胞
    for idx, cell_id in enumerate(np.unique(encoded_label)[1:], start=1):
        y_coords, x_coords = np.where(encoded_label == cell_id)
        cell_result.append({
            "cell_id": idx,
            "pixel_coords": np.stack([y_coords, x_coords], axis=1)
        })
    

提取出的pixel_coords数组里,每一行都是对应细胞的一个像素点坐标,格式为(y轴行号, x轴列号),和图像数组的索引规则完全一致,可以直接用来做后续的像素值提取、形态学计算等操作。

内容的提问来源于stack exchange,提问作者Mark Zurbrügg

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.02 04:48:23