python指定位置写字
时间: 2024-03-17 12:39:06 浏览: 73
在Python中,可以使用各种库和方法来在指定位置字。以下是一种常见的方法:
1. 使用Pillow库:
- 首先,确保已经安装了Pillow库(可以使用pip install pillow命令进行安装)。
- 导入所需的库:from PIL import Image, ImageDraw, ImageFont。
- 打开一张图片:image = Image.open("image.jpg")。
- 创建一个可绘制的对象:draw = ImageDraw.Draw(image)。
- 定义要写的文字内容和位置:text = "Hello, World!",position = (x, y)。
- 定义字体样式和大小:font = ImageFont.truetype("font.ttf", size)。
- 使用draw.text方法在指定位置写字:draw.text(position, text, font=font, fill=(r, g, b))。
- 保存修改后的图片:image.save("output.jpg")。
2. 使用OpenCV库:
- 首先,确保已经安装了OpenCV库(可以使用pip install opencv-python命令进行安装)。
- 导入所需的库:import cv2。
- 读取一张图片:image = cv2.imread("image.jpg")。
- 定义要写的文字内容和位置:text = "Hello, World!",position = (x, y)。
- 定义字体样式和大小:font = cv2.FONT_HERSHEY_SIMPLEX,font_scale = 1,color = (r, g, b),thickness = 2。
- 使用cv2.putText方法在指定位置写字:cv2.putText(image, text, position, font, font_scale, color, thickness)。
- 显示图片:cv2.imshow("Output", image),并等待按下任意键关闭窗口。
- 保存修改后的图片:cv2.imwrite("output.jpg", image)。
阅读全文
相关推荐

















