当前位置: 首页 > news >正文

录制mp4

目录

单线程保存mp4

多线程保存mp4 rtsp

ffmpeg录制mp4


单线程保存mp4


import cv2
import imageiocv2.namedWindow('photo', 0)  # 0窗口大小可以任意拖动,1自适应
cv2.resizeWindow('photo', 1280, 720)
url ="rtsp://admin:aa123456@192.168.1.64/h264/ch1/main/av_stream"
cap = cv2.VideoCapture(1)
ret = cap.isOpened()
imgs = []
fps =30
index = 0
count = 0
strat_record = False
while (ret):ret, img = cap.read()if not ret: breakcv2.imshow('photo', img)img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)if strat_record:imgs.append(img)index +=1if index %300 == 299 and strat_record:count+=1save_video_path = f'lanqiu_{count}.mp4'imageio.mimsave(save_video_path, imgs, fps=fps, macro_block_size=None)imgs=[]key = cv2.waitKey(1) & 0xFFif key == ord('q'):breakelif key == ord('s'):strat_record = Trueprint("start_record", strat_record)elif key == ord('e'):strat_record = Falseprint("end_record", strat_record)
cap.release()
save_video_path = f'lanqiu_{count}.mp4'
imageio.mimsave(save_video_path, imgs, fps=fps, macro_block_size=None)

多线程保存mp4 rtsp

import cv2
import threading
import queue
import time# 参数设置
url = "rtsp://admin:aa123456@192.168.1.64/h264/ch1/main/av_stream"
fps = 30
segment_time = 10  # 每段录制 10 秒
fourcc = cv2.VideoWriter_fourcc(*'mp4v')# 用于保存帧的队列
frame_queue = queue.Queue()
recording = False
stop_signal = False
video_count = 0# 保存线程函数
def save_video_worker():global video_countwhile True:if stop_signal and frame_queue.empty():breakframes = []start_time = time.time()while time.time() - start_time < segment_time:try:frame = frame_queue.get(timeout=1)frames.append(frame)except queue.Empty:continueif frames:h, w = frames[0].shape[:2]video_count += 1save_path = f'lanqiu_{video_count}.mp4'out = cv2.VideoWriter(save_path, fourcc, fps, (w, h))for f in frames:out.write(f)out.release()print(f"[保存完成] {save_path}")# 启动摄像头
cap = cv2.VideoCapture(url)
ret = cap.isOpened()cv2.namedWindow('photo', 0)
cv2.resizeWindow('photo', 1280, 720)# 开启保存线程(一直运行,直到设置 stop_signal)
thread = threading.Thread(target=save_video_worker)
thread.start()while ret:ret, frame = cap.read()if not ret:breakcv2.imshow('photo', frame)key = cv2.waitKey(1) & 0xFFif key == ord('q'):breakelif key == ord('s') and not recording:recording = Trueprint("[开始录制]")elif key == ord('e') and recording:recording = Falseprint("[停止录制]")if recording:frame_queue.put(frame.copy())  # 用 copy 避免线程间冲突cap.release()
stop_signal = True
thread.join()
cv2.destroyAllWindows()

ffmpeg录制mp4

import subprocess
import threading
import queue
import time
import cv2
import numpy as np# === 参数设置 ===
rtsp_url = "rtsp://admin:aa123456@192.168.1.64/h264/ch1/main/av_stream"
width, height = 1280, 720
fps = 25
segment_time = 10  # 每段录制时间(秒)
fourcc = cv2.VideoWriter_fourcc(*'mp4v')recording = False
stop_signal = False
video_count = 0frame_queue = queue.Queue()# === 保存线程函数 ===
def save_video_worker():global video_countwhile not stop_signal or not frame_queue.empty():frames = []start_time = time.time()while time.time() - start_time < segment_time:try:frame = frame_queue.get(timeout=1)frames.append(frame)except queue.Empty:continueif frames:video_count += 1out = cv2.VideoWriter(f'video_segment_{video_count}.mp4', fourcc, fps, (width, height))for f in frames:out.write(f)out.release()print(f"[保存完成] video_segment_{video_count}.mp4")# === 启动 FFmpeg 读取 RTSP ===
ffmpeg_cmd = [r'E:\soft\ffmpeg-7.1.1-full_build\ffmpeg-7.1.1-full_build\bin\ffmpeg.exe','-rtsp_transport', 'tcp','-i', rtsp_url,'-f', 'rawvideo','-pix_fmt', 'bgr24','-vf', f'scale={width}:{height}','-'
]pipe = subprocess.Popen(ffmpeg_cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, bufsize=10**8)# === 启动保存线程 ===
thread = threading.Thread(target=save_video_worker)
thread.start()# === 实时显示和按键控制 ===
cv2.namedWindow("photo", 0)
cv2.resizeWindow("photo", width, height)try:while True:raw_frame = pipe.stdout.read(width * height * 3)if not raw_frame:print("视频读取失败,退出")breakframe = np.frombuffer(raw_frame, np.uint8).reshape((height, width, 3))cv2.imshow("photo", frame)key = cv2.waitKey(1) & 0xFFif key == ord('q'):breakelif key == ord('s') and not recording:recording = Trueprint("[开始录制]")elif key == ord('e') and recording:recording = Falseprint("[停止录制]")if recording:frame_queue.put(frame.copy())except KeyboardInterrupt:print("中断退出")# === 清理资源 ===
stop_signal = True
thread.join()
pipe.terminate()
cv2.destroyAllWindows()

http://www.lqws.cn/news/136387.html

相关文章:

  • RAG技术解析:实现高精度大语言模型知识增强
  • promethues上监控K3S中的pod的状态
  • [AI Claude] 软件测试2
  • 互斥锁与消息队列的架构哲学
  • 网络攻防技术十三:网络防火墙
  • docker的基本命令
  • (四)docker命令—容器管理命令
  • SOC-ESP32S3部分​​​​​​​:29-乐鑫组件库的使用
  • 6个月Python学习计划 Day 14 - 异常处理基础( 补充学习)
  • Kafka broker 写消息的过程
  • UE 材质基础第三天
  • 细说C语言将格式化输出到字符串的函数sprintf、_sprintf_l、swprintf、_swprintf_l、__swprintf_l
  • MP4文件声音与视频分离
  • 网络寻路--图论
  • C语言数据结构笔记3:Union联合体+结构体取8位Bool量
  • 嵌入式常见 CPU 架构
  • 传输层协议 UDP 介绍 -- UDP 协议格式,UDP 的特点,UDP 的缓冲区
  • 激光干涉仪:解锁协作机器人DD马达的精度密码
  • [Java 基础]类,面向对象的蓝图
  • ABP-Book Store Application中文讲解 - Part 9: Authors: User Interface
  • AWS中国区IAM相关凭证自行管理策略(只读CodeCommit版)
  • Linux容器篇、第一章docker命令总结表
  • C++入门基础
  • JavaScript基础:运算符
  • 本地IP配置
  • 【电赛培训课程】电子设计竞赛工程基础知识
  • psycopg2-binary、pgvector、 SQLAlchemy、 PostgreSQL四者的关系
  • typescript中的type如何使用
  • FSC认证概述?FSC认证的核心原则与标准?FSC认证的市场价值与意义
  • QRSuperResolutionNet:一种结构感知与识别增强的二维码图像超分辨率网络(附代码解析)