Python OpenCV cv2 drawing rectangle with text

38,865

Solution 1

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

Solution 2

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 will it use and then use it to define the rectangle width.

Solution 3

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)
Share:
38,865
55597
Author by

55597

Updated on October 26, 2021

Comments

  • 55597
    55597 over 2 years

    I draw a rectangle on my image using

    cv2.rectangle(frame,(x,y),(x1,y1),(0,255,0),2)
    

    I would like to draw rectangles with text information on them. How do I do it? Are there any ready to use implementations available? Or should I match the top left coordinate of the rectangle and try to display a different cv2 text element with the cv2 rect element?

    Can you direct me to any code implementation/workaround?

    P.S: I don't want to use the object_detection. visualisation utils available with tf.

    enter image description here