This chapter aims to document how the author adds text to each frame of the video

# Importing all necessary libraries
import cv2
import os


def makeVideo(path, video_name):
    cam = cv2.VideoCapture(path)
    try:
        if not os.path.exists('data'):
            os.makedirs('data')
    except OSError:
        print('Error: Creating directory of data')

    fps = cam.get(cv2.CAP_PROP_FPS)
    # 总帧数(frames)
    frames = cam.get(cv2.CAP_PROP_FRAME_COUNT)
    print("帧数:" + str(fps))
    print("总帧数:" + str(frames))
    print("视屏总时长:" + "{0:.2f}".format(frames / fps) + "秒")

    height = 0;
    width = 0;
    layers = 0;
    # determine whether to open normally
    if cam.isOpened():
        ret, frame = cam.read()
        height, width, layers = frame.shape
    else:
        ret = False
    video = cv2.VideoWriter(video_name, 0, fps, (width, height))
    index = 0;

    allFrames = []
    add = 0

    while ret:
        text = "index={}".format(index)
        #text = "frame of No " + str(index)
        cv2.putText(frame, text, (50,150), cv2.FONT_HERSHEY_SIMPLEX, 1, (50, 50, 50), 2)
        video.write(frame)
        #video.write(frame)
        ret, frame = cam.read()
        index = index + 1
    cam.release()
    video.release()
    cv2.destroyAllWindows()

if __name__ == '__main__':

    video_name = 'New_Camera_standard.mp4'
    pathVideo = "E:\\PythonMedia\\media\\xxxxxxxxx"
    makeVideo(pathVideo, video_name)



By Admin

Think-Math Website