In this blog, we will discuss how to write the rotated text using OpenCV-Python. OpenCV as such do not provide any function for doing this. The cv2.putText() function only draws the text at the desired location and doesn’t account for the rotation. So, let’s discuss an alternative way to do this. This approach produces almost the expected results.
Approach
Instead of directly writing the rotated text, we can first write the text at the desired location and then rotate it. Below are the steps summarized to do this.
- Create a zeros image of the desired shape
- Draw the text using cv2.putText()
- Rotate at the desired angle using cv2.warpAffine(). To know more, refer to this blog.
Below is the code for doing this using OpenCV-Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import cv2 import numpy as np # Create a zeros image img = np.zeros((400,400), dtype=np.uint8) # Specify the text location and rotation angle text_location = (100,200) angle = 30 # Draw the text using cv2.putText() font = cv2.FONT_HERSHEY_SIMPLEX cv2.putText(img, 'TheAILearner', text_location, font, 1, 255, 2) # Rotate the image using cv2.warpAffine() M = cv2.getRotationMatrix2D(text_location, angle, 1) out = cv2.warpAffine(img, M, (img.shape[1], img.shape[0])) # Display the results cv2.imshow('img',out) cv2.waitKey(0) |
Below is the output image for the 30-degree counterclockwise rotation. Here, the left image represents the original image while the right one is the rotated image.
Hope you enjoy reading.
If you have any doubts/suggestions please feel free to ask and I will do my best to help or improve myself. Good-bye until next time.