Bohrium
robot
新建

空间站广场

论文
Notebooks
比赛
课程
Apps
我的主页
我的Notebooks
我的论文库
我的足迹

我的工作空间

任务
节点
文件
数据集
镜像
项目
数据库
公开
Cellpose: a generalist algorithm for cellular segmentation
Deep Learning
notebook
cellpose
python
Deep Learningnotebookcellposepython
HwBayshell
更新于 2024-09-03
推荐镜像 :Basic Image:ubuntu22.04-py3.10-R
推荐机型 :c2_m4_cpu
赞 1
一、导言
二、Cellpose算法简介
1. Cellpose算法的安装和使用
2. Cellpose算法的通用性
3. Cellpose算法的有效性
4. 提交手动分割图像以优化Cellpose运行
5. Cellpose分割3D图像事例
三. 通过t-SNE图进行数据集的可视化
1. 导言
2. t-SNE算法的实现
基本原理
将点间距离转换为概率分布
用KL散度度量概率分布的差异
定义损失函数,计算梯度
四、Cellpose算法的代码实现
提示
获取图片的 Google Drive 路径
安装 Cellpose
运行 Cellpose
Step 6. 根据想要分割的内容选择模型。
Step 7.在图像上测试 cellpose,且根据图像调整参数。
使用 CELLPOSE 分割细胞
如何使用 FIJI 从掩码或标签图中提取 ROI
将文件另存为 *.npy
五、使用CELLPOSE进行细胞分割-1
六、在Colab中使用GPU运行Cellpose

一、导言

许多生物学应用需要从显微镜图像中分割细胞体、膜和细胞核。深度学习在解决这一问题上取得了显著进展,但目前的方法通常专用于具有大量训练数据集的图像。我们在此介绍一种通用的基于深度学习的分割方法——Cellpose,它可以精确分割多种类型的图像中的细胞,而无需对模型进行重新训练或调整参数。Cellpose是在一个包含超过70,000个分割对象的高度多样化细胞图像新数据集上训练的。我们还展示了Cellpose的三维(3D)扩展版,它可以重用二维(2D)模型,无需3D标记数据。为了支持社区对训练数据的贡献,我们开发了用于手动标注和整理自动化结果的软件。通过定期对社区贡献的数据进行重新训练,Cellpose将持续改进。

代码
文本

二、Cellpose算法简介

1. Cellpose算法的安装和使用

Cellpose是实现细胞分割(cell segmentation)的一种通用算法,可以通过网址 www.cellpose.org ,或者通过 pip install cellpose 安装GUI,演示及使用视频如下。

代码
文本

2. Cellpose算法的通用性

生物领域许多大大小小的问题都需要用到细胞分割,作为通用模型的Cellpose可以实现对更多类型细胞的更广泛训练及测试。

代码
文本

3. Cellpose算法的有效性

Cellpose可以从不同类型的微观、各异的组织和不同染色或荧光标签中分离出大量不同种类的图像,甚至可以用于岩石、水母、海胆的分割。

代码
文本

4. 提交手动分割图像以优化Cellpose运行

在图形用户界面(GUI)中,可以以每小时 300-600 个对象的速度手动分割上传的图像,且并不需要非常精确的轮廓。上传的分割图像将会用于优化后续版本Cellpose算法的优化。

代码
文本

5. Cellpose分割3D图像事例

下列图像展现了 Cellpose 分割 3D 图片的案例,通过旋转图像,可以得到在投影面上的不同划分。

代码
文本

更多内容可以在论文https://www.nature.com/articles/s41592-020-01018-x 中找到。

代码
文本

三. 通过t-SNE图进行数据集的可视化

1. 导言

t-SNE图可以用于将数据从高维数据转到低维数据,并且保留数据的主要信息,从而可以在图像上更好呈现,便于可视化。 相较于PCA算法的降维方式,t-SNE算法可以保留数值的局部信息,更加凸显数据间的差异,而避免在将高维数据降维的过程中形成拥挤现象。t-SNE算法的流程和实现这一过程的Python程序见下。


