87 lines
2.7 KiB
Python
87 lines
2.7 KiB
Python
import os
|
||
import tempfile
|
||
import time
|
||
from pathlib import Path
|
||
|
||
import cv2
|
||
from loguru import logger
|
||
|
||
|
||
def get_first_frame(video_path, output_path):
|
||
"""
|
||
提取视频的第一帧并保存为图片
|
||
:param video_path: 视频文件路径
|
||
:param output_path: 输出图片路径
|
||
:return: 输出图片的绝对路径,如果失败则返回None
|
||
"""
|
||
cap = None
|
||
try:
|
||
logger.info(f"开始提取视频首帧: {video_path}")
|
||
# 打开视频文件
|
||
cap = cv2.VideoCapture(video_path)
|
||
if not cap.isOpened():
|
||
logger.error(f"无法打开视频: {video_path}")
|
||
return None
|
||
|
||
# 读取首帧
|
||
ret, frame = cap.read()
|
||
if not ret:
|
||
logger.error("无法读取视频帧")
|
||
cap.release()
|
||
return None
|
||
|
||
# 保存首帧为图片
|
||
try:
|
||
# 获取项目根目录
|
||
project_root = os.getcwd()
|
||
project_root_path = Path(project_root).resolve()
|
||
|
||
# 创建临时目录
|
||
temp_dir = project_root_path / "temp"
|
||
try:
|
||
temp_dir.mkdir(parents=True, exist_ok=True)
|
||
except Exception as e:
|
||
logger.error(f"Failed to create temp directory: {e}")
|
||
raise FileNotFoundError(f"Could not create temp directory: {temp_dir}")
|
||
|
||
# 生成唯一的临时文件名
|
||
timestamp = int(time.time())
|
||
output_image_path = temp_dir / output_path
|
||
cv2.imwrite(str(output_image_path), frame)
|
||
logger.info(f"首帧已保存为: {str(output_image_path)}")
|
||
except Exception as e:
|
||
logger.error(f"保存首帧图片失败: {e}")
|
||
cap.release()
|
||
return None
|
||
|
||
# 释放资源
|
||
cap.release()
|
||
return os.path.abspath(str(output_image_path))
|
||
|
||
except Exception as e:
|
||
logger.error(f"提取视频首帧时出错: {e}")
|
||
return None
|
||
finally:
|
||
cap.release()
|
||
|
||
|
||
def get_first_frame_bytes(video_bytes, output_path):
|
||
"""
|
||
提取视频的第一帧并保存为图片
|
||
:param video_bytes: 视频文件流
|
||
:param output_path: 输出图片路径
|
||
:return: 输出图片的绝对路径,如果失败则返回None
|
||
"""
|
||
try:
|
||
logger.info(f"开始提取视频流首帧")
|
||
# 创建临时文件
|
||
with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as temp_file:
|
||
# 将字节流写入临时文件
|
||
temp_file.write(video_bytes)
|
||
temp_file_path = temp_file.name # 获取临时文件路径
|
||
# 打开视频文件
|
||
return get_first_frame(temp_file_path, output_path)
|
||
except Exception as e:
|
||
logger.error(f"提取视频首帧时出错: {e}")
|
||
return None
|