欢迎访问宙启技术站
智能推送

Python中使用OpenCV的putText()函数给图像添加中文标题的步骤和代码

发布时间:2023-12-19 06:10:07

要在图像中添加中文标题,可以使用OpenCV中的putText()函数。以下是实现的步骤和示例代码:

步骤1:导入所需库和模块

import cv2
import numpy as np
from PIL import ImageFont, ImageDraw, Image

步骤2:加载图像

image = cv2.imread("image.jpg")

步骤3:将图像从BGR格式转换为RGB格式

image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

步骤4:将图像转换为PIL Image对象

pil_image = Image.fromarray(image_rgb)

步骤5:创建一个可以用于绘制文本的font对象

font_path = "font.ttf"  # 字体文件路径
font_size = 30  # 字体大小
font = ImageFont.truetype(font_path, font_size)

步骤6:创建一个可以用于绘制文本的draw对象

draw = ImageDraw.Draw(pil_image)

步骤7:设置文本的位置和内容

text = "这是一个中文标题"
text_position = (50, 50)  # 文本位置,以左上角为原点
text_color = (255, 255, 255)  # 文本颜色,以RGB格式指定

步骤8:使用draw对象的text()方法将文本绘制到图像上

draw.text(text_position, text, font=font, fill=text_color)

步骤9:将PIL Image对象转换回OpenCV格式的图像

cv2_image = cv2.cvtColor(np.array(pil_image), cv2.COLOR_RGB2BGR)

步骤10:显示带有中文标题的图像

cv2.imshow("Image with Chinese Title", cv2_image)
cv2.waitKey(0)
cv2.destroyAllWindows()

完整的示例代码如下:

import cv2
import numpy as np
from PIL import ImageFont, ImageDraw, Image

# Step 1: Import necessary libraries and modules

# Step 2: Load the image
image = cv2.imread("image.jpg")

# Step 3: Convert the image from BGR to RGB format
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Step 4: Convert the image to a PIL Image object
pil_image = Image.fromarray(image_rgb)

# Step 5: Create a font object for drawing text
font_path = "font.ttf"  # Font file path
font_size = 30  # Font size
font = ImageFont.truetype(font_path, font_size)

# Step 6: Create a draw object for drawing text
draw = ImageDraw.Draw(pil_image)

# Step 7: Set the position and content of the text
text = "这是一个中文标题"
text_position = (50, 50)  # Text position, with (0, 0) as top-left corner
text_color = (255, 255, 255)  # Text color, specified in RGB format

# Step 8: Use the text() method of the draw object to draw the text on the image
draw.text(text_position, text, font=font, fill=text_color)

# Step 9: Convert the PIL Image object back to the OpenCV format image
cv2_image = cv2.cvtColor(np.array(pil_image), cv2.COLOR_RGB2BGR)

# Step 10: Display the image with the Chinese title
cv2.imshow("Image with Chinese Title", cv2_image)
cv2.waitKey(0)
cv2.destroyAllWindows()

这个示例代码加载名为"image.jpg"的图像,并将一个中文标题添加到图像的左上角。替换"image.jpg"为您自己的图像文件,替换字体文件路径为您自己的字体文件路径,将中文标题替换为您想要添加的文本。