python3.8 图片加字
时间: 2023-11-26 14:04:45 浏览: 82
以下是一些使用Python 3.8进行图像处理和添加文字的示例代码:
1. 使用Pillow库加载图片并添加文字
```python
from PIL import Image, ImageDraw, ImageFont
# Load image
image = Image.open('example.jpg')
# Create draw object
draw = ImageDraw.Draw(image)
# Define font and text
font = ImageFont.truetype('arial.ttf', size=36)
text = 'Hello World!'
# Get text size
text_size = draw.textsize(text, font=font)
# Calculate text position
x = (image.width - text_size[0]) // 2
y = (image.height - text_size[1]) // 2
# Add text to image
draw.text((x, y), text, font=font, fill=(255, 255, 255))
# Save image
image.save('example_with_text.jpg')
```
2. 使用OpenCV库加载图片并添加文字
```python
import cv2
# Load image
image = cv2.imread('example.jpg')
# Define font and text
font = cv2.FONT_HERSHEY_SIMPLEX
text = 'Hello World!'
# Get text size
text_size, _ = cv2.getTextSize(text, font, 1, 2)
# Calculate text position
x = (image.shape[1] - text_size[0]) // 2
y = (image.shape[0] - text_size[1]) // 2
# Add text to image
cv2.putText(image, text, (x, y), font, 1, (255, 255, 255), 2, cv2.LINE_AA)
# Save image
cv2.imwrite('example_with_text.jpg', image)
```
阅读全文