Reputation: 21
enter image description hereThere are already a few questions, that sound quite similar to this one on stackoverflow, but their focuses are a little bit different from what I want to know.
I pasted a text on an image using ImageDraw from the Python Image Library. My question now is: Is there a way to find out the width and height of the text as a whole? For myself imagine the text to have kind of a rectangular frame. I want to get the measurements of this text-field. Can my text1 be treated like an image and can I get its size by typing in something like "width, height = text1.size"?
I have already tried to get the width, by using a ImageDraw.getwidth command, as proposed in other questions, but those solutions sadly didn't work for me.
What I want to achieve in particular is to be able to calculate, where the next text-field can be placed without overlaying the current text.
Thanks in advance for your support!
In the attached picture you can see the two ImageDraw-drawed texts, named "text" and "xyz". I want xyz to fit behind "test", even if "test" would include more letters. Therefor I need to know the width of "test".
Upvotes: 2
Views: 2793
Reputation: 207365
You can just write the same text with the same font of the same size in white on a separate canvas (black background) and then get the trimmed "bounding box" like this which is the size:
#!/usr/bin/env python3
from PIL import Image, ImageFont, ImageDraw
# Create a blank canvas
canvas = Image.new('RGB', (100,100))
# Get a drawing context
fontsize=28
draw = ImageDraw.Draw(canvas)
monospace = ImageFont.truetype("/Library/Fonts/Andale Mono.ttf",fontsize)
text = "Hello"
white = (255,255,255)
draw.text((10, 10), text, font=monospace, fill=white)
# Find bounding box
bbox = canvas.getbbox()
# Debug
print(bbox)
Output
(12, 17, 93, 36)
That means the text is (93-12) = 81 pixels wide and (36-17) = 19 pixels tall.
Upvotes: 4
Reputation: 14094
using opencv or matplotlib to read your image
img = cv2.cvtColor(cv2.imread('/home/ksooklall/q0MXd.jpg'), cv2.COLOR_BGR2RGB)
find the image location
text1 = img[950:, 50:250]
print(text1.shape)
(50, 200, 3)
Upvotes: 0