代码
文本

2. t-SNE算法的实现

基本原理

t-SNE算法的基本原理是给定一组高维数据,通过点间距离得到概率分布,再在低纬平面上生成同等数量的点,计算这组点间的概率分布,并通过计算损失函数,进行梯度下降的方法更新数据,得到满足要求的低维数据。

事实上,t-SNE算法是直接在低维平面上拟合点并进行优化而实现的算法,故其优化与迭代次数,初始生成的随机数据都有关。而在实现这一操作的过程中,有如下具体的问题尚待解决:

  • 如何定性高维点间的概率分布
  • 如何“量化”高维与低维组间数据的差距,得到损失函数
  • 如何通过损失函数更新数据,通过迭代实现优化

以下将对上述问题进行解释。

将点间距离转换为概率分布

通过如下公式,将高维坐标点与其他点的距离转化为概率分布。

其中高维数据采用指数衰减方式定义相似度:

而低维数据采用如下方式定义相似度:

代码
文本
[ ]
def fit(X):
n_samples = X.shape[0]
# Compute euclidean distance
distances = pairwise_distances(X, metric='euclidean', squared=True)
# Compute joint probabilities p_ij from distances.
P = _joint_probabilities(distances=distances, desired_perplexity=perplexity, verbose=False)
# The embedding is initialized with iid samples from Gaussians with standard deviation 1e-4.
X_embedded = 1e-4 * np.random.mtrand._rand.randn(n_samples, n_components).astype(np.float32)
# degrees_of_freedom = n_components - 1 comes from
# "Learning a Parametric Embedding by Preserving Local Structure"
# Laurens van der Maaten, 2009.
degrees_of_freedom = max(n_components - 1, 1)
return _tsne(P, degrees_of_freedom, n_samples, X_embedded=X_embedded)

代码
文本

用KL散度度量概率分布的差异

对于两个随机变量 ,定义KL散度为

且可以由琴生不等式确保KL散度非负。KL散度衡量了q对p概率密度的“差异性”,且在对上式优化的过程中,在p的高概率部分,q也会取到高概率。下图展现了在优化过程中的结果差异:

代码
文本

定义损失函数,计算梯度

我们定义损失函数为

对每个求偏导得到梯度:

将其组合得到梯度向量,即可通过设定学习率,实现梯度优化过程: ,过程的代码块见下。

代码
文本
[ ]
def _kl_divergence(params, P, degrees_of_freedom, n_samples, n_components):
X_embedded = params.reshape(n_samples, n_components)
dist = pdist(X_embedded, "sqeuclidean")
dist /= degrees_of_freedom
dist += 1.
dist **= (degrees_of_freedom + 1.0) / -2.0
Q = np.maximum(dist / (2.0 * np.sum(dist)), MACHINE_EPSILON)
# Kullback-Leibler divergence of P and Q
kl_divergence = 2.0 * np.dot(P, np.log(np.maximum(P, MACHINE_EPSILON) / Q))
# Gradient: dC/dY
grad = np.ndarray((n_samples, n_components), dtype=params.dtype)
PQd = squareform((P - Q) * dist)
for i in range(n_samples):
grad[i] = np.dot(np.ravel(PQd[i], order='K'),
X_embedded[i] - X_embedded)
grad = grad.ravel()
c = 2.0 * (degrees_of_freedom + 1.0) / degrees_of_freedom
grad *= c
return kl_divergence, grad
代码
文本

故通过多次优化,迭代,可以通过t-SNE算法实现数据的二维可视化。剩下的代码块见下:

