Cellpose-SAM
#5_image_analysis
概要
2026.06.04にCellposeのバージョンアップがあり、基本モデルがcpsam_v2になり、DINOv3ベースのcpdinoが追加された。
2025.05.01にCellpose-SAMのプレプリントが出たのと同時に、Cellposeがver.4.0になった。
これまでと少しコードが変わってくるので注意。
MacでもGPUデバイスを指定する必要がなくなった
Macでの構築環境について、メモを残しておきます(by 井上紘一)
準備
Miniconda + conda-forgeによる環境構築 (2024.06.26)
code:Anaconda Prompt
pip install --upgrade cellpose
Cellpose-dinoを使いたい場合は以下も(注:Python3.11以上が必要)
code:Anaconda Prompt
git+https://github.com/facebookresearch/dinov3
Sample code
code:jupyter notebook
## Import modules
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from cellpose import models, io, utils, plot,core
import torch
print(core.use_gpu())
code:jupyter notebook
##Image loading and check
images = io.imread('test.tif') #Multitiff, grayscale-one color
print(f"Image shape: {images.shape}")
print(f"Timepoints: {images.shape0}")
plt.imshow(images0, cmap='gray')
plt.title('First timepoint')
plt.colorbar()
plt.show()
code:jupyter notebook
%%time
##Run with CPU, You can skip if GPU=true
model = models.CellposeModel(gpu=False)
masks, flows, styles = model.eval(images0,flow_threshold=0.4,cellprob_threshold=0.0)
fig = plt.figure(figsize=(16, 10))
plot.show_segmentation(fig, images0, masks, flows0)
plt.tight_layout()
plt.show()
code:jupyter notebook
%%time
##Run with GPU
model = models.CellposeModel(gpu=True)
masks, flows, styles = model.eval(images0,flow_threshold=0.4,cellprob_threshold=0.0)
fig = plt.figure(figsize=(16, 10))
plot.show_segmentation(fig, images0, masks, flows0)
plt.tight_layout()
plt.show()
code:jupyter notebook
%%time
##Batch calculation for multi-tiff
model = models.CellposeModel(gpu=True)
for i, img in enumerate(images):
mask, flow, style = model.eval(img,flow_threshold=0.4,cellprob_threshold=0.0)
io.save_to_png(img, mask, flow, 'segmentation/'+str(i)+'.png')
<Mac studio M4 Maxチップ 36 GB メモリの場合 by 井上>
code: Miniconda
conda create -n cellpose-env2 python=3.10 -y
conda activate cellpose-env2
#公式案内の Apple Silicon 用MPS版 にしたがって:
pip install torch torchvision torchaudio
# pipでcellposeと基本ライブラリをインストール
pip install cellpose tifffile matplotlib numpy pandas scikit-image scipy torch seaborn
pip install ipykernel
python -m ipykernel install --user --name=cellpose-env2 --display-name "Python (cellpose-env2)"
conda activate base
jupyter lab
カーネルを指定(Python (cellpose-env2))して、実行
code: #cellpose segmentation, マスク作成オーバーレイ(GPU使用)
# ===== バージョン&GPU確認 =====
import sys, platform
import numpy
import matplotlib
import pandas
import skimage
import scipy
import torch
import importlib.metadata
from cellpose import models, core
print("GPU利用可能:", core.use_gpu())
print("=== 環境情報 ===")
print("OS:", platform.system(), platform.release())
print("Python:", sys.version.split()0)
print("NumPy:", numpy.__version__)
print("matplotlib:", matplotlib.__version__)
print("pandas:", pandas.__version__)
print("scikit-image:", skimage.__version__)
print("SciPy:", scipy.__version__)
print("Torch:", torch.__version__, "| MPS available:",
getattr(torch.backends, "mps", None) and torch.backends.mps.is_available())
try:
cellpose_version = importlib.metadata.version("cellpose")
except Exception:
cellpose_version = "不明"
print("cellpose:", cellpose_version)
# ===== Cellposeモデル初期化(MPS有効ならGPU) =====
print("\n=== Cellpose モデル初期化チェック ===")
use_gpu = getattr(torch.backends, "mps", None) and torch.backends.mps.is_available()
try:
model = models.CellposeModel(model_type='cyto2', gpu=use_gpu)
print("Cellpose OK:", type(model).__name__, "| GPU使用:", use_gpu)
except Exception as e:
print("Cellpose 初期化エラー:", str(e))
raise SystemExit
# ===== マスク作成とオーバーレイ保存処理 =====
import os
import numpy as np
import matplotlib.pyplot as plt
from tifffile import imread, imwrite
from cellpose import plot
# === ファイルリスト(拡張可能) ===
filenames = "t1-1_DIC.tif"
# === ディレクトリ設定 ===
input_dir = "/Users/koichiinoue/Q-bio Exp(2025-)/Analysis-SP8ZDC4/SpeQ-ZDC4/images"
mask_dir = "/Users/koichiinoue/Q-bio Exp(2025-)/Analysis-SP8ZDC4/SpeQ-ZDC4/masks"
overlay_dir = "/Users/koichiinoue/Q-bio Exp(2025-)/Analysis-SP8ZDC4/SpeQ-ZDC4/visualize"
os.makedirs(mask_dir, exist_ok=True)
os.makedirs(overlay_dir, exist_ok=True)
# === 各画像の処理 ===
for filename in filenames:
print(f"\n--- 処理中: {filename} ---")
input_path = os.path.join(input_dir, filename)
# 画像読み込み(DICは単チャネル)
img = imread(input_path)
if img.ndim == 3:
img = img0
print("画像shape:", img.shape, "| dtype:", img.dtype)
# float32で正規化
img_float = img.astype(np.float32)
img_float /= img_float.max()
# セグメンテーション実行
masks, flows, styles = model.eval(img_float,
diameter=None,
channels=0, 0,
flow_threshold=0.4,
cellprob_threshold=0.0)
# === マスク保存 ===
mask_name = filename.replace(".tif", "_mask.tif")
mask_path = os.path.join(mask_dir, mask_name)
imwrite(mask_path, masks.astype(np.uint16))
print("マスク画像を保存:", mask_path)
# === オーバーレイ保存 ===
overlay_name = filename.replace(".tif", "_overlay.png")
overlay_path = os.path.join(overlay_dir, overlay_name)
fig = plt.figure(figsize=(10, 10))
_ = plot.show_segmentation(fig, img_float, masks, flows0)
plt.axis('off')
plt.tight_layout()
plt.savefig(overlay_path, dpi=300)
plt.close()
print("オーバーレイ画像を保存:", overlay_path)
GPU利用可能: True
=== 環境情報 ===
OS: Darwin 24.6.0
Python: 3.10.19
NumPy: 2.2.6
matplotlib: 3.10.7
pandas: 2.3.3
scikit-image: 0.25.2
SciPy: 1.15.3
Torch: 2.9.1 | MPS available: True
cellpose: 4.0.7
Date :2025/5/20
Modified Date :
Author : y-goto.icon