# Overlay texts on images#

After labeling elements in an image, one may want to see some text over each element describing, for example, its area, or simply the label number of that element. One way to do that is using the matplotlib axes annotate function.

Previous related topics:

from skimage import io
import matplotlib.pyplot as plt
from skimage import measure


We first open a labeled image and plot it with matplotlib.

# Load data

# Visualization
fig, axs = plt.subplots(1, 1, figsize=(15,15))
axs.imshow(labeled_blobs, cmap='nipy_spectral')

<matplotlib.image.AxesImage at 0x7f87c0430340>


Then, we analyze the labeled elements and get their properties.

# Analyse objects
regionprops = measure.regionprops(labeled_blobs)


Finally, we use the axs.annotate() function with the following arguments:

• text: the string to be displayed;

• xy: the coordinates to plot the text;

• fontsize: the size of the text;

• color: the color of the text;

# Visualization
fig, axs = plt.subplots(1, 1, figsize=(15,15))
axs.imshow(labeled_blobs, cmap='nipy_spectral')

# Plot label number over each element (iterate over each element)
for element in regionprops:
# Get element centroid (x, y)
element_centroid = (element.centroid[1], element.centroid[0])

# Get element label and convert it to string
element_label = str(element.label)

# Plot label number at the coordinates of that element centroid
axs.annotate(text = element_label, xy = element_centroid, fontsize = 18, color = 'white')


As mentioned before, we can write quantitative measurements on top of each element, like its area.

# Visualization
fig, axs = plt.subplots(1, 1, figsize=(15,15))
axs.imshow(labeled_blobs, cmap='nipy_spectral')

# Plot label number over each element (iterate over each element)
for element in regionprops:
# Get element centroid (x, y)
element_centroid = (element.centroid[1], element.centroid[0])

# Get element label and convert it to string
element_area = str(element.area)

# Plot label number at the coordinates of that element centroid
axs.annotate(text = str(element_area) + " px", xy = element_centroid, fontsize = 18, color = 'white')