如何根据Python OpenCV中的图像大小调整cv2.putText的文本大小?

2024-09-28 17:24:31 发布

您现在位置:Python中文网/ 问答频道 /正文

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)

看起来fontScale没有根据图像的宽度和高度缩放文本,因为对于不同大小的图像,文本的大小几乎相同。那么,如何根据图像大小调整文本大小,使所有文本都能放入图像中呢


Tags: thetext图像文本areacv2intfontface
3条回答

如果对大小约为1000 x 1000的图像使用fontScale = 1,则此代码应正确缩放字体

fontScale = (imageWidth * imageHeight) / (1000 * 1000) # Would work best for almost square images

如果您仍然有任何问题,请发表评论

以下是适合矩形内文本的解决方案。如果矩形的宽度可变,则可以通过循环潜在的比例并测量文本的宽度(以像素为单位)来获得字体比例。当您将比例降到矩形宽度以下时,您可以检索比例并使用它实际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

这一切都成功了

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)

请记住,字体类型可能会影响25常量

相关问题 更多 >