gpt4 book ai didi

python - 在 Python 中以一定角度(旋转)绘制文本

转载 作者:太空宇宙 更新时间:2023-11-04 00:32:48 27 4
gpt4 key购买 nike

我正在将文本绘制到 numpy 上Python 中的数组图像(使用自定义字体)。目前我正在将图像转换为 PIL,绘制文本,然后再转换回 numpy 数组。

import numpy as np
import cv2

from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont

char_image = np.zeros((200, 300, 3), np.uint8)

# convert to pillow image
pillowImage = Image.fromarray(char_image)
draw = ImageDraw.Draw(pillowImage)

# add chars to image
font = ImageFont.truetype("arial.ttf", 32)
draw.text((50, 50), 'ABC', (255, 255, 255), font=font)

# convert back to numpy array
char_image = np.array(pillowImage, np.uint8)

# show image on screen
cv2.imshow('myImage', char_image)
cv2.waitKey(0)

有没有办法在给定的角度上绘制文本,即。 33 度?

不能在绘制完文本后旋转图像

最佳答案

您可以使用 PIL 绘制旋转文本。我建议将文本绘制到空白图像上,旋转该图像,然后将旋转后的图像粘贴到主图像中。像这样的东西:

代码:

def draw_rotated_text(image, angle, xy, text, fill, *args, **kwargs):
""" Draw text at an angle into an image, takes the same arguments
as Image.text() except for:

:param image: Image to write text into
:param angle: Angle to write text at
"""
# get the size of our image
width, height = image.size
max_dim = max(width, height)

# build a transparency mask large enough to hold the text
mask_size = (max_dim * 2, max_dim * 2)
mask = Image.new('L', mask_size, 0)

# add text to mask
draw = ImageDraw.Draw(mask)
draw.text((max_dim, max_dim), text, 255, *args, **kwargs)

if angle % 90 == 0:
# rotate by multiple of 90 deg is easier
rotated_mask = mask.rotate(angle)
else:
# rotate an an enlarged mask to minimize jaggies
bigger_mask = mask.resize((max_dim*8, max_dim*8),
resample=Image.BICUBIC)
rotated_mask = bigger_mask.rotate(angle).resize(
mask_size, resample=Image.LANCZOS)

# crop the mask to match image
mask_xy = (max_dim - xy[0], max_dim - xy[1])
b_box = mask_xy + (mask_xy[0] + width, mask_xy[1] + height)
mask = rotated_mask.crop(b_box)

# paste the appropriate color, with the text transparency mask
color_image = Image.new('RGBA', image.size, fill)
image.paste(color_image, mask)

它是如何工作的:

  1. 创建一个透明蒙版。
  2. 将文本绘制到 mask 上。
  3. 旋转蒙版,裁剪到合适的大小。
  4. 使用包含文本的旋转透明蒙版,将所需颜色粘贴到图像中。

测试代码:

import numpy as np

from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont

char_image = np.zeros((100, 150, 3), np.uint8)

# convert to pillow image
pillowImage = Image.fromarray(char_image)

# draw the text
font = ImageFont.truetype("arial.ttf", 32)
draw_rotated_text(pillowImage, 35, (50, 50), 'ABC', (128, 255, 128), font=font)

pillowImage.show()

结果:

Results Image

关于python - 在 Python 中以一定角度(旋转)绘制文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45179820/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com