一、概述
cv2.puttext
是OpenCV库中的一种图像绘制方法,它能够在图像上绘制文字。对于需要在图片中加入文字的场景,cv2.puttext
提供了一种比较直接方便的方式。
二、函数参数
cv2.putText(img, text, org, fontFace, fontScale, color[, thickness[, lineType[, bottomLeftOrigin]]])
上述参数分别表示:
- img: 需要绘制文本的图像;
- text: 要绘制的文本内容;
- org: 绘制文本的起始点;
- fontFace: 字体类型,如
cv2.FONT_HERSHEY_SIMPLEX
、cv2.FONT_HERSHEY_PLAIN
等; - fontScale: 字体大小;
- color: 字体颜色;
- thickness: 字体粗细,默认为1;
- lineType: 线条类型,默认为
cv2.LINE_AA
; - bottomLeftOrigin: 坐标原点,默认为False,即左上角。
其中,
org
定义了文本起始位置,可以用一个元祖来表示x、y坐标,例如(10, 100)
表示x=10,y=100。
三、实现过程
下面通过几个实际的例子,来演示cv2.puttext
的使用方法。
例1:在图片中央添加文字
首先,我们创建一个黑色背景的图片,并在其中心位置添加一段黑色的文字。
import numpy as np
import cv2
# create a black background image
img = np.zeros((512, 512, 3), np.uint8)
# add text to the image
text = "Hello, cv2.puttext!"
font = cv2.FONT_HERSHEY_SIMPLEX
org = (int(img.shape[1] / 2) - 100, int(img.shape[0] / 2))
fontScale = 1
color = (0, 0, 0)
thickness = 2
lineType = cv2.LINE_AA
cv2.putText(img, text, org, font, fontScale, color, thickness, lineType)
# show the image
cv2.imshow("Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
执行上述代码,会显示出一张黑色背景,并在中央位置添加了黑色的文字“Hello, cv2.puttext!”。
例2:设置不同大小、颜色的字体
在很多场景中,我们需要在图片中添加不同大小、颜色的字体。下面的例子中,我们将在图片中央分别添加大小、颜色不同的两段文字。
import numpy as np
import cv2
# create a white background image
img = np.zeros((512, 512, 3), np.uint8)
# add first text to the image
text1 = "Hello, cv2.puttext!"
font1 = cv2.FONT_HERSHEY_SIMPLEX
org1 = (int(img.shape[1] / 2) - 150, int(img.shape[0] / 2))
fontScale1 = 2
color1 = (255, 0, 0)
thickness1 = 2
lineType1 = cv2.LINE_AA
cv2.putText(img, text1, org1, font1, fontScale1, color1, thickness1, lineType1)
# add second text to the image
text2 = "OpenCV is amazing!"
font2 = cv2.FONT_HERSHEY_SIMPLEX
org2 = (int(img.shape[1] / 2) - 200, int(img.shape[0] / 2) + 80)
fontScale2 = 1
color2 = (0, 255, 0)
thickness2 = 2
lineType2 = cv2.LINE_AA
cv2.putText(img, text2, org2, font2, fontScale2, color2, thickness2, lineType2)
# show the image
cv2.imshow("Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
执行上述代码,会显示出一张白色背景,并在中央位置分别添加了大小不同、颜色不同的两段文字。
例3:绘制阴影效果
在一些场景中,我们需要给文字添加一些阴影效果,以增强文字的清晰度。下面的例子中,我们将在图片中央添加一个带有阴影效果的文本。
import numpy as np
import cv2
# create a white background image
img = np.zeros((512, 512, 3), np.uint8)
# add text to the image with shadow effect
text = "Hello, cv2.puttext!"
font = cv2.FONT_HERSHEY_SIMPLEX
org = (int(img.shape[1] / 2) - 150, int(img.shape[0] / 2))
fontScale = 2
color = (255, 255, 255)
thickness = 2
lineType = cv2.LINE_AA
# add shadow effect first
cv2.putText(img, text, (org[0]+2, org[1]+2), font, fontScale, (0, 0, 0), thickness, lineType)
# add text to the image
cv2.putText(img, text, org, font, fontScale, color, thickness, lineType)
# show the image
cv2.imshow("Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
执行上述代码,会显示出一张白色背景,并在中央位置添加了一个带有阴影效果的文本。
四、总结
我们可以看到,cv2.puttext
是OpenCV库中一个非常实用的图像绘制方法,能够在图像上绘制出各种文字效果。在实际的开发工作中,我们可以利用cv2.puttext
快速完成文字的添加操作,从而提高开发效率。