putText的用法示例
时间: 2024-01-08 22:02:43 浏览: 96
Sure! Here's an example of how to use the `putText` function in OpenCV:
```python
import cv2
import numpy as np
# Create a black image
image = np.zeros((500, 500, 3), dtype=np.uint8)
# Define the text to be displayed
text = "Hello, CSDN!"
# Choose the font type, scale, color, and thickness
font = cv2.FONT_HERSHEY_SIMPLEX
scale = 1.5
color = (255, 255, 255) # White color
thickness = 2
# Get the size of the text box
size, _ = cv2.getTextSize(text, font, scale, thickness)
# Calculate the position to place the text in the center of the image
text_x = (image.shape[1] - size[0]) // 2
text_y = (image.shape[0] + size[1]) // 2
# Draw the text on the image
cv2.putText(image, text, (text_x, text_y), font, scale, color, thickness)
# Display the image
cv2.imshow("Image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
In this example, we first create a black image using `np.zeros` with dimensions (500, 500, 3). Then we define the text to be displayed as "Hello, CSDN!". We choose a font type (`cv2.FONT_HERSHEY_SIMPLEX`), scale (1.5), color (white), and thickness (2) for the text.
Next, we use `cv2.getTextSize` to get the size of the text box. We calculate the position to place the text in the center of the image by subtracting half the width of the text from the image width and adding half the height of the text to the image height.
Finally, we use `cv2.putText` to draw the text on the image at the calculated position. The image is then displayed using `cv2.imshow`.
阅读全文