import cv2 import numpy as np from PIL import Image, ImageDraw, ImageFont # 视频分辨率 VIDEO_WIDTH = 1920 VIDEO_HEIGHT = 1080 # 文本属性 FONT_SIZE = int(VIDEO_HEIGHT * 0.75) FONT_COLOR = (255, 255, 255) # 背景属性 BACKGROUND_COLOR = (255,0,0,255) # 文本滚动速度 SCROLL_SPEED = int(VIDEO_WIDTH / 100) # 跑马灯文本 MARQUEE_TEXT = "Hello World! This is a marquee text." # 创建视频输出对象 fourcc = cv2.VideoWriter_fourcc(*'mp4v') video_writer = cv2.VideoWriter("E:/Template/word/marquee.mp4", fourcc, 25, (VIDEO_WIDTH, VIDEO_HEIGHT)) # 创建画布 canvas = Image.new('RGB', (VIDEO_WIDTH, VIDEO_HEIGHT), BACKGROUND_COLOR) draw = ImageDraw.Draw(canvas) # 加载字体 font = ImageFont.truetype("arial.ttf", FONT_SIZE) # 计算文本宽度 text_width, text_height = draw.textsize(MARQUEE_TEXT, font=font) # 文本起始位置 x = VIDEO_WIDTH # 循环生成帧并写入视频文件 while x > -text_width: # 添加文本 draw.text((x, (VIDEO_HEIGHT - text_height) / 2), MARQUEE_TEXT, font=font, fill=FONT_COLOR) # 转换图像格式 frame = np.array(canvas) frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR) # 写入视频文件 video_writer.write(frame) # 清空画布 draw.rectangle((0, 0, VIDEO_WIDTH, VIDEO_HEIGHT), fill=BACKGROUND_COLOR) # 更新文本位置 x -= SCROLL_SPEED # 释放资源 video_writer.release() 优化代码,加入导出进度条百分比
时间: 2024-04-03 10:30:55 浏览: 181
python 3.74 运行import numpy as np 报错lib\site-packages\numpy\__init__.py
import cv2
import numpy as np
from PIL import Image, ImageDraw, ImageFont
# 视频分辨率
VIDEO_WIDTH = 1920
VIDEO_HEIGHT = 1080
# 文本属性
FONT_SIZE = int(VIDEO_HEIGHT * 0.75)
FONT_COLOR = (255, 255, 255)
# 背景属性
BACKGROUND_COLOR = (255,0,0,255)
# 文本滚动速度
SCROLL_SPEED = int(VIDEO_WIDTH / 100)
# 跑马灯文本
MARQUEE_TEXT = "Hello World! This is a marquee text."
# 创建视频输出对象
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
video_writer = cv2.VideoWriter("E:/Template/word/marquee.mp4", fourcc, 25, (VIDEO_WIDTH, VIDEO_HEIGHT))
# 创建画布
canvas = Image.new('RGB', (VIDEO_WIDTH, VIDEO_HEIGHT), BACKGROUND_COLOR)
draw = ImageDraw.Draw(canvas)
# 加载字体
font = ImageFont.truetype("arial.ttf", FONT_SIZE)
# 计算文本宽度
text_width, text_height = draw.textsize(MARQUEE_TEXT, font=font)
# 文本起始位置
x = VIDEO_WIDTH
# 循环生成帧并写入视频文件
while x > -text_width:
# 添加文本
draw.text((x, (VIDEO_HEIGHT - text_height) / 2), MARQUEE_TEXT, font=font, fill=FONT_COLOR)
# 转换图像格式
frame = np.array(canvas)
frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
# 写入视频文件
video_writer.write(frame)
# 清空画布
draw.rectangle((0, 0, VIDEO_WIDTH, VIDEO_HEIGHT), fill=BACKGROUND_COLOR)
# 更新文本位置
x -= SCROLL_SPEED
# 导出进度条百分比
progress = int((x / VIDEO_WIDTH) * 100)
print("Exporting video: {}%".format(progress), end='\r')
# 释放资源
video_writer.release()
阅读全文