python opencv根据图像大小调整cv2.putText的文本大小

时间:2018-10-17 02:32:34

标签: 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)

fontScale似乎无法根据图像的宽度和高度缩放文本,因为对于不同尺寸的图像,文本几乎具有相同的大小。那么如何根据图像大小调整文本大小,以使所有文本都适合图像?

4 个答案:

答案 0 :(得分:1)

这是将文本放入矩形内的解决方案。如果矩形的宽度可变,则可以通过遍历潜在的比例并测量文本需要多少宽度(以像素为单位)来获得字体比例。一旦降到矩形宽度以下,您就可以获取比例并将其实际用于MongoDB

putText

答案 1 :(得分:0)

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

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

如果仍有问题,请发表评论。

答案 2 :(得分:0)

为此有效!

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个常量

答案 3 :(得分:0)

我实现了一项功能,以找到文本的最佳拟合居中位置。

看看这些代码是否对您有帮助。

def findFontLocate(s_txt, font_face, font_thick, cv_bgd):
    best_scale = 1.0
    bgd_w = cv_bgd.shape[1]
    bgd_h = cv_bgd.shape[0]
    txt_rect_w = 0
    txt_rect_h = 0
    baseline = 0
    for scale in np.arange(1.0, 6.0, 0.2):
        (ret_w, ret_h), tmp_bsl = cv2.getTextSize(
            s_txt, font_face, scale, font_thick)
        tmp_w = ret_w + 2 * font_thick
        tmp_h = ret_h + 2 * font_thick + tmp_bsl
        if tmp_w >= bgd_w or tmp_h >= bgd_h:
            break
        else:
            baseline = tmp_bsl
            txt_rect_w = tmp_w
            txt_rect_h = tmp_h
            best_scale = scale
    lt_x, lt_y = round(bgd_w/2-txt_rect_w/2), round(bgd_h/2-txt_rect_h/2)
    rb_x, rb_y = round(bgd_w/2+txt_rect_w/2), round(bgd_h/2+txt_rect_h/2)-baseline
    return (lt_x, lt_y, rb_x, rb_y), best_scale, baseline

请注意,该函数接受四个参数:s_txt(要渲染的字符串),font_facefont_thickcv_bgd(ndarray格式的背景图片)


putText()时,编写如下代码:

cv2.putText(
    cv_bgd, s_txt, (lt_x, rb_y), font_face,
    best_scale, (0,0,0), font_thick, cv2.LINE_AA)