import cv2 import numpy as np import random import math def generate_table_video(output_path='rotating_table.mp4'): # 参数设置 width, height = 800, 800 fps = 30 duration_ring = 2 # 红圈停留2秒 duration_rotate = 5 # 旋转5秒 total_frames = (duration_ring + duration_rotate) * fps # 桌子属性 table_size = 400 table_color = (99, 110, 141) # BGR 格式的 #8d6e63 ring_color = (59, 59, 255) # 红色 text_color = (255, 255, 255) # 白色 # 随机选择一个角落 (0:左上, 1:右上, 2:右下, 3:左下) chosen_corner = random.randint(0, 3) corners_rel = [ (-140, -140), (140, -140), (140, 140), (-140, 140) ] target_pos = corners_rel[chosen_corner] # 视频写入器 fourcc = cv2.VideoWriter_fourcc(*'mp4v') out = cv2.VideoWriter(output_path, fourcc, fps, (width, height)) for frame_idx in range(total_frames): # 创建画布 (浅灰色背景) img = np.full((height, width, 3), (245, 242, 240), dtype=np.uint8) current_time = frame_idx / fps angle = 0 show_letters = False # 逻辑判断 if current_time < duration_ring: # 第一阶段:红圈停留 angle = 0 # 模拟闪烁效果 ring_opacity = 1.0 if (int(current_time * 4) % 2 == 0) else 0.7 else: # 第二阶段:旋转 rotate_time = current_time - duration_ring # 使用简单的缓动函数 (Ease-in-out) 模拟平滑旋转至 380 度 # t 从 0 到 1 t = rotate_time / duration_rotate # 缓动函数: 3t^2 - 2t^3 ease_t = 3 * (t**2) - 2 * (t**3) angle = ease_t * 380 if frame_idx == total_frames - 1: show_letters = True # 1. 绘制桌子 (旋转矩形) center = (width // 2, height // 2) # 计算旋转矩阵 M = cv2.getRotationMatrix2D(center, -angle, 1.0) # OpenCV 逆时针为正,所以取负 # 创建桌子图层 table_layer = np.zeros_like(img) rect_pts = np.array([ [center[0] - table_size//2, center[1] - table_size//2], [center[0] + table_size//2, center[1] - table_size//2], [center[0] + table_size//2, center[1] + table_size//2], [center[0] - table_size//2, center[1] + table_size//2] ]) # 旋转桌子顶点 ones = np.ones(shape=(len(rect_pts), 1)) pts_ones = np.hstack([rect_pts, ones]) transformed_pts = pts_ones.dot(M.T).astype(np.int32) # 绘制圆角矩形桌子 (简化为填充多边形) cv2.fillPoly(table_layer, [transformed_pts], table_color) # 叠加桌子 mask = np.any(table_layer != 0, axis=-1) img[mask] = table_layer[mask] # 2. 绘制红圈 (仅在第一阶段) if current_time < duration_ring: # 圈的位置相对于中心是不旋转的 ring_x = center[0] + target_pos[0] ring_y = center[1] + target_pos[1] cv2.circle(img, (ring_x, ring_y), 40, ring_color, 5) # 3. 绘制字母 (仅在最后一帧) if show_letters: letters = ["A", "B", "C", "D"] # 计算 380 度后的旋转矩阵 final_M = cv2.getRotationMatrix2D(center, -380, 1.0) for i, char in enumerate(letters): orig_pos = np.array([center[0] + corners_rel[i][0], center[1] + corners_rel[i][1], 1]) new_pos = final_M.dot(orig_pos) cv2.putText(img, char, (int(new_pos[0]-20), int(new_pos[1]+20)), cv2.FONT_HERSHEY_SIMPLEX, 2, text_color, 5, cv2.LINE_AA) out.write(img) out.release() print(f"视频已生成: {output_path}") if __name__ == "__main__": generate_table_video()