In the realm of image processing, adding text to an image is a common task that can be useful in various applications, from watermarking photos to creating memes. Python, with its rich ecosystem of libraries, makes this task straightforward, especially with the help of OpenCV. OpenCV is an open-source computer vision and machine learning software library that offers a wide range of functionalities, including operations on images and videos. In this blog post, we'll guide you through the process of writing text on an image using Python and OpenCV.
Before we dive into the code, make sure you have Python installed on your system. You'll also need to install OpenCV. If you haven't done so, you can install it using pip, Python's package installer, with the following command:
pip install opencv-python
The process of writing text on an image with OpenCV is simple and can be broken down into a few steps:
Let's go through each step with code examples.
To load an image, we use the cv2.imread()
function. Provide the path to your image as the argument.
import cv2
# Load the image
image = cv2.imread('path/to/your/image.jpg')
Before adding text, we need to specify a few details like the text content, font, scale (size), color, and position on the image.
# Text settings
text = "Hello, OpenCV!"
font = cv2.FONT_HERSHEY_SIMPLEX
fontScale = 1
color = (255, 0, 0) # Blue in BGR
position = (50, 50) # x, y position
thickness = 2
Now, we use the cv2.putText()
function to add text to the image. This function requires the image, text content, position, font, font scale, color, and thickness of the text.
# Add text
cv2.putText(image, text, position, font, fontScale, color, thickness, cv2.LINE_AA)
After adding the text, you can either save the image to a file using cv2.imwrite()
or display it using cv2.imshow()
.
To save the image:
# Save the image
cv2.imwrite('path/to/save/image.jpg', image)
To display the image:
# Display the image
cv2.imshow('Image with Text', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
Adding text to an image using Python and OpenCV is a straightforward task that can be accomplished in just a few lines of code. Whether you're working on a personal project or a professional application, this technique is incredibly useful for a wide range of purposes. Remember, the key steps involve loading the image, specifying the text details, using cv2.putText()
to add the text, and finally, saving or displaying the image. With this knowledge, you're now equipped to enhance your images with textual information using Python and OpenCV.