0

I am trying to center a text horizontally and vertically with ffmpeg python but I can't seem to get it right. The mid point shifts depending on the amount of characters in the text.

How do I always center the text to the centre of the screen no matter the length of the text?

Here is my code.


v_width = 1080

v_height = 1633

def create_video():

    overlay1 = ffmpeg.input("sukuna.gif").filter("scale", 1080, -1, height = 1633 / 2)

    overlay2 = ffmpeg.input("akaza_long.mp4").filter("scale", 1080, -1, height = 1633 / 2 )

    (

    ffmpeg.input('letsgo.mp4')

    .overlay(overlay1)

    .overlay(overlay2, x = 0, y = v_height / 2)

    .drawtext(textfile = "char_names.txt", fontfile = "/storage/emulated/0/PyFiles/Helvetica-Bold.ttf", fontcolor = "yellow", bordercolor = "black", escape_text = True, start_number = 0, fontsize = "80", x = (v_width / 2) - 40, y = (v_height / 2) - 40, borderw = 4, line_spacing = 3)

    .output("newVideo.mp4")

    .run()

    )

The - 40 is for adding some extra padding to the text.

How do I go about this?

I want the below position always no matter how big or amount of characters in the text. Centred text

Already tried adding a couple of offset to the text but once the text gets longer, it loses its alignment.

1 Answers1

0

Your x and y variables are not just integers. There are supposed to be string containing an expression.

And one valid "vocabulary" of this expression is tw, which is the width of the text.

So, in your case, you could

    .drawtext(textfile = "char_names.txt", fontfile = "/storage/emulated/0/PyFiles/Helvetica-Bold.ttf", fontcolor = "yellow", bordercolor = "black", escape_text = True, start_number = 0, fontsize = "80", x = f'{v_width // 2} - tw/2', y = f'{v_height//2} - th/2', borderw = 4, line_spacing = 3)

Note that W and H are also valid vocabulary of those expressions. So you don't need those hard coded v_width and v_height. You can also, instead of expanding them in python (like I did with previous f-string, in which {v_width//2} is computed before passing the string to ffmpeg), let ffmpeg do the job, and therefore having something more adaptative and less hard coded.

    .drawtext(textfile = "char_names.txt", fontfile = "/storage/emulated/0/PyFiles/Helvetica-Bold.ttf", fontcolor = "yellow", bordercolor = "black", escape_text = True, start_number = 0, fontsize = "80", x = 'W/2 - tw/2', y = 'H/2 - th/2', borderw = 4, line_spacing = 3)
chrslg
  • 9,023
  • 5
  • 17
  • 31
  • Thanks, I am literally crying. This problem has haunted me for days. I didn't know about these vocabulary where can I read more about them? By the way, is there a vocab for center aligning the text. Something like "Sukuna Vs Akaza" gets right aligned instead of center aligned. Thanks. – Sixtus Anyanwu Feb 18 '23 at 15:59