Scikit Image - Render Text onto an Image



Rendering text onto an image refers to the process of adding text or labels to an existing image. This can be useful for annotating images, creating captions, and adding metadata to an image.

The Scikit-image library does not have a built-in function for rendering text directly onto an image. Instead, you can use its optional dependency, Matplotlib. Matplotlib is a widely used plotting library in Python that offers a wide range of functions for creating different types of plots and visualizations. Skimage itself is built on top of Matplotlib, so you can leverage Matplotlib's text-drawing capabilities to add text to images, which are processed with Skimage.

Example

Here is an example that demonstrates how to render text onto an image using Matplotlib and scikit-image (skimage) libraries.

import matplotlib.pyplot as plt
import numpy as np
from skimage import io

# Load an input image

input_image = io.imread('Images/book.jpg')

# Create a Matplotlib figure
figure = plt.figure()
figure.figimage(input_image, resize=True)

# Add text to the figure
figure.text(0, 0.99, "Tutorialspoint", fontsize=32, va="top")

# Draw the figure on the canvas
figure.canvas.draw()

# Convert the annotated figure to a NumPy array
annotated_image = np.asarray(figure.canvas.renderer.buffer_rgba())

# Close the Matplotlib figure
plt.close(figure)

# Display the annotated image (optional)
displayed_figure, axis = plt.subplots()
axis.imshow(annotated_image)
axis.set_axis_off()
axis.set_position([0, 0, 1, 1])
plt.show()

Output

render text onto image

Example

Here is another simple example that writes text on top of an image using skimage and matplotlib.

import matplotlib.pyplot as plt
import numpy as np
from skimage import io

# Load an image 
img = io.imread('Images/logo_Black.png')

# Define the text properties
text = "tutorialspoint.com"
x = 35 
y = 280 
font_size = 20
font_color = 'white'
font_weight = 'bold'

# Display the original and Outpur images
fig, axes = plt.subplots(1, 2, figsize=(10, 8))
ax = axes.ravel()

# Display the original image
ax[0].imshow(img)
ax[0].set_title('Input Image')
ax[0].axis('off')

# Display the computed Haar-like feature
ax[1].imshow(img)
# Add text to the image
ax[1].text(x, y, text, fontsize=font_size, color=font_color, weight=font_weight)
ax[1].set_title('Output Image')
ax[1].axis('off')
plt.show()

Output

logo black
Advertisements