使用Python生成跑马灯视频的完整代码

  from PIL import Image, ImageDraw, ImageFont

  import cv2

  import numpy as np

  from threading import Thread

  def generate_video(text):

  # 视频分辨率

  width = 1920

  height = 1080

  # 背景颜色和字体颜色

  background_color = (255,0, 0, 255) # 红色背景

  text_color = (255, 255, 255) # 白色字体

  # 字体大小和类型

  font_size = int(height * 0.60)

  font = ImageFont.truetype('msyh.ttc', font_size)

  # 计算文本大小

  text_size = font.getsize(text)

  # 计算视频长度

  video_length = int((width + text_size[0]) / 20)

  # 创建视频写入器

  fourcc = cv2.VideoWriter_fourcc(*'mp4v')

  video_writer = cv2.VideoWriter(r'E:Templatewordmarquee.mp4', fourcc, 60, (width, height))

  def update_progress(progress):

  print('

  [{}{}] {:.2f}%'.format('#' * int(progress * 10), ' ' * (10 - int(progress * 10)), progress * 100), end='')

  def export_video():

  for i in range(video_length):

  # 创建背景图像

  img = Image.new('RGB', (width, height), background_color)

  # 添加文本

  draw = ImageDraw.Draw(img)

  x = width - i * 20

  y = int(height / 2 - text_size[1] / 2)

  draw.text((x, y), text, fill=text_color, font=font)

  # 写入视频帧

  video_writer.write(cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR))

  # 更新进度条

  update_progress(i / video_length)

  # 关闭视频写入器

  video_writer.release()

  print('

  视频导出完成!')

  # 使用多线程优化视频导出速度

  export_thread = Thread(target=export_video)

  export_thread.start()

  generate_video('这里是您要显示的文本')