I've been through several questions and unsatisfying answers about this. Pillow can use ttf fonts but draw.textsize(text,font) and font.getsize(text) return the same wrong dimensions.
opencv.getTextSize is correct, but only offers a few fonts.
I got precise results by drawing text with pillow on an image dimensioned larger than the approximate size it tells to need, in step 2 converting that image to an opencv pixel array and in step 3 cropping it precisely.
That has two problems:
- It's too slow. So is there a fast way to extract a central part of an array cutting off boundaries with all white pixels or everything under a threshold value?
- Even knowing the exact dimensions, drawing a text at the origin computed with the exact textsize within a larger box, ie centering a digit in a square, it's still not drawn centered. I assume pillow counts empty pixels for kerning or such font related dimensions into the area textsize or getsize returns. So ultimately this might also be a thing about specific bad fonts, but I get the same wrong results for Arial, Arialbd, Times New Roman or Cambria, to name jus a few.
Is there any chance to get this precise? In the end I'd like to produce boxes quite narrow bounding an inner number (for math related learning/demo video). It's not just to be pedantic, but fiddling with manual corrections would make generating such videos a nightmare, the base tools I now build up should be as precise as possible.
Edit: In my case the texts are numbers, and they neither have ascenders nor descenders. I also observe the horizontal centering works okay, it's just the vertical position is too low. I'll see what I get when taking the offsets into account.
