|
| 1 | +import os |
| 2 | +import textwrap |
| 3 | + |
| 4 | +import cv2 |
| 5 | +from PIL import Image, ImageDraw, ImageFont |
| 6 | + |
| 7 | + |
| 8 | +def create_image(text, font, index=0, image_size=(1920, 1080), |
| 9 | + bg_color=(255, 255, 255), font_color=(0, 0, 0), |
| 10 | + save_location="./resource/tmp"): |
| 11 | + font_size = font.size |
| 12 | + # text treatment |
| 13 | + text = textwrap.wrap(text, width=font_size) |
| 14 | + # drawing text on image |
| 15 | + MAX_W, MAX_H = image_size |
| 16 | + img = Image.new('RGB', image_size, bg_color) |
| 17 | + draw = ImageDraw.Draw(img) |
| 18 | + # drawing lines in text with padding |
| 19 | + current_h, pad = MAX_H/2 - ((len(text)*font_size/2)), 10 |
| 20 | + for line in text: |
| 21 | + w, h = draw.textsize(line, font=font) |
| 22 | + draw.text(((MAX_W - w) / 2, current_h), |
| 23 | + line, font=font, fill=font_color) |
| 24 | + current_h += h + pad |
| 25 | + # saving image |
| 26 | + path = f"{save_location}/{index}.png" |
| 27 | + img.save(path) |
| 28 | + return path |
| 29 | + |
| 30 | + |
| 31 | +def get_file_content(file_name): |
| 32 | + try: |
| 33 | + file = open(file_name, 'r') |
| 34 | + lines = file.read().split('\n') |
| 35 | + return lines |
| 36 | + except Exception as e: |
| 37 | + print(e) |
| 38 | + |
| 39 | + |
| 40 | +def create_frames(images, fps=10, duration_per_frame=3): |
| 41 | + img_array = [] |
| 42 | + for filename in images: |
| 43 | + img = cv2.imread(filename) |
| 44 | + for i in range(fps*duration_per_frame): |
| 45 | + img_array.append(img) |
| 46 | + return img_array |
| 47 | + |
| 48 | + |
| 49 | +def create_video_from_frames(frames, dimensions, output_file, fps=10): |
| 50 | + try: |
| 51 | + video = cv2.VideoWriter( |
| 52 | + output_file, cv2.VideoWriter_fourcc(*'DIVX'), fps, dimensions) |
| 53 | + for frame in frames: |
| 54 | + video.write(frame) |
| 55 | + video.release() |
| 56 | + |
| 57 | + except Exception as e: |
| 58 | + print(e) |
| 59 | + |
| 60 | + |
| 61 | +def remove_temp_files(files): |
| 62 | + for file in files: |
| 63 | + os.unlink(file) |
| 64 | + |
| 65 | + |
| 66 | +if __name__ == "__main__": |
| 67 | + # create images from text |
| 68 | + dimensions = (1920, 1080) |
| 69 | + fps = 1 |
| 70 | + font_size = 50 |
| 71 | + font = ImageFont.truetype('./resource/Urbanist.ttf', font_size) |
| 72 | + sentences = get_file_content("input.txt") |
| 73 | + images = [] |
| 74 | + for idx, sentence in enumerate(sentences): |
| 75 | + imagePath = create_image( |
| 76 | + sentence, font, idx+1, image_size=dimensions) |
| 77 | + images.append(imagePath) |
| 78 | + # read all images |
| 79 | + frames = create_frames(images, fps=fps, duration_per_frame=1) |
| 80 | + create_video_from_frames(frames, dimensions, "output.mp4", fps=fps) |
| 81 | + remove_temp_files(images) |
0 commit comments