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)
Run Code Online (Sandbox Code Playgroud)
它似乎fontScale
没有根据图像的宽度和高度缩放文本,因为对于不同大小的图像,文本的大小几乎相同。那么如何根据图像大小调整文本大小,以便所有文本都适合图像?
这是将文本放入矩形内的解决方案。如果您的矩形宽度可变,那么您可以通过循环潜在的比例并测量文本将采用的宽度(以像素为单位)来获取字体比例。一旦你下降到矩形宽度以下,你就可以检索比例并使用它来实际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]
if (new_width <= width):
print(new_width)
return scale/10
return 1
Run Code Online (Sandbox Code Playgroud)
如果您拍摄fontScale = 1
的图像尺寸约为 1000 x 1000,那么此代码应该正确缩放您的字体。
fontScale = (imageWidth * imageHeight) / (1000 * 1000) # Would work best for almost square images
Run Code Online (Sandbox Code Playgroud)
如果您仍有任何问题,请发表评论。
归档时间: |
|
查看次数: |
15953 次 |
最近记录: |