代码
文本
[ ]
def _tsne(P, degrees_of_freedom, n_samples, X_embedded):
params = X_embedded.ravel()
obj_func = _kl_divergence
params = _gradient_descent(obj_func, params, [P, degrees_of_freedom, n_samples, n_components])
X_embedded = params.reshape(n_samples, n_components)
return X_embedded
代码
文本
[ ]
def _gradient_descent(obj_func, p0, args, it=0, n_iter=1000,
n_iter_check=1, n_iter_without_progress=300,
momentum=0.8, learning_rate=200.0, min_gain=0.01,
min_grad_norm=1e-7):
p = p0.copy().ravel()
update = np.zeros_like(p)
gains = np.ones_like(p)
error = np.finfo(np.float64).max
best_error = np.finfo(np.float64).max
best_iter = i = it
for i in range(it, n_iter):
error, grad = obj_func(p, *args)
grad_norm = linalg.norm(grad)
inc = update * grad < 0.0
dec = np.invert(inc)
gains[inc] += 0.2
gains[dec] *= 0.8
np.clip(gains, min_gain, np.inf, out=gains)
grad *= gains
update = momentum * update - learning_rate * grad
p += update
print("[t-SNE] Iteration %d: error = %.7f, gradient norm = %.7f" % (i + 1, error, grad_norm))
if error < best_error:
best_error = error
best_iter = i
elif i - best_iter > n_iter_without_progress:
break
if grad_norm <= min_grad_norm:
break
return p
代码
文本
[ ]
X_embedded = fit(X)
sns.scatterplot(X_embedded[:,0], X_embedded[:,1], hue=y, legend='full', palette=palette)
代码
文本

在Cellpose中,t-SNE算法对图像的可视化呈现起到了重要作用。在下图中,通过分析不同细胞的类型,可以得到对应的分类,并在二维平面上呈现。

代码
文本

四、Cellpose算法的代码实现

提示

通过选择“运行时”->“更改运行时类型”->“硬件加速器”并选择“GPU”,确保您已启用 GPU 访问

代码
文本
[ ]
from google.colab import drive
drive.mount('/content/drive')
代码
文本
[ ]
#@markdown ##Step 1: Run this cell to connect your Google Drive to colab

#@markdown * Click on the URL.

#@markdown * Sign in your Google Account.

#@markdown You will either have to:
#@markdown * copy the authorisation code and enter it into box below OR

#@markdown * in the new google colab, you can just click "Allow" and it should connect.

#@markdown * Click on "Folder" icon on the Left, press the refresh button. Your Google Drive folder should now be available here as "gdrive".

# mount user's Google Drive to Google Colab.
from google.colab import drive
drive.mount('/content/gdrive')
代码
文本

获取图片的 Google Drive 路径

这一步骤允许此 Colab 笔记本从 Google Drive 访问图片,但另外需要加入图片的文件夹路径。 在笔记本左侧的文件图标中。单击 gdrive 左侧的三角形图标,在下拉视图中导航到包含图片的文件夹。单击文件夹右侧的三个点,然后选择“复制路径”,并将其黏贴于Input_Directory下方。

代码
文本

代码
文本

代码
文本

安装 Cellpose

安装 GPU 版本的 Cellpose 并配置依赖项:

代码
文本
[ ]
#@markdown ##Step 2: Click Play to Install Cellpose
#@markdown * After cellpose installation, the runtime will restart a warning that it has **crashed**, which is fine. This is essential to configure the environment.


#@markdown * On occasion, you may not be able to see the folders on the left panel. Just refresh your browser webpage and it should appear.
#!pip install git+https://www.github.com/mouseland/cellpose.git #to install development version
!pip install cellpose
!pip install torch torchvision torchaudio

#Fix opencv error: ImportError: cannot import name '_registerMatType' from 'cv2.cv2'
!pip install "opencv-python-headless<4.3"
exit(0) #Restart Runtime to use newly installed numpy
#or may get the error: ValueError: numpy.ndarray size changed, may indicate binary incompatibility. Expected 88 from C header, got 80 from PyObject
代码
文本
[ ]
#@markdown ##Step 3: Click Play to configure Cellpose, dependencies and check GPU access

#@markdown *Models will be downloaded when running for the first time*
#disabled installation and import of mxnet as pytorch is the default neural net
import numpy as np
import time, os, sys, random
from urllib.parse import urlparse
import skimage.io
import matplotlib.pyplot as plt
import matplotlib as mpl
%matplotlib inline
mpl.rcParams['figure.dpi'] = 300

from urllib.parse import urlparse
import shutil

#from tifffile import imread, imsave


print ("Downloading Models")
from cellpose import models,core


#https://stackoverflow.com/questions/8924173/how-do-i-print-bold-text-in-python
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
END = '\033[0m'

#Check if colab notebook instance has GPU access
if core.use_gpu()==False:
#Warnings from the ZeroCost StarDist notebook
print(BOLD+UNDERLINE+'You do not have GPU access.'+END)
print('Did you change your runtime ?')
print('If the runtime setting is correct then Google did not allocate a GPU for your session')
print('Expect slow performance. To access GPU try reconnecting later')
use_GPU=False
else:
print(BOLD+UNDERLINE+"You have access to the GPU."+END+"\nDetails are:")
print("*************************************************")
!nvidia-smi
use_GPU=True

print("*************************************************")
print("Libraries imported and configured")
代码
文本
[ ]
import os
#@markdown ###Step 4: Enter Directory path containing the images:
#@markdown ##### Existing Masks directory will be deleted. (Does not read images in subfolders)
Input_Directory = "/content/gdrive/MyDrive/test_imgs" #@param {type:"string"}
input_dir = os.path.join(Input_Directory, "") #adds separator to the end regardless if path has it or not

#@markdown ###Optional: Enter image extension here to read only files/images of specified extension (.tif,.jpg..):
#@markdown ###### Leave empty if not specifying anything
image_format = "tif" #@param {type:"string"}

##@markdown ###Tick if image is RGB:
#RGB= False #@param {type:"boolean"}
#rgb=RGB
save_dir = input_dir+"Masks/"
if not os.path.exists(save_dir):
os.makedirs(save_dir)
else:
print("Existing Mask Directory found. Deleting it.")
shutil.rmtree(save_dir)

#@markdown ##### Save Directory will be created in the input path under Masks

##@markdown ###Advanced Parameters
#Use_Default_Advanced_Parameters = True #@param {type:"boolean"}


# r=root, d=directories, f = files
files=[]

for r, d, f in os.walk(input_dir):
for fil in f:
if (image_format):
if fil.endswith(image_format):
files.append(os.path.join(r, fil))
else:
files.append(os.path.join(r, fil))
break #only read the root directory; can change this to include levels
if(len(files)==0):
print("Number of images loaded: %d." %(len(files)))
print("Cannot read image files. Check if folder has images")
else:
print("Number of images loaded: %d." %(len(files)))
代码
文本
[ ]
from cellpose import io
import random
import matplotlib.pyplot as plt
#@markdown ###Step 5: Read and Load all the images
#@markdown #####A random image will be shown as an example with each channel separated. If it is a single channel image, only the one channel will be shown
#imgs = [imread(f) for f in files]

imgs=[] #store all images
#Read images
for f in files:
im=io.imread(f)
n_dim=len(im.shape) #shape of image
dim=im.shape #dimensions of image
channel=min(dim) #channel will be dimension with min value usually
channel_position=dim.index(channel)
#if no of dim is 3 and channel is first index, swap channel to last index
if n_dim==3 and channel_position==0:
#print(dim)
im=im.transpose(1,2,0)
dim=im.shape
#print("Shape changed")
#print(dim)
imgs.append(im)

nimg = len(imgs)
print("No of images loaded are: ", nimg)

print("Example Image:")

