Python OpenCV cv2 drawing rectangle with text

You can use cv2.putText() to overlay text information on top of a rectangle. For example, you can grab the contour coordinates, draw a rectangle, and put text on top of it by shifting it upwards.

x,y,w,h = cv2.boundingRect(contour)
image = cv2.rectangle(image, (x, y), (x + w, y + h), (36,255,12), 1)
cv2.putText(image, 'Fedex', (x, y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (36,255,12), 2)

You will get something like this

enter image description here


enter image description here

Maybe too late for you but we could do something like this:

x1, y1 is top left point
x2, y2 is bottom right point

# For bounding box
img = cv2.rectangle(img, (x1, y1), (x2, y2), color, 2)
 
# For the text background
# Finds space required by the text so that we can put a background with that amount of width.
(w, h), _ = cv2.getTextSize(
        label, cv2.FONT_HERSHEY_SIMPLEX, 0.6, 1)

# Prints the text.    
img = cv2.rectangle(img, (x1, y1 - 20), (x1 + w, y1), color, -1)
img = cv2.putText(img, label, (x1, y1 - 5),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.6, text_color, 1)

# For printing text
img = cv2.putText(img, 'test', (x1, y1),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255,255,255), 1)

You may need to extend your code with a function that takes your text as input, position_x, position_y ... and it will measure the size of the letters and dynamically set a rectangle width based on that.

You can use

cv2.getTextSize(text, font, font_scale, thickness)

to get how many pixels it will use and then use it to define the rectangle width.