不要重复自己#

有时,我们会多次复制粘贴代码以快速处理图像。从长远来看,这种代码重复对代码质量不利,因为如果我们想要更改某些内容,就需要在多个地方进行更改,并可能忘记某些地方。因此,防止重复代码至关重要。这个软件设计原则被称为不要重复自己

import pyclesperanto_prototype as cle
image = cle.imread("../../data/BBBC007_batch/17P1_POS0013_D_1UL.tif")
labels = cle.voronoi_otsu_labeling(image, spot_sigma=3)
number_of_nuclei = labels.max()
number_of_nuclei
44.0
image = cle.imread("../../data/BBBC007_batch/20P1_POS0005_D_1UL.tif")
labels = cle.voronoi_otsu_labeling(image, spot_sigma=3)
number_of_nuclei = labels.max()
number_of_nuclei
41.0
image = cle.imread("../../data/BBBC007_batch/20P1_POS0007_D_1UL.tif")
labels = cle.voronoi_otsu_labeling(image, spot_sigma=3)
number_of_nuclei = labels.max()
number_of_nuclei
73.0

如果我们现在想看看改变上面的spot_sigma参数如何影响结果,我们需要在三个地方更改这个值。当代码变得更长时,可能会发生我们忘记在某个地方更改它的情况。

使用for循环替代代码重复#

防止代码重复的一种方法是使用for循环。

folder = "../../data/BBBC007_batch/"
files = ["17P1_POS0013_D_1UL.tif",
        "20P1_POS0005_D_1UL.tif",
        "20P1_POS0007_D_1UL.tif"]
for file in files:
    image = cle.imread(folder + file)
    labels = cle.voronoi_otsu_labeling(
                    image, 
                    spot_sigma=3)
    number_of_nuclei = labels.max()
    print(file, number_of_nuclei)
17P1_POS0013_D_1UL.tif 44.0
20P1_POS0005_D_1UL.tif 41.0
20P1_POS0007_D_1UL.tif 73.0

使用函数替代代码重复#

通过引入所谓的辅助函数,我们可以获得更大的灵活性,这些函数可以_帮助_我们完成一个专门的任务,例如计算细胞核:

def count_nuclei(image, spot_sigma=3):
    labels = cle.voronoi_otsu_labeling(
                    image, 
                    spot_sigma=spot_sigma)
    number_of_nuclei = labels.max()
    
    return number_of_nuclei
count_nuclei(cle.imread(folder + files[0]))
44.0
count_nuclei(cle.imread(folder + files[1]))
41.0
count_nuclei(cle.imread(folder + files[2]))
73.0
count_nuclei(cle.imread(folder + files[2]), spot_sigma=5)
68.0