5 Best Ways to Display Date and Time in Videos Using OpenCV Python

πŸ’‘ Problem Formulation: In video processing and surveillance applications, it is often essential to overlay the current date and time onto the video frames to know exactly when the footage was captured. For instance, consider a video input from a traffic camera. The desired output is a series of video frames with the real-time timestamp displayed on each frame, aiding in event tracking and evidence logging.

Method 1: Basic Text Overlay Using OpenCV

Add date and time as a text overlay on video frames using OpenCV’s putText() function. This method involves fetching the system’s current date and time using Python’s datetime module and then overlaying it onto each frame as it is processed by OpenCV.

Here’s an example:

import cv2
from datetime import datetime

cap = cv2.VideoCapture("input_video.mp4")

while True:
    ret, frame = cap.read()
    if not ret:
        break

    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    cv2.putText(frame, timestamp, (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2, cv2.LINE_AA)
    cv2.imshow("Video with Timestamp", frame)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

This code snippet will display the video with the current date and time on each frame.

This code reads the video frame by frame, adds a timestamp using the datetime.now() and putText() functions of OpenCV and displays it. Once the video starts, you can see the date and time at the top left of each frame. To exit the displayed video, simply press ‘q’.

Method 2: Using a Custom Overlay Function

This method defines a custom function to handle the date-time overlay, allowing for more flexible and reusable code. The function takes the frame and a position as arguments and overlays the timestamp efficiently.

Here’s an example:

import cv2
from datetime import datetime

def overlay_timestamp(frame, position):
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    cv2.putText(frame, timestamp, position, cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,255,255), 1, cv2.LINE_AA)
    return frame

cap = cv2.VideoCapture("input_video.mp4")

while True:
    ret, frame = cap.read()
    if not ret:
        break
    
    frame = overlay_timestamp(frame, (10, 50))
    cv2.imshow("Video with Timestamp", frame)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

This code outputs the video frames with a date-time stamp on the top left corner.

By encapsulating the overlay functionality in a separate function, the code is cleaner. As the video frames are processed, the overlay_timestamp function is called, adding the current timestamp to the specified frame position.

Method 3: Embedding Subtitles (SRT)

Instead of overlaying text on the video, timestamps can be added as a subtitle track. This includes the creation of a .srt file, which is then used by video players to display the timestamp as a subtitle.

Here’s an example:

# This method does not use OpenCV, instead it shows how to generate an SRT file.
from datetime import datetime, timedelta

start_time = datetime.now()
frame_rate = 30  # modify this according to your video's frame rate
duration = timedelta(seconds=1/frame_rate)

with open("timestamp.srt", "w") as srt_file:
    for i in range(1, 100):  # replace 100 with the total number of frames
        end_time = start_time + duration
        srt_file.write(f"{i}\n")
        srt_file.write(f"{start_time.strftime('%H:%M:%S,%f')[:-3]} --> {end_time.strftime('%H:%M:%S,%f')[:-3]}\n")
        srt_file.write(f"{start_time.strftime('%Y-%m-%d %H:%M:%S')}\n\n")
        start_time += duration

The outcome is an SRT file with timestamps corresponding to each frame of the video.

This approach provides the option to toggle the visibility of the timestamps, as it offers separate subtitle files instead of permanently embedded text in the video. It creates a subtitle file that can be loaded alongside the actual video.

Method 4: Real-Time Video Streaming

For live video streaming applications, you can use OpenCV to capture video from a camera and overlay the current date and time in real-time.

Here’s an example:

import cv2
from datetime import datetime

cap = cv2.VideoCapture(0)  # Replace 0 with the appropriate camera index

while True:
    ret, frame = cap.read()
    if not ret:
        break
    
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    cv2.putText(frame, timestamp, (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2, cv2.LINE_AA)

    cv2.imshow("Live Video with Timestamp", frame)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

This code outputs a live video stream with the current date and time on each frame.

Using OpenCV with a connected camera, the code captures live video, applies a timestamp overlay, and then shows the results in real-time on the screen. Again, pressing ‘q’ will exit the stream.

Bonus One-Liner Method 5: Adding Timestamp with Command-Line FFMPEG

In environments where Python is not preferred or possible, one can use FFMPEG command line to add a timestamp to the video. This method requires FFMPEG to be pre-installed on your machine.

Here’s an example:

ffmpeg -i input_video.mp4 -vf "drawtext=text='%{localtime%:fontcolor=white:fontsize=24:x=10:y=50}" -codec:a copy output_video.mp4

The output is a new video file with the date and time overlaid on each frame.

The FFMPEG command line utility applies a filter to draw text on the video. It fetches the local time and places it at specified coordinates on the video frame. This method is efficient but less flexible than a Python-based approach.

Summary/Discussion

  • Method 1: Basic Text Overlay. Strengths: direct and easy to understand, minimal code required. Weaknesses: Not very flexible, styling options limited to OpenCV’s putText() functionality.
  • Method 2: Custom Overlay Function. Strengths: more modular, allowing for reuse across different projects; easy to customize timestamp formatting. Weaknesses: Still reliant on OpenCV’s text overlay capabilities, which are more limited compared to dedicated graphics libraries.
  • Method 3: Embedding Subtitles (SRT). Strengths: Does not alter original video frames; the timestamp can be toggled on/off in video players. Weaknesses: Involves creating and managing separate subtitle files; not suitable for all video playback contexts.
  • Method 4: Real-Time Video Streaming. Strengths: Allows overlaying timestamps in live video streams. Weaknesses: Can add delay to the video stream; dependent on camera and system performance.
  • Method 5: FFMPEG Command-Line. Strengths: Doesn’t require Python; highly efficient; flexible command-line options. Weaknesses: Requires FFMPEG installation; lower level of granularity compared to Python scripts.