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

为何我的Cellpose脚本未将文件写入输出文件夹?

Cellpose脚本无报错但未生成输出文件排查

脚本功能为从输入文件夹读取图像,通过预训练Cellpose模型处理后将分割掩码存入输出文件夹,但运行无报错却未生成预期输出文件,代码如下:

import os
import numpy as np
import imageio.v2 as imageio
from cellpose import models

model_path = r"C:\Users\TomoCube\Desktop\New Testing\trained_model\models\cellpose_residual_on_style_on_concatenation_off_trained_model_2025_05_29_14_15_22.066364"
input_folder = r"C:\Users\TomoCube\Desktop\Input Folder"
output_folder = r"C:\Users\TomoCube\Desktop\Output Folder"
os.makedirs(output_folder, exist_ok=True)

# 🔧 TEST: Write a dummy file to confirm save path works
dummy_test_path = os.path.join(output_folder, "dummy_test.tif")
imageio.imwrite(dummy_test_path, np.zeros((10, 10), dtype='uint16'))
print(f"✅ Dummy test file saved: {dummy_test_path}")

model = models.CellposeModel(pretrained_model=model_path, gpu=False)

image_files = [
    f for f in os.listdir(input_folder)
    if f.lower().endswith(('.png', '.jpg', '.tif')) and '_masks' not in f
]
image_files.sort()

for filename in image_files:
    image_path = os.path.join(input_folder, filename)
    print(f"\n🔍 Processing: {filename}")

    img = imageio.imread(image_path)
    print(f"  ➤ Image shape: {img.shape}, dtype: {img.dtype}")

    masks, flows, styles = model.eval(img, channels=[0, 0])
    print(f"  ➤ masks.max(): {masks.max()}, dtype: {masks.dtype}, shape: {masks.shape}")

    output_filename = f"{os.path.splitext(filename)[0]}_mask.tif"
    output_path = os.path.join(output_folder, output_filename)

    try:
        imageio.imwrite(output_path, masks.astype('uint16'))
        print(f"  ✅ Mask saved: {output_path}")
    except Exception as e:
        print(f"  ❌ Failed to save mask for {filename}: {e}")

print("\n✅ All done! Masks saved to:", output_folder)

排查步骤及解决方案

  • 确认是否有符合条件的输入文件
    代码仅筛选文件名不含_masks、后缀为.png/.jpg/.tif的文件,可能输入文件夹内的文件不符合规则(比如后缀为.tiff、文件名带_masks,或文件夹为空)。在image_files.sort()后添加一行打印:

    print(f"共找到{len(image_files)}个待处理图像文件")
    

    若输出为0,说明没有文件被选中,需调整筛选规则或检查输入文件夹内容。

  • 检查模型输出的掩码是否全为0
    若masks.max()打印值为0,说明模型未检测到任何细胞,保存的是全黑TIFF文件,容易被误认为未生成。可直接打开输出文件夹查看是否存在对应_mask.tif文件,或修改代码将掩码可视化后保存:

    imageio.imwrite(output_path, (masks/masks.max()*255).astype('uint8'))
    
  • 替换TIFF写入库解决兼容性问题
    部分环境下imageio写入uint16格式TIFF可能存在隐性问题,可改用tifffile库写入:

    1. 先安装库:pip install tifffile
    2. 修改代码中的写入部分:
      import tifffile
      # 替换原imageio.imwrite行
      tifffile.imwrite(output_path, masks.astype('uint16'))
      
  • 验证输出路径的实际位置
    虽然dummy文件能保存,但需确认输出文件夹路径是否正确(比如是否存在同名快捷方式而非实际文件夹),可直接打印output_folder的绝对路径并手动打开验证。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 00:06:00