-2

How can I add text to an image with a different angle? It can use OpenCV, Pillow or anything. For example, how can I print "Hello World" at 120° in an image?

1

khelwood
  • 55,782
  • 14
  • 81
  • 108
  • You can do that very easily with `wand` https://docs.wand-py.org/en/0.6.11/wand/image.html?highlight=Annotate#wand.image.BaseImage.annotate – Mark Setchell Feb 17 '23 at 08:31

1 Answers1

0

You can use the Python Imaging Library (Pillow) to add text with a different angle to an image. Here's an example code snippet to print "Hello World" at 120 degrees angle in an image:

from PIL import Image, ImageDraw, ImageFont
import math

# Open the image
image = Image.open("your_image.png")

# Create a new transparent image with the same size as the original image
overlay = Image.new('RGBA', image.size, (255, 255, 255, 0))

# Get a drawing context
draw = ImageDraw.Draw(overlay)

# Set the font and text
font = ImageFont.truetype('arial.ttf', 36)
text = "Hello World"

# Calculate the position and rotation of the text
angle = 120
radians = math.radians(angle)
width, height = draw.textsize(text, font)
x = (image.width - width) / 2
y = (image.height - height) / 2
cx, cy = x + width / 2, y + height / 2
x, y = x - cx, y - cy
x, y = x * math.cos(radians) - y * math.sin(radians), x * math.sin(radians) + y * math.cos(radians)
x, y = x + cx, y + cy

# Draw the text on the transparent image
draw.text((x, y), text, font=font, fill=(255, 255, 255, 255))

# Paste the transparent image on the original image with a given alpha value
alpha = 0.5
image = Image.alpha_composite(image, overlay)

# Save the image
image.save("output.png")

In this code, we first open the original image and create a new transparent image with the same size as the original image. Then, we get a drawing context for the transparent image, set the font and text, and calculate the position and rotation of the text based on the angle. Finally, we draw the text on the transparent image, paste the transparent image on the original image with a given alpha value, and save the output image.

Xu Qiushi
  • 1,111
  • 1
  • 5
  • 10