| | 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 |
| | duration_rotate = 5 |
| | total_frames = (duration_ring + duration_rotate) * fps |
| | |
| | |
| | table_size = 400 |
| | table_color = (99, 110, 141) |
| | ring_color = (59, 59, 255) |
| | text_color = (255, 255, 255) |
| | |
| | |
| | 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 |
| | |
| | |
| | t = rotate_time / duration_rotate |
| | |
| | ease_t = 3 * (t**2) - 2 * (t**3) |
| | angle = ease_t * 380 |
| | |
| | if frame_idx == total_frames - 1: |
| | show_letters = True |
| |
|
| | |
| | center = (width // 2, height // 2) |
| | |
| | M = cv2.getRotationMatrix2D(center, -angle, 1.0) |
| | |
| | |
| | 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] |
| |
|
| | |
| | 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) |
| |
|
| | |
| | if show_letters: |
| | letters = ["A", "B", "C", "D"] |
| | |
| | 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() |