Prevent magic numbers
Contents
Prevent magic numbers#
When reading code, we sometimes find numbers in the code where it is not ovious what they do. However, when we change them, suddenly our program does not work anymore. We call these numbers magic numbers. For example, do you know what the 3
and 7
in the code below do?
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
A configuration section at the beginning#
To prevent magic numbers and to make code better readable, it is recommended to have a configuration code section at the beginning of every script / notebook. There you can also use comments to explain what variables mean. Btw. giving those variables good names is key.
# 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
One more hint: Python allows specifying keyword arguments when calling functions. When using them, code becomes easier to read and understand:
blurred = gaussian(image, sigma=approximate_nuclei_radius)