90 lines
3.2 KiB
Python
90 lines
3.2 KiB
Python
import os
|
|
from PIL import Image
|
|
from decord import VideoReader
|
|
|
|
class VideoMonitor:
|
|
def __init__(self, recordings_path):
|
|
self.recordings_path = recordings_path
|
|
self.images_path = "/home/zydi/VLM/images"
|
|
|
|
# 确保images目录存在
|
|
if not os.path.exists(self.images_path):
|
|
os.makedirs(self.images_path)
|
|
|
|
def _save_first_frame(self, video_path):
|
|
"""从视频中截取第一帧并保存为jpg"""
|
|
try:
|
|
# 获取对应的图片保存路径
|
|
rel_path = os.path.relpath(video_path, self.recordings_path)
|
|
camera_dir = os.path.dirname(rel_path)
|
|
image_dir = os.path.join(self.images_path, camera_dir)
|
|
|
|
# 确保对应的相机目录存在
|
|
if not os.path.exists(image_dir):
|
|
os.makedirs(image_dir)
|
|
|
|
# 构建图片保存路径(使用相同的文件名,但改为jpg后缀)
|
|
image_name = os.path.splitext(os.path.basename(video_path))[0] + '.jpg'
|
|
image_path = os.path.join(image_dir, image_name)
|
|
|
|
# 如果图片已存在,则跳过
|
|
if os.path.exists(image_path):
|
|
return
|
|
|
|
# 读取视频第一帧
|
|
vr = VideoReader(video_path)
|
|
frame = vr[0].asnumpy()
|
|
|
|
# 将帧保存为jpg
|
|
image = Image.fromarray(frame)
|
|
image.save(image_path)
|
|
print(f"已保存首帧图片: {image_path}")
|
|
|
|
except Exception as e:
|
|
print(f"保存视频首帧失败 {video_path}: {str(e)}")
|
|
|
|
def monitor_directories(self):
|
|
"""监控目录变化"""
|
|
try:
|
|
print(f"开始监控目录: {self.recordings_path}")
|
|
|
|
while True:
|
|
try:
|
|
# 处理所有视频文件
|
|
for camera_dir in os.listdir(self.recordings_path):
|
|
camera_path = os.path.join(self.recordings_path, camera_dir)
|
|
if not os.path.isdir(camera_path):
|
|
continue
|
|
|
|
for video_file in os.listdir(camera_path):
|
|
if not video_file.endswith('.avi'):
|
|
continue
|
|
|
|
video_path = os.path.join(camera_path, video_file)
|
|
self._save_first_frame(video_path)
|
|
print("等待新视频文件...") # 添加此行
|
|
# 等待一段时间再检查新文件
|
|
import time
|
|
time.sleep(300) # 每10秒检查一次
|
|
|
|
except Exception as e:
|
|
print(f"监控过程出错: {str(e)}")
|
|
time.sleep(10)
|
|
|
|
except KeyboardInterrupt:
|
|
print("\n程序已终止")
|
|
except Exception as e:
|
|
print(f"\n程序异常终止: {str(e)}")
|
|
raise
|
|
|
|
def main():
|
|
try:
|
|
recordings_path = "recordings"
|
|
monitor = VideoMonitor(recordings_path)
|
|
monitor.monitor_directories()
|
|
|
|
except Exception as e:
|
|
print(f"\n未预期的错误: {str(e)}")
|
|
|
|
if __name__ == "__main__":
|
|
main() |