Python使用OpenCV对视频逐帧绘制矩形框并保存的方法
本文介绍如何使用Python和OpenCV库对视频文件进行逐帧处理,通过在指定坐标绘制矩形框实现标记功能,并将处理后的视频保存为新文件。代码示例展示了视频读取、帧循环、矩形绘制及视频写入的完整流程,适用于需要视频内容标注的场景。
在使用OpenCV对视频进行矩形框标记时,需确保代码中绘制矩形的函数调用未被注释。具体而言,应取消对语句的注释,该函数用于在视频帧上指定左上角和右下角坐标来绘制矩形,参数包括颜色(如红色)和线条粗细。只有启用此步骤,标记效果才会出现在最终输出的视频中。
import cv2
import os,sys,shutil
import numpy as np
# Open the input movie file, input the filepath as
input_filepath = sys.argv[1]
input_movie = cv2.VideoCapture(input_filepath)
length = int(input_movie.get(cv2.CAP_PROP_FRAME_COUNT))
#设置output
output_movie = cv2.VideoWriter(input_filepath.replace("mp4","avi").replace("input","output"), cv2.VideoWriter_fourcc('D', 'I', 'V', 'X'), 25, (1280, 720))
# Initialize some variables
frame_number = 0
while True:
# Grab a single frame of video
ret, frame = input_movie.read()
frame_number += 1
# Quit when the input video file ends
if not ret:
break
# Draw a box around the body: input the top left point(x,y) and bottom right point(x,y)
#cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
# Write the resulting image to the output video file
print("Writing frame {} / {}".format(frame_number, length))
output_movie.write(frame)
# All done!
input_movie.release()
cv2.destroyAllWindows()
上述内容详细讲解了利用Python结合OpenCV实现视频帧矩形标记并保存的完整方法。该方案通过遍历视频帧、调用绘图函数并写入新视频文件,提供了可参考的技术实现。建议读者在实际应用中根据需求调整坐标参数和视频编码格式,如有相关问题欢迎进一步探讨。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













