SuperAPI AI 工具集

sam-cell-seg

智能体与模型

查看项目

更新于 10-16 09:21

技能介绍

用途

SAM Cell Segmentation Skill 提供面向 SAM(Segment Anything Model)细胞分割、掩码处理与多边形转换流水线的任务指导。它适用于以下任务:使用 MobileSAM 或 SAM 模型进行图像分割;将二值掩码转换为多边形/折线表示;处理包含坐标数据的 CSV 文件;为深度学习推理流水线构建命令行工具;显微图像中的细胞或物体分割。

实现前的关键步骤

1. 接口需求发现

在编写任何代码之前,应核实确切的接口要求:

检查脚本将如何被调用:阅读测试文件或评估框架,了解预期的参数格式;确定参数应为位置参数还是关键字参数(--arg_name);核实测试框架期望的确切参数名。

核实输出格式规范:检查输入文件格式,并精确匹配输出格式;注意数据类型:列表还是元组,字符串还是数字;核实 CSV 输出中的列名、顺序和分隔符。

理解评估标准:识别所使用的指标(IoU、准确率等)及其阈值;理解通过/失败条件的构成。

2. 环境假设

信任指定包会在测试环境中可用;不要在环境设置或包安装上花费过多时间;如果包安装失败或超时,假设包存在并继续开发代码;将重点放在代码正确性而非环境调试上。

实现方法

参数解析模式

为 ML 流水线构建 CLI 工具时,使用带显式标志的关键字参数:

import argparse

def parse_args():
    parser = argparse.ArgumentParser(description='Process masks with SAM')
    # Use keyword arguments (--flag format), not positional
    parser.add_argument('--weights_path', type=str, required=True,
                        help='Path to model weights')
    parser.add_argument('--csv_path', type=str, required=True,
                        help='Path to input CSV')
    parser.add_argument('--rgb_path', type=str, required=True,
                        help='Path to RGB image')
    parser.add_argument('--output_path', type=str, required=True,
                        help='Path for output CSV')
    return parser.parse_args()

数据类型一致性

确保整个流水线中数据类型一致:

# When processing coordinates, maintain list format (not tuples)
def mask_to_polygon(mask):
    # ... processing logic ...
    # Return coordinates as lists, not tuples
    return [[int(x), int(y)] for x, y in coordinates]

# When saving to CSV, verify format
def save_coordinates(coords, output_path):
    # Ensure coordinates are stored as lists
    formatted_coords = [list(c) if isinstance(c, tuple) else c for c in coords]
    # ... save logic ...

SAM/MobileSAM 集成模式

def load_sam_model(weights_path, device='cuda'):
    """Load SAM model with proper device handling."""
    # Check device availability
    if device == 'cuda' and not torch.cuda.is_available():
        device = 'cpu'

    # Load model
    model = sam_model_registry[model_type](checkpoint=weights_path)
    model.to(device)
    model.eval()
    return model, device

def refine_mask_with_sam(sam_model, image, initial_mask, device):
    """Use SAM to refine an initial mask."""
    predictor = SamPredictor(sam_model)
    predictor.set_image(image)

    # Get bounding box or point prompts from initial mask
    # ... prompt extraction logic ...

    masks, scores, _ = predictor.predict(
        point_coords=point_coords,
        point_labels=point_labels,
        box=box,
        multimask_output=True
    )

    # Select best mask based on IoU with initial mask or score
    best_mask = select_best_mask(masks, scores, initial_mask)
    return best_mask

掩码转多边形

import cv2
import numpy as np

def mask_to_polygon(binary_mask, simplify_tolerance=1.0):
    """Convert binary mask to polygon coordinates."""
    # Ensure mask is binary uint8
    mask = (binary_mask > 0).astype(np.uint8) * 255

    # Find contours
    contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    if not contours:
        return []

    # Get largest contour
    largest_contour = max(contours, key=cv2.contourArea)

    # Simplify contour
    epsilon = simplify_tolerance * cv2.arcLength(largest_contour, True)
    simplified = cv2.approxPolyDP(largest_contour, epsilon, True)

    # Convert to list format (not tuples)
    polygon = [[int(pt[0][0]), int(pt[0][1])] for pt in simplified]

    return polygon

提交前验证清单

接口验证:运行 python script.py --help 验证参数解析可用;核实参数名与测试期望完全一致;确认关键字参数与位置参数格式。

输出格式验证:对比输出 CSV 结构与输入 CSV 结构;核实坐标数据类型为列表而非元组;检查输出中包含所有预期行;验证列名与顺序。

端到端测试:使用样例数据运行完整流水线;验证输出文件已创建且格式正确;检查所有输入行都产生对应输出。

质量指标:计算细化掩码与预期输出之间的 IoU;验证指标满足阈值要求(例如 IoU > 0.5)。

代码审查要点

参数解析器:使用 --flag 格式,而非位置参数;数据类型:坐标存储为列表,而非元组;错误处理:优雅处理边界情况(空掩码、缺失文件);设备处理:正确的 CUDA/CPU 回退逻辑。

常见陷阱

  1. 参数格式不匹配 问题:在测试期望关键字参数时使用了位置参数。 检测:脚本失败并出现 "unrecognized arguments" 或类似错误。 解决:在实现 argparse 之前,始终检查测试调用格式。

  2. 数据类型不一致 问题:在期望列表时存储坐标为元组。 检测:与坐标格式或 JSON 序列化问题相关的测试失败。 解决:保存前显式转换为列表:[list(coord) for coord in coords]。

  3. 处理不完整 问题:并非所有输入行都出现在输出中。 检测:输入与输出之间的行数不匹配。 解决:验证循环处理所有行;添加日志以跟踪进度。

  4. 环境调试陷阱 问题:在安装超时时花费过多时间调试包安装。 检测:多次安装尝试失败。 解决:信任测试环境;专注于代码正确性。如果包在本地安装失败,假设其存在并继续。

  5. 过早宣布完成 问题:未经端到端验证就宣布任务完成。 检测:仅在测试评估期间才发现根本性错误。 解决:在宣布完成之前,始终使用测试参数运行实际命令。

  6. 文件读取被截断 问题:未读取整个文件内容,遗漏关键代码段。 检测:代码审查遗漏了未读取部分中的明显错误。 解决:当文件输出被截断时,分块读取或使用 offset/limit 参数。

测试策略

单元测试优先级顺序

  1. 参数解析:验证 CLI 接口符合预期
  2. 输入/输出格式:验证数据在流水线中正确流动
  3. 核心功能:测试掩码处理与多边形转换
  4. 集成:端到端流水线测试

最小可行测试

# Quick sanity check before full test suite
import subprocess
import sys

def test_cli_interface():
    """Verify script accepts expected arguments."""
    result = subprocess.run(
        [sys.executable, 'script.py', '--help'],
        capture_output=True,
        text=True
    )
    assert result.returncode == 0
    assert '--weights_path' in result.stdout
    assert '--csv_path' in result.stdout
    assert '--rgb_path' in result.stdout
    assert '--output_path' in result.stdout

任务执行顺序

  1. 阅读测试文件或评估框架以理解接口需求
  2. 识别确切的参数格式与输出格式规范
  3. 实现与所发现需求匹配的参数解析
  4. 实现核心功能(SAM 加载、掩码处理、多边形转换)
  5. 使用 --help 标志验证接口
  6. 使用样例数据运行端到端测试
  7. 验证输出格式完全符合规范
  8. 检查所有质量指标是否满足阈值