random_idx = random.choice(range(len(imgs)))
x=imgs[random_idx]
n_dim=len(x.shape)
file_name=os.path.basename(files[random_idx])
print(file_name+" has "+str(n_dim)+" dimensions/s")
if n_dim==3:
channel_image=x.shape[2]
fig, axs = plt.subplots(1, channel_image,figsize=(12,5))
print("Image: %s" %(file_name))
for channel in range(channel_image):
axs[channel].imshow(x[:,:,channel])
axs[channel].set_title('Channel '+str(channel+1),size=5)
axs[channel].axis('off')
fig.tight_layout()
elif n_dim==2:
print("One Channel")
plt.imshow(x)
else:
print("Channel number invalid or dimensions wrong. Image shape is: "+str(x.shape))
代码
文本

运行 Cellpose

Step 6. 根据想要分割的内容选择模型。

如果有细胞质标记,则选择细胞质以分割整个细胞;选择细胞核以分割细胞核;如果您使用的是细胞质模型并且有核通道,这也会对分割有帮助。

代码
文本
[ ]
#updated the models
#@markdown ## Choose a model
#@markdown 'cyto' and 'nuclei' are the original cellpose models for cytoplasm and nuclei.
#@markdown The other models are from the Cellpose 2.0 paper (please cite that paper if you use them):
#@markdown 'cyto2' was trained including user submissions,
#@markdown 'tissuenet' was trained on the tissuenet data set, and
#@markdown 'livecell' was trained on the livecell data set,

Model_Choice = "cyto" #@param ["cyto", "nuclei", "cyto2", "tissuenet", "livecell"]
model_choice=Model_Choice

print("Using model ",model_choice)

#@markdown If the image has only one channel, leave it as 0
Channel_for_segmentation="0" #@param[0,1,2,3]
segment_channel=int(Channel_for_segmentation)

# @markdown ###If you choose cyto or tissuenet, tick if you have a nuclear channel
Use_nuclear_channel= False #@param {type:"boolean"}
Nuclear_channel="3" #@param[1,2,3]
nuclear_channel=int(Nuclear_channel)

#@markdown ### Diameter of cell (pixels):
#@markdown #### Enter 0 if you don't know and cellpose will estimate it automatically. You can define this later as well.
Diameter = 0#@param {type:"number"}
diameter=Diameter

# define CHANNELS to run segementation on
# grayscale=0, R=1, G=2, B=3
# channels = [cytoplasm, nucleus]
# if NUCLEUS channel does not exist, set the second channel to 0
# channels = [0,0]
# IF ALL YOUR IMAGES ARE THE SAME TYPE, you can give a list with 2 elements
# channels = [0,0] # IF YOU HAVE GRAYSCALE
# channels = [2,3] # IF YOU HAVE G=cytoplasm and B=nucleus
# channels = [2,1] # IF YOU HAVE G=cytoplasm and R=nucleus


model_type = model_choice


# channels = [cytoplasm, nucleus]
if model_choice not in "Nucleus":
if Use_nuclear_channel:
channels=[segment_channel,nuclear_channel]
else:
channels=[segment_channel,0]
else: #nucleus
channels=[segment_channel,0]




# DEFINE CELLPOSE MODEL
# model_type='cyto' or model_type='nuclei'
model = models.Cellpose(gpu=use_GPU, model_type=model_type)

# define CHANNELS to run segementation on
# grayscale=0, R=1, G=2, B=3
# channels = [cytoplasm, nucleus]
# if NUCLEUS channel does not exist, set the second channel to 0
# channels = [0,0]
# IF ALL YOUR IMAGES ARE THE SAME TYPE, you can give a list with 2 elements
# channels = [0,0] # IF YOU HAVE GRAYSCALE
# channels = [2,3] # IF YOU HAVE G=cytoplasm and B=nucleus
# channels = [2,1] # IF YOU HAVE G=cytoplasm and R=nucleus

# or if you have different types of channels in each image
#channels = [[2,3], [0,0], [0,0]]

