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

S Andrew :

I have a project of opencv where on the frame I am displaying some text using cv2.putText(). Currently it looks like below:

enter image description here

As you can see on the top left corner, the text is present but its not clearly visible. Is it possible to make background black so that the text will then appear good. Something like below image:

enter image description here

Even if the black background covers till right side of the frame, that is also fine. Below is the code I am using for putting text on frame:

cv2.putText(frame, "Data: N/A", (5, 30), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 0, 255), 1)
cv2.putText(frame, "Room: C1", (5, 60), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 0, 255), 1)

Is there any prebuilt method/library available in opencv which can do this. Can anyone please suggest a good way?

nathancy :

There's no prebuilt method but a simple appraoch is to use cv2.rectangle + cv2.putText. All you need to do is to draw the black rectangle on the image followed by placing the text. You can adjust the x,y,w,h parameters depending on how large/small you want the rectangle. Here's an example:

Input image:

enter image description here

Result:

enter image description here

import cv2
import numpy as np

# Load image, define rectangle bounds
image = cv2.imread('1.jpg')
x,y,w,h = 0,0,175,75

# Draw black background rectangle
cv2.rectangle(image, (x, x), (x + w, y + h), (0,0,0), -1)

# Add text
cv2.putText(image, "THICC flower", (x + int(w/10),y + int(h/2)), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255,255,255), 2)

# Display
cv2.imshow('image', image)
cv2.waitKey()

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=297543&siteId=1