乐闻世界logo
搜索文章和话题

How to make black background in cv2.putText with Python OpenCV

1个答案

1

When adding text using the cv2.putText method in the OpenCV library with Python, if you need a prominent black background around the text to improve readability, you can first draw a black rectangle behind the text using the cv2.rectangle method, and then add the text on top of this rectangle using cv2.putText.

Here is a step-by-step guide and example code:

  1. Import necessary libraries: First, import the OpenCV library, which serves as the foundation for using cv2.putText and cv2.rectangle.

  2. Read or create an image: Load an image or create a new one to display the text.

  3. Set text-related parameters: Include text content, position, font, font size, and color.

  4. Calculate text width and height: Use cv2.getTextSize to compute the text dimensions, so you know the required rectangle size for the background.

  5. Draw the rectangle: Based on the calculated text dimensions and position, use cv2.rectangle to draw a black rectangle on the image as the text background.

  6. Add text: Use cv2.putText to draw the required text on the previously drawn black rectangle.

Example code

python
import cv2 import numpy as np # Create a blank image img = np.zeros((500, 800, 3), dtype=np.uint8) # Set text-related parameters text = "Hello, OpenCV" font_face = cv2.FONT_HERSHEY_SIMPLEX font_scale = 1 thickness = 2 color = (255, 255, 255) # White text background_color = (0, 0, 0) # Black background # Get the size of the text area (text_width, text_height), _ = cv2.getTextSize(text, font_face, font_scale, thickness) # Set the text position text_x = 50 text_y = 100 # Draw a black rectangle as the background on the image cv2.rectangle(img, (text_x, text_y - text_height - 10), (text_x + text_width, text_y + 10), background_color, -1) # Add white text cv2.putText(img, text, (text_x, text_y), font_face, font_scale, color, thickness) # Display the image cv2.imshow('Text with Background', img) cv2.waitKey(0) cv2.destroyAllWindows()

This code first creates a completely black image, calculates the dimensions of the text to be added, and draws a black rectangle behind the text position. It then adds white text on this black rectangle and finally displays the image.

By doing this, you can clearly display text with a black background in the image, ensuring readability on images with different background colors.

2024年8月15日 11:51 回复

你的答案