# if diameter is set to None, the size of the cells is estimated on a per image basis
# you can set the average cell `diameter` in pixels yourself (recommended)
# diameter can be a list or a single number for all images
if diameter is 0:
diameter = None
print("Diameter is set to None. The size of the cells will be estimated on a per image basis")
代码
文本

Step 7.在图像上测试 cellpose,且根据图像调整参数。

可以通过细胞分割的初步结果,调整参数,并寻找符合分割目的的最佳参数组合。

Flow_threshold 参数是每个掩码的流的最大允许误差。默认值为 0.4。

如果 cellpose 返回的分割过粗,不如预期,则增加此阈值

如果 cellpose 返回的分割过细,出现了错误分割,则降低此阈值。

Cell Probability Threshold 确定检测到的物体是细胞的概率。默认值为 0.0。

如果 cellpose 返回的分割数量不如您预期,或者分割太少,则降低此阈值

如果 cellpose 返回的分割过细,尤其是来自暗淡/昏暗区域的分割,则增加此阈值。

如果您不知道细胞的直径,或者细胞的直径不同,请在Diameter框中输入 0,cellpose 将自动估算直径

有关参数的更多信息:https://cellpose.readthedocs.io/_/downloads/en/latest/pdf/

代码
文本
[ ]
from skimage.util import img_as_ubyte

Image_Number = 1#@param {type:"number"}
Image_Number-=1 #indexing starts at zero
#print(Image_Number)
Diameter = 0#@param {type:"number"}
#Flow_Threshold=0.4#@param {type:"number"}
Flow_Threshold = 0.3 #@param {type:"slider", min:0.1, max:1.1, step:0.1}
flow_threshold=Flow_Threshold

#Cell_Probability_Threshold=-5#@param {type:"number"}
#Using slider to restrict values
Cell_Probability_Threshold=-1 #@param {type:"slider", min:-6, max:6, step:1}
cellprob_threshold=Cell_Probability_Threshold


diameter=Diameter
if diameter is 0:
diameter = None
if Image_Number is -1:
Image_Number=0
#print("Image_Number is set to zero, opening first image.")
try:
image = imgs[Image_Number]
except IndexError as i:
print("Image number does not exist",i)
print("Actual no of images in folder: ",len(imgs))
print("Image: %s" %(os.path.splitext(os.path.basename(files[Image_Number]))[0]))
img1=imgs[Image_Number]

import cv2

masks, flows, styles, diams = model.eval(img1, diameter=diameter, flow_threshold=flow_threshold,cellprob_threshold=cellprob_threshold, channels=channels)



# DISPLAY RESULTS
from cellpose import plot
maski = masks
flowi = flows[0]

#convert to 8-bit if not so it can display properly in the graph
if img1.dtype!='uint8':
img1=img_as_ubyte(img1)

fig = plt.figure(figsize=(24,8))
plot.show_segmentation(fig, img1, maski, flowi, channels=channels)
plt.tight_layout()
plt.show()
代码
文本

使用 CELLPOSE 分割细胞

上面定义的值将用于细胞分割,且得到的结果将自动保存。

代码
文本
[ ]
#@markdown ### **Step 8. Run Cellpose on folder of images**

#@markdown ###Tick if you want to save the flow image/s:
Save_Flow= True #@param {type:"boolean"}
#@markdown ##### *Flow image will be resized when saved
save_flow=Save_Flow

print("Running segmentation on channel %s" %(segment_channel))
print("Using the model: ",model_choice)
if diameter is None:
print("Diameter will be estimated from the image/s")
else:
print(f"Cellpose will use a diameter of {diameter}")

print(f"Using a flow threshold of: {flow_threshold} and a cell probability threshold of: {cellprob_threshold}")

#if too many images, it will lead to memory error.
#will evaluate on a per image basis
#masks, flows, styles, diams = model.eval(imgs, diameter=diameter, flow_threshold=flow_threshold,cellprob_threshold=cellprob_threshold, channels=channels)


#save images in folder with the diameter value used in cellpose
print("Segmentation Done. Saving Masks and flows now")
print("Save Directory is: ",save_dir)
if (not os.path.exists(save_dir)):
os.mkdir(save_dir)

if save_flow:
print("Saving Flow")
flows_save_dir=save_dir+"flows"+os.sep
print("Save Directory for flows is: ",flows_save_dir)
if (not os.path.exists(flows_save_dir)):
os.mkdir(flows_save_dir)


for img_idx, img in enumerate(imgs):
file_name=os.path.splitext(os.path.basename(files[img_idx]))[0]
print("\nSegmenting: ",file_name)
mask, flow, style, diam = model.eval(img, diameter=diameter, flow_threshold=flow_threshold,cellprob_threshold=cellprob_threshold, channels=channels)
#save images in folder with the diameter value used in cellpose
print("Segmentation complete . Saving Masks and flows")
#Output name for masks
mask_output_name=save_dir+"MASK_"+file_name+".tif"
#Save mask as 16-bit in case this has to be used for detecting than 255 objects
mask=mask.astype(np.uint16)
#Save flow as 8-bit
skimage.io.imsave(mask_output_name,mask, check_contrast=False)
if save_flow:
#Output name for flows
flow_output_name=flows_save_dir+"FLOWS_"+file_name+".tif"
#Save as 8-bit
flow_image=flow[0].astype(np.uint8)
skimage.io.imsave(flow_output_name,flow_image, check_contrast=False)

#Save parameters used in Cellpose
parameters_file=save_dir+"Cellpose_parameters_used.txt"
outFile=open(parameters_file, "w")
outFile.write("CELLPOSE PARAMETERS\n")
outFile.write("Model: "+model_choice+"\n")
if diameter == 0:
diameter = "Automatically estimated by cellpose"
outFile.write("Diameter: "+str(diameter)+"\n")
outFile.write("Flow Threshold: "+str(flow_threshold)+"\n")
outFile.write("Cell probability Threshold: "+str(cellprob_threshold)+"\n")
outFile.close()
print("\nSegmentation complete and files saved")
代码
文本

如何使用 FIJI 从掩码或标签图中提取 ROI

分割结果将保存为 16 位标签图像,其中每个单元格/ROI 都有不同的颜色或标签。如果您使用的是 ImageJ/FIJI 并希望将其转换为 ROI Manager 的 ROI,则有几种转换为 ROI 的选项:

SCF 插件(更新站点:https://sites.imagej.net/SCF-MPI-CBG/ )。安装插件后,转到 SCF-> 分割 -> LabelMap 到 ROI Manager (2D)。这应该会在 ROI Manager 中生成 ROI

另一个非常好的插件是LabelsToROIs。它有一些很好的功能可以调整 ROI 的大小并生成测量值。

将文件另存为 *.npy

如果您想保存文件以便在 Cellpose GUI 中查看它,您可以将其另存为 colab 中的 *_seg.npy 文件,您可以在 GUI 中下载并打开它。

代码
文本
[ ]
#@markdown ### **Run this cell to save output of the model as an npy file**
from cellpose import io

#save output of model eval to be loaded in GUI
io.masks_flows_to_seg(imgs, masks, flows, diams, files, channels)
Acknowledgments:

Thanks to Lior Pytowski from University of Oxford for testing this notebook out and giving some really good suggestions
代码
文本

五、使用CELLPOSE进行细胞分割-1

代码
文本
[ ]
import numpy as np
import time, os, sys
from urllib.parse import urlparse
import matplotlib.pyplot as plt
import matplotlib as mpl
%matplotlib inline
mpl.rcParams['figure.dpi'] = 300
from cellpose import utils, io

# I will download images from website
urls = ['http://www.cellpose.org/static/images/img02.png',
'http://www.cellpose.org/static/images/img03.png',
'http://www.cellpose.org/static/images/img05.png']
files = []
for url in urls:
parts = urlparse(url)
filename = os.path.basename(parts.path)
if not os.path.exists(filename):
sys.stderr.write('Downloading: "{}" to {}\n'.format(url, filename))
utils.download_url_to_file(url, filename)
files.append(filename)

# REPLACE FILES WITH YOUR IMAGE PATHS
# files = ['img0.tif', 'img1.tif']

# view 1 image
img = io.imread(files[-1])
plt.figure(figsize=(2,2))
plt.imshow(img)
plt.axis('off')
plt.show()
代码
文本
[ ]
# RUN CELLPOSE

from cellpose import models, io

# DEFINE CELLPOSE MODEL
# model_type='cyto3' or model_type='nuclei'
model = models.Cellpose(gpu=False, model_type='cyto3')

# define CHANNELS to run segementation on
# grayscale=0, R=1, G=2, B=3
# channels = [cytoplasm, nucleus]
# if NUCLEUS channel does not exist, set the second channel to 0
# channels = [0,0]
# IF ALL YOUR IMAGES ARE THE SAME TYPE, you can give a list with 2 elements
# channels = [0,0] # IF YOU HAVE GRAYSCALE
# channels = [2,3] # IF YOU HAVE G=cytoplasm and B=nucleus
# channels = [2,1] # IF YOU HAVE G=cytoplasm and R=nucleus

# or if you have different types of channels in each image
channels = [[2,3], [0,0], [0,0]]

# if diameter is set to None, the size of the cells is estimated on a per image basis
# you can set the average cell `diameter` in pixels yourself (recommended)
# diameter can be a list or a single number for all images

# you can run all in a list e.g.
# >>> imgs = [io.imread(filename) in for filename in files]
# >>> masks, flows, styles, diams = model.eval(imgs, diameter=None, channels=channels)
# >>> io.masks_flows_to_seg(imgs, masks, flows, diams, files, channels)
# >>> io.save_to_png(imgs, masks, flows, files)

# or in a loop
for chan, filename in zip(channels, files):
img = io.imread(filename)
masks, flows, styles, diams = model.eval(img, diameter=None, channels=chan)

# save results so you can load in gui
io.masks_flows_to_seg(img, masks, flows, filename, channels=chan, diams=diams)

# save results as png
io.save_to_png(img, masks, flows, filename)
代码
文本
[ ]
# DISPLAY RESULTS
from cellpose import plot

fig = plt.figure(figsize=(12,5))
plot.show_segmentation(fig, img, masks, flows[0], channels=chan)
plt.tight_layout()
plt.show()
代码
文本

六、在Colab中使用GPU运行Cellpose

代码
文本
[ ]
!pip install "opencv-python-headless<4.3"
!pip install cellpose
代码
文本
[ ]
!nvcc --version
!nvidia-smi

import os, shutil
import numpy as np
import matplotlib.pyplot as plt
from cellpose import core, utils, io, models, metrics
from glob import glob

use_GPU = core.use_gpu()
yn = ['NO', 'YES']
print(f'>>> GPU activated? {yn[use_GPU]}')
代码
文本
Deep Learning
notebook
cellpose
python
Deep Learningnotebookcellposepython
已赞1
推荐阅读
公开
AI4S Cup -LLM挑战赛-大模型提取“基因-疾病-药物”知识图谱-解决方案-你好晚安-训练代码
AI4SAI4SCUP-LLMKG
AI4SAI4SCUP-LLMKG
G17
发布于 2024-04-25
1 赞1 转存文件
公开
pysodb:可能是最好的空间多组学数据处理入门
空间组学生物信息学数据分析Pipeline
空间组学生物信息学数据分析Pipeline
zhouziyi
发布于 2023-08-03
2 赞2 转存文件