opencvsharp usb摄像头录像 c# H264编码

1.首先创建ConsoleApp,.Net 9.0,不要创建WinFormWInForm帧率和实际对不上,有延时

2.下载opencvsharp。

3.下载openh264-1.8.0-win32.dll , openh264-1.8.0-win64.dll .放在根目录。

https://github.com/cisco/openh264

复制代码
using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    internal class Program
    {
        private const int CameraIndex = 0;

        private const double Fps = 30.0;
        // private static readonly OpenCvSharp.Size FrameSize = new OpenCvSharp.Size(1280, 720);
        private static readonly OpenCvSharp.Size FrameSize = new OpenCvSharp.Size(640, 480);
        private const int ReconnectInterval = 3000; // 重试间隔(ms)
        private const int MaxReconnectAttempts = 5; // 最大重试次数

        static void Main(string[] args)
        {

            int reconnectAttempts = 0;
            bool isRecording = true;

            while (isRecording && reconnectAttempts < MaxReconnectAttempts)
            {
                try
                {
                    using (var capture = new VideoCapture(CameraIndex))
                    using (var writer = new VideoWriter())
                    {
                        if (!InitializeCamera(capture))
                        {
                            reconnectAttempts++;
                            Thread.Sleep(ReconnectInterval);
                            continue;
                        }
                        string OutputFile = System.DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") + "_output.avi";
                        if (!InitializeVideoWriter(writer, OutputFile, Fps, FrameSize))
                        {
                            Console.WriteLine("无法初始化视频写入器!");
                            return;
                        }

                        Console.WriteLine("开始录制,按ESC键停止...");
                        reconnectAttempts = 0; // 重置重试计数器

                        using (var window = new Window("摄像头画面"))
                        using (var frame = new Mat())
                        {
                            while (true)
                            {
                                // 检查摄像头是否仍然连接
                                if (!capture.IsOpened())
                                {
                                    Console.WriteLine("检测到摄像头断开连接!");
                                    break;
                                }

                                // 捕获帧
                                capture.Read(frame);
                                DateTime now = DateTime.Now;
                                Cv2.PutText(frame, now.ToString("yyyy-MM-dd HH:mm:ss"), new Point(10, 30),
                                            HersheyFonts.HersheySimplex, 0.6, Scalar.White, 1);
                                if (frame.Empty())
                                {
                                    Console.WriteLine("接收到空帧,可能摄像头已断开!");
                                    break;
                                }

                                // 显示帧
                                window.ShowImage(frame);

                                // 写入帧到文件
                                writer.Write(frame);

                                // 按ESC键退出
                                if (Cv2.WaitKey(10) == 27)
                                {
                                    isRecording = false;
                                    break;
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"发生错误: {ex.Message}");
                }

                if (isRecording && reconnectAttempts < MaxReconnectAttempts)
                {
                    Console.WriteLine($"尝试重新连接({reconnectAttempts + 1}/{MaxReconnectAttempts})...");
                    reconnectAttempts++;
                    Thread.Sleep(ReconnectInterval);
                }
            }

            if (reconnectAttempts >= MaxReconnectAttempts)
            {
                Console.WriteLine($"已达到最大重试次数({MaxReconnectAttempts}),停止尝试。");
            }

            Console.WriteLine("程序结束");
        }

        static bool InitializeCamera(VideoCapture capture)
        {
            if (!capture.IsOpened())
            {
                Console.WriteLine("无法打开摄像头!");
                return false;
            }

            // 设置摄像头参数
            capture.Set(VideoCaptureProperties.FrameWidth, FrameSize.Width);
            capture.Set(VideoCaptureProperties.FrameHeight, FrameSize.Height);
            capture.Set(VideoCaptureProperties.Fps, Fps);

            // 验证实际设置的值
            double actualWidth = capture.Get(VideoCaptureProperties.FrameWidth);
            double actualHeight = capture.Get(VideoCaptureProperties.FrameHeight);
            Console.WriteLine($"摄像头分辨率: {actualWidth}x{actualHeight}");

            return true;
        }

        static bool InitializeVideoWriter(VideoWriter writer, string filename, double fps, Size frameSize)
        {
            // 尝试几种常见的编码格式
            Dictionary<string, FourCC> _codecs = new Dictionary<string, FourCC>()
            {
                 {"X264", FourCC.X264},
                 {"XVID", FourCC.XVID},
                 {"MJPG", FourCC.MJPG},
                 {"H264", FourCC.H264},
                 {"MP4V", FourCC.MP4V},
                 {"DIVX", FourCC.DIVX}
            };

            foreach (var codec in _codecs)
            {
                writer.Open(filename, codec.Value, fps, frameSize, true);
                if (writer.IsOpened())
                {
                    Console.WriteLine($"使用编码器: {codec.Key}");
                    return true;
                }
            }

            Console.WriteLine("无法找到合适的视频编码器!");
            return false;
        }
    }
}

4.运行。

整个工程打包下载:

【免费】opencvsharpusb摄像头录像c#H264编码资源-CSDN文库

相关推荐
孫治AllenSun1 小时前
【DataX】生产环境搭建DataX集群案例
java·开发语言·jvm
c238562 小时前
把 C++ 内存分配拆透:new 与 malloc 的三层血缘
开发语言·c++·算法
moonsims3 小时前
星闪在跨域无人化系统作用
开发语言·php
Iruoyaoxh3 小时前
栈和队列~
java·开发语言
Hrain-AI4 小时前
2026 企业 AI 编程智能体实战:Codex 与 Claude Code
开发语言·人工智能·kotlin
wdfk_prog4 小时前
嵌入式面试真题第 13 题:单硬件 Timer 下的高精度多路软件定时器架构设计
c语言·开发语言·面试·职场和发展·嵌入式
oort1234 小时前
吃上了自家的细糠,还挺丝滑,用起来手感还行,OortCloud发布新版AI编程平台,下载 OortCodex,Token多,免费薅
大数据·开发语言·人工智能·ai编程
slandarer4 小时前
MATLAB | 泰勒图绘制,支持各种角度范围
开发语言·数学建模·matlab·nature·顶刊·泰勒图
Xin_ye100865 小时前
第三章:内存泄漏的常见“案发现场”
c#·wpf
mct1235 小时前
c++ iconv 字符utf-8转换gb2312失败
开发语言·c++