Introduce three functions: rectangle(), getTextSize(), putText()
1. Function introduction
cv2.rectangle(img, pt1, pt2, color, thickness=None, lineType=None, shift=None)
parameter | Explanation |
---|---|
img | The image to be drawn |
pt1 | The coordinates of the upper left corner of the rectangle (xmin, ymin) (x_(min), y_(min))(xm i n,andm i n) |
pt2 | The coordinates of the bottom right corner of the rectangle (xmax, ymax) (x_(max),y_(max))(xmax,andmax) |
color | The color/brightness of the rectangular border or fill |
thickness | The thickness of the rectangle border. Negative value means to fill the rectangle with color |
lineType | Line style of rectangular border |
shift | Number of decimal places in coordinates |
retval, baseLine = cv2.getTextSize(text, fontFace, fontScale, thickness)
Calculate the width and height of the text
parameter | Explanation |
---|---|
text | The text to be calculated |
fonFace | Font to use |
fontScale | Multiply the scale factor by the basic size of a specific font |
thickness | The thickness of the text line |
retval | Return value, tuple, font width and height (width, height) |
baseLine | Relative to the y coordinate of the bottom text, the height of the text is from baseLine to the top of the text |
Write text on the picture, some parameters are the same as above
parameter | Explanation |
---|---|
org | The coordinates of the lower left corner of the text (xmin, ymax) (x_(min), y_(max))(xm i n,andmax) |
bottomLeftOrigin | When True, the origin of the image is the lower left corner; otherwise, the far point of the image is the upper left corner (default) |
2. Function example
Use these three functions to draw a rectangular box and rectangular box text on the image
# -*- coding: utf-8 -*-
import numpy as np
import cv2 as cv
image = cv.imread('test.jpg')
pt1, pt2 = (423, 103), (531, 358)
text = 'Man 0.9'
fontFace = cv.FONT_HERSHEY_COMPLEX_SMALL
fontScale = 1
thickness = 1
# 绘制矩形框
cv.rectangle(image, pt1, pt2, thickness=2, color=(0, 255, 0))
# 计算文本的宽高,baseLine
retval, baseLine = cv.getTextSize(text,fontFace=fontFace,fontScale=fontScale, thickness=thickness)
# 计算覆盖文本的矩形框坐标
topleft = (pt1[0], pt1[1] - retval[1])
bottomright = (topleft[0] + retval[0], topleft[1] + retval[1])
cv.rectangle(image, (topleft[0], topleft[1] - baseLine), bottomright,thickness=-1, color=(0, 255, 0))
# 绘制文本
cv.putText(image, text, (pt1[0], pt1[1]-baseLine), fontScale=fontScale,fontFace=fontFace, thickness=thickness, color=(0,0,0))
cv.imwrite('test_.jpg', image)