Skip to content

Instantly share code, notes, and snippets.

@SurendraTamang
Created January 5, 2024 05:49
Show Gist options
  • Save SurendraTamang/14f3eb34d43d2cc952a8cdc13ef04a2e to your computer and use it in GitHub Desktop.
Save SurendraTamang/14f3eb34d43d2cc952a8cdc13ef04a2e to your computer and use it in GitHub Desktop.
Timer
import cv2
from PIL import Image, ImageDraw, ImageFont
import datetime
import numpy as np
# Constants
total_seconds = 60 # 24 hours in seconds
fps = 1 # 1 frame per second
size = (800, 600) # Frame size
font_size = 200
font_color = (255, 255, 255)
background_color = (0, 0, 0)
output_file = f"{total_seconds}_seconds_timer.mp4"
def get_text_dimensions(text_string, font):
# https://stackoverflow.com/a/46220683/9263761
ascent, descent = font.getmetrics()
text_width = font.getmask(text_string).getbbox()[2]
text_height = font.getmask(text_string).getbbox()[3] + descent
return (text_width, text_height)
# Create Video Writer
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
video = cv2.VideoWriter(output_file, fourcc, fps, size)
# Check if video writer is opened
if not video.isOpened():
raise Exception("Video writer cannot be opened")
# Function to generate each frame
def create_frame(remaining_time):
img = Image.new('RGB', size, background_color)
draw = ImageDraw.Draw(img)
# Using a TrueType font if available, otherwise the default font
try:
font = ImageFont.truetype("arial.ttf", font_size)
except IOError:
font = ImageFont.load_default(font_size)
text = str(datetime.timedelta(seconds=remaining_time))
# Measure the size of the text using the textsize method
text_width, text_height = get_text_dimensions(text, font)
position = ((size[0] - text_width) / 2, (size[1] - text_height) / 2)
draw.text(position, text, font=font, fill=font_color)
return cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
# Generate video frames
for remaining_seconds in range(total_seconds, -1, -1):
frame = create_frame(remaining_seconds)
video.write(frame)
# Release the video writer
video.release()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment