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文库

相关推荐
aashuii32 分钟前
go客户端ssh交换机
开发语言·golang·ssh
是紫焅呢36 分钟前
E结构体基础.go
开发语言·后端·golang·学习方法·visual studio code
clt12332139 分钟前
golang excel导出时需要显示刷新
开发语言·后端·golang
Silverdew*40 分钟前
vs code配置go开发环境以及问题解决 could not import cannot find package in GOROOT or GOPATH
开发语言·后端·golang
周圣贤3 小时前
九尾狐编程语言新算法“超维时空演算体”
开发语言·算法
CaracalTiger4 小时前
HTTP 协议的基本概念(请求/响应流程、状态码、Header、方法)问题解决方案大全
开发语言·网络·python·深度学习·网络协议·http·pip
随缘而动,随遇而安4 小时前
第八十二篇 大数据开发基础:树形数据结构深度解析与实战指南(附创新生活案例)
大数据·开发语言·数据结构
西猫雷婶4 小时前
python学智能算法(十三)|机器学习朴素贝叶斯方法进阶-简单二元分类
开发语言·人工智能·python·深度学习·机器学习·矩阵·分类
武子康5 小时前
Java-49 深入浅出 Tomcat 手写 Tomcat 实现【02】HttpServlet Request RequestProcessor
java·开发语言·后端·学习·spring cloud·tomcat
张朝阳的博客5 小时前
哈夫曼树Python实现
开发语言·python