Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resize text for cv2.putText according to the image size in OpenCV, Python?

Tags:

python

opencv

fontScale = 1
fontThickness = 1

# make sure font thickness is an integer, if not, the OpenCV functions that use this may crash
fontThickness = int(fontThickness)

upperLeftTextOriginX = int(imageWidth * 0.05)
upperLeftTextOriginY = int(imageHeight * 0.05)

textSize, baseline = cv2.getTextSize(resultText, fontFace, fontScale, fontThickness)
textSizeWidth, textSizeHeight = textSize

# calculate the lower left origin of the text area based on the text area center, width, and height
lowerLeftTextOriginX = upperLeftTextOriginX
lowerLeftTextOriginY = upperLeftTextOriginY + textSizeHeight

# write the text on the image
cv2.putText(openCVImage, resultText, (lowerLeftTextOriginX, lowerLeftTextOriginY), fontFace, fontScale, Color,
            fontThickness)

It seems fontScale does not scale text according to the image width and height because the text is almost in the same size for different sized images. So how can I resize the text according to the image size so that all the text could fit in the image?

like image 952
XINDI LI Avatar asked Oct 17 '18 02:10

XINDI LI


People also ask

How do I reduce font size in cv2 putText?

If you take fontScale = 1 for images with size approximately 1000 x 1000, then this code should scale your font correctly.

What is font scale in cv2?

Some of font types are FONT_HERSHEY_SIMPLEX, FONT_HERSHEY_PLAIN, , etc. fontScale: Font scale factor that is multiplied by the font-specific base size. color: It is the color of text string to be drawn. For BGR, we pass a tuple. eg: (255, 0, 0) for blue color.

How do I add text to bounding box in OpenCV?

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.


2 Answers

Here is the solution that will fit the text inside your rectangle. If your rectangles are of variable width, then you can get the font scale by looping through the potential scales and measuring how much width (in pixels) would your text take. Once you drop below your rectangle width you can retrieve the scale and use it to actually putText:

def get_optimal_font_scale(text, width):
    for scale in reversed(range(0, 60, 1)):
    textSize = cv.getTextSize(text, fontFace=cv.FONT_HERSHEY_DUPLEX, fontScale=scale/10, thickness=1)
    new_width = textSize[0][0]
    print(new_width)
    if (new_width <= width):
        return scale/10
return 1
like image 142
shabany Avatar answered Sep 17 '22 12:09

shabany


for this worked!

scale = 1 # this value can be from 0 to 1 (0,1] to change the size of the text relative to the image
fontScale = min(imageWidth,imageHeight)/(25/scale)

just keep in mind that the font type can affect the 25 constant

like image 22
Ger hashim Avatar answered Sep 16 '22 12:09

Ger hashim