避免魔法数字#

在阅读代码时,我们有时会发现代码中出现一些数字,但不清楚它们的作用。然而,当我们改变这些数字时,程序突然就不能正常工作了。我们称这些数字为魔法数字。例如,你知道下面代码中的 37 是做什么用的吗?

from skimage.io import imread
from skimage.filters import gaussian, threshold_otsu
from skimage.measure import label
image = imread("../../data/BBBC007_batch/17P1_POS0013_D_1UL.tif")

# noise removal
blurred = gaussian(image, 3)

# instance segmentation
binary = blurred > threshold_otsu(blurred)
labels = label(binary)

# quantitative measurement
labels.max()
37
image = imread("../../data/BBBC007_batch/17P1_POS0013_D_1UL.tif")

# noise removal
blurred = gaussian(image, 7)

# instance segmentation
binary = blurred > threshold_otsu(blurred)
labels = label(binary)

# quantitative measurement
labels.max()
19

在开头设置配置部分#

为了避免魔法数字并使代码更易读,建议在每个脚本/笔记本的开头设置一个配置代码部分。在那里,你还可以使用注释来解释变量的含义。顺便说一下,给这些变量取一个好名字是关键。

# enter the image filename to be processed here
file_to_process = "../../data/BBBC007_batch/17P1_POS0013_D_1UL.tif"

# enter the expected radius of nuclei here, in pixel units
approximate_nuclei_radius = 3
image = imread(file_to_process)

# noise removal
blurred = gaussian(image, approximate_nuclei_radius)

# instance segmentation
binary = blurred > threshold_otsu(blurred)
labels = label(binary)

# quantitative measurement
labels.max()
37

再提一个建议:Python 允许在调用函数时指定关键字参数。使用关键字参数可以使代码更易读和理解:

blurred = gaussian(image, sigma=approximate_nuclei_radius)