避免视频捕获延迟的 gocv 实用技巧
在使用 GoCV 录制视频时,指定分辨率可能会导致视频捕获延迟。当未指定分辨率时,捕获效果良好,但设置图像大小后,会产生延时摄影,因为网络摄像头将多次录制,并将整个捕获时间填充到所需的视频长度。要避免这种情况,可以尝试设置 fps 标志,例如 webcam.Set(5, 30),其中 5 是 fps 标志。这可以帮助确保以所需的帧速率捕获视频,从而消除延迟摄影。
我想捕获并保存 mjpeg 格式的视频文件,并将分辨率设置为 1920x1080p。当我不指定分辨率时,捕获效果很好,我可以以 30fps 的速度录制和播放。但如果我改变记录的图像大小,我会得到一个延时摄影。网络摄像头会根据需要进行多次录制,并将整个捕获时间放入所需的视频长度中。例如,网络摄像头应以 30fps 录制 120 帧,因此视频捕获以及录制的视频长度应持续 4 秒。相反,捕获持续约 20 秒。整个 20 秒都在 4 秒内,这就产生了延时摄影。我怎样才能避免这种情况?我是否使用了错误的命令来定义分辨率?这是我的代码,我已经尝试过“webcam.set(3, 1920)”等以及 gocv.newmat() 或 newmatwithsize(...)。以下是我的代码
/*-------------------------------------------- savevideotest.go ----- | | Created - | | Version 1.0 2021-01-03 Initial version |------------------------------------------------------------------ | Version - - - |------------------------------------------------------------------ | Purpose: Video capture tool | Video Capture Tool to be used as main tool when it comes | to recording videos with the raspberry pi *-------------------------------------------------------------------*/ package main import ( "flag" "fmt" "gocv.io/x/gocv" "strconv" "strings" "sync" "time" "github.com/op/go-logging" "os" ) var( videolength = 120 //videolength in frames (recording with 25fps). 15k = 10min framecheck [2]int videoformat *string location *string camcount *int path *string log = logging.MustGetLogger("example") format = logging.MustStringFormatter(`%{color} %{time:2006:Jan:2:15:04:05.000} %{shortfunc} > %{level:.4s} %{id:03x}%{color:reset} %{message}`) // Mon Jan 2 15:04:05 MST 2006 ) ) /*-------------------------------------------- init ----- | Function init | Created 01.03.2021 - | Last change -- / ---- - -- | Purpose: Initialize flags for usage in other functions by parsing | Parameters: --- | Returns: --- *-------------------------------------------------------------------*/ func init() { videoformat = flag.String("videoformat",".avi","desired video format") location = flag.String("location", "BU_", "location of raspberry pi") camcount = flag.Int("camcount",1,"number of used cams") path = flag.String("path","","sets the path of videofile") } /*-------------------------------------------- main ----- | Function main | Created 01.03.2021 - | Last change -- / ---- - -- | Purpose: main function, creating infinite recording loop | with error control(var framecheck) and log generation | Parameters: --- | Returns: --- *-------------------------------------------------------------------*/ func main() { flag.Parse() printHeader() for { savevideo(videolength) //fmt.Printf("%v\n",framecheck) for k:= 0; k < *camcount; k++ { if framecheck[k] != videolength { fmt.Printf("Webcam %v hat nicht die geforderte Videolänge aufgenommen! Das Programm wird terminiert.", k) writeVideoLog(k) writeErrorLog(k) return }else { //framecheck[k] = 0 writeVideoLog(k) } } } } /*-------------------------------------------- generateFileName ----- | Function AddItem | Created 01.03.2021 - | Last change -- / ---- - -- | Purpose: Function to generate the desired Filename by using flags | Parameters: deviceID int | Returns: filename.String *-------------------------------------------------------------------*/ func generateFileName(j int) string { flag.Parse() var filename strings.Builder filename.WriteString(*path) filename.WriteString(*location) filename.WriteString("__") filename.WriteString("Cam") filename.WriteString(strconv.Itoa(j)) filename.WriteString("__") filename.WriteString(time.Now().Format("20060102_150405")) filename.WriteString(*videoformat) return filename.String() } /*-------------------------------------------- saveVideo ----- | Function saveVideo | Created 01.03.2021 - | Last change -- / ---- - -- | Purpose: Function to record and save the video | Parameters: videolength int | Returns: --- *-------------------------------------------------------------------*/ func savevideo(videolength int) { flag.Parse() var wg sync.WaitGroup wg.Add(*camcount) for j := 0; j < *camcount; j++ { go func(j int) { defer wg.Done() deviceID := j saveFile := generateFileName(j) webcam, err := gocv.VideoCaptureDevice(deviceID)// OpenVideoCapture(deviceID) if err != nil { fmt.Printf("Error opening video capture device: %v\n", deviceID) return } defer webcam.Close() img := gocv.NewMatWithSize(1280, 720, gocv.MatTypeCV64F) defer img.Close() webcam.Set(3, 1280) webcam.Set(4, 780) if ok := webcam.Read(&img); !ok { fmt.Printf("Cannot read device %v\n", deviceID) return } writer, err := gocv.VideoWriterFile(saveFile, "MJPG", 30, 1280, 720, true) if err != nil { fmt.Printf("error opening video writer device: %v\n", saveFile) return } defer writer.Close() fmt.Printf("%v %v ", img.Cols(), img.Rows()) for i := 0; i < videolength; i++ { if ok := webcam.Read(&img); !ok { fmt.Printf("Device closed: %v\n", deviceID) return } if img.Empty() { continue } framecheck[j]++ writer.Write(img) } }(j) } wg.Wait() } /*-------------------------------------------- printHeader ----- | Function printHeader | Created 01.03.2021 - | Last change -- / ---- - -- | Purpose: Function to print the header of the logfile | Parameters: --- | Returns: --- *-------------------------------------------------------------------*/ func printHeader() { flag.Parse() file, err := os.OpenFile("logs.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666) if err != nil { log.Fatal(err) } defer file.Close() backend1 := logging.NewLogBackend(file, "", 0) backend2 := logging.NewLogBackend(file, "", 0) // For messages written to backend2 we want to add some additional // information to the output, including the used log level and the name of // the function. backend2Formatter := logging.NewBackendFormatter(backend2, format) // Only errors and more severe messages should be sent to backend1 backend1Leveled := logging.AddModuleLevel(backend1) backend1Leveled.SetLevel(logging.ERROR, "") // Set the backends to be used. logging.SetBackend(backend1Leveled, backend2Formatter) log.Info("|---------------|--------|---------------------------\n") log.Info("|BUSA VIDEO LOG | |\n") log.Info("|---------------|--------|---------------------------\n") log.Info("|LOG SETUP | INFO | ROTATIONSIZE 800000000 [KBytes]]\n") log.Info("| | | Maximum size of Video directory\n") log.Info("| | | before old videos get deleted\n") log.Info("| |--------|---------------------------\n") log.Info("| | INFO | MaxFileSizeLOG 500 [KBytes]\n") log.Info("| | | Maximum size of Logfile\n") log.Info("| | | before old logfiles get copied\n") log.Info("| | | away to BUSA_VIDEO.log.TIMESTAMP\n") log.Info("| |--------|---------------------------\n") log.Info("| | INFO | MaxNumOldLOGS 10\n") log.Info("| | | Maximum number of old Logfiles\n") log.Info("| | | before oldest logfile get deleted\n") log.Info("|---------------|--------|---------------------------\n") log.Info("|LOCATION SETUP | INFO | LOCATION_NAME " + *location + "\n") log.Info("| | | Name of Location\n") log.Info("| | | Used in filename\n") log.Info("| |--------|---------------------------\n") log.Info("| | INFO | OBJECT_ID 1500021BU027-542~~~~~\n") log.Info("| | | ID for MQTT Topic to identify Object\n") log.Info("| | | where video are recorded\n") log.Info("|---------------|--------|---------------------------\n") log.Info("|MQTT SETUP | INFO | localIP 10.170.63.11\n") log.Info("| | | IP Addr that get used\n") log.Info("| | | in MQTT message for URL of Video\n") log.Info("| |--------|---------------------------\n") log.Info("| | INFO | BUSA_MQTT_BROKER\n") log.Info("| | | MQTT Broker\n") log.Info("| |--------|---------------------------\n") log.Info("| | INFO | BOX_ID 70820e1224c5\n") log.Info("| | | Hardware ID derived from MAC-Addr\n") log.Info("|---------------|--------|---------------------------\n") } /*-------------------------------------------- writeErrorLog ----- | Function writeErrorLog | Created 01.03.2021 - | Last change -- / ---- - -- | Purpose: Function to print an error log entry in case something wents wrong | Parameters: deviceID | Returns: --- *-------------------------------------------------------------------*/ func writeErrorLog(k int) { flag.Parse() file, err := os.OpenFile("logs.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666) if err != nil { log.Fatal(err) } defer file.Close() backend1 := logging.NewLogBackend(file, "", 0) backend2 := logging.NewLogBackend(file, "", 0) // For messages written to backend2 we want to add some additional // information to the output, including the used log level and the name of // the function. backend2Formatter := logging.NewBackendFormatter(backend2, format) // Only errors and more severe messages should be sent to backend1 backend1Leveled := logging.AddModuleLevel(backend1) backend1Leveled.SetLevel(logging.ERROR, "") // Set the backends to be used. logging.SetBackend(backend1Leveled, backend2Formatter) log.Error(" | ERROR | Kritischer Fehler: Webcam " + strconv.Itoa(k) + " hat nicht die erforderliche Anzahl an Frames aufgenommen. Die Anwendung wurde beendet.\n") } /*-------------------------------------------- writeVideoLog ----- | Function writeVideoLog | Created 01.03.2021 - | Last change -- / ---- - -- | Purpose: Function to write an info log entry when a video is saved | Parameters: deviceID | Returns: --- *-------------------------------------------------------------------*/ func writeVideoLog(k int) { flag.Parse() file, err := os.OpenFile("logs.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666) if err != nil { log.Fatal(err) } defer file.Close() backend1 := logging.NewLogBackend(file, "", 0) backend2 := logging.NewLogBackend(file, "", 0) // For messages written to backend2 we want to add some additional // information to the output, including the used log level and the name of // the function. backend2Formatter := logging.NewBackendFormatter(backend2, format) // Only errors and more severe messages should be sent to backend1 backend1Leveled := logging.AddModuleLevel(backend1) backend1Leveled.SetLevel(logging.ERROR, "") // Set the backends to be used. logging.SetBackend(backend1Leveled, backend2Formatter) log.Info(" | INFO | Neues Video " + generateFileName(k) + "\n") }
哦,是的,我对编码很陌生,尤其是 golang。我学习 java 一个月了,但作为实习生参与了一个 go 项目,以了解作为一名开发人员的意义。 (ps:我希望 deadprogram 能看到这一点,他似乎是 golang 和 gocv 中的神,他在我到目前为止查到的每个问题下:d)
解决方案
您是否尝试过设置 fps
webcam.Set(5, 30)
其中 5 是 fps 标志。
今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

- 上一篇
- go tool pprof显示的内存占用比linux top显示的要低得多

- 下一篇
- 揭示:前端领域中Golang的潜在应用
-
- Golang · Go问答 | 1年前 |
- 在读取缓冲通道中的内容之前退出
- 139浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 戈兰岛的全球 GOPRIVATE 设置
- 204浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何将结构作为参数传递给 xml-rpc
- 325浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何用golang获得小数点以下两位长度?
- 477浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何通过 client-go 和 golang 检索 Kubernetes 指标
- 486浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 将多个“参数”映射到单个可变参数的习惯用法
- 439浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 将 HTTP 响应正文写入文件后出现 EOF 错误
- 357浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 结构中映射的匿名列表的“复合文字中缺少类型”
- 352浏览 收藏
-
- Golang · Go问答 | 1年前 |
- NATS Jetstream 的性能
- 101浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何将复杂的字符串输入转换为mapstring?
- 440浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 相当于GoLang中Java将Object作为方法参数传递
- 212浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何确保所有 goroutine 在没有 time.Sleep 的情况下终止?
- 143浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 508次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 497次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 484次学习
-
- 笔灵AI生成答辩PPT
- 探索笔灵AI生成答辩PPT的强大功能,快速制作高质量答辩PPT。精准内容提取、多样模板匹配、数据可视化、配套自述稿生成,让您的学术和职场展示更加专业与高效。
- 23次使用
-
- 知网AIGC检测服务系统
- 知网AIGC检测服务系统,专注于检测学术文本中的疑似AI生成内容。依托知网海量高质量文献资源,结合先进的“知识增强AIGC检测技术”,系统能够从语言模式和语义逻辑两方面精准识别AI生成内容,适用于学术研究、教育和企业领域,确保文本的真实性和原创性。
- 36次使用
-
- AIGC检测-Aibiye
- AIbiye官网推出的AIGC检测服务,专注于检测ChatGPT、Gemini、Claude等AIGC工具生成的文本,帮助用户确保论文的原创性和学术规范。支持txt和doc(x)格式,检测范围为论文正文,提供高准确性和便捷的用户体验。
- 37次使用
-
- 易笔AI论文
- 易笔AI论文平台提供自动写作、格式校对、查重检测等功能,支持多种学术领域的论文生成。价格优惠,界面友好,操作简便,适用于学术研究者、学生及论文辅导机构。
- 47次使用
-
- 笔启AI论文写作平台
- 笔启AI论文写作平台提供多类型论文生成服务,支持多语言写作,满足学术研究者、学生和职场人士的需求。平台采用AI 4.0版本,确保论文质量和原创性,并提供查重保障和隐私保护。
- 40次使用
-
- GoLand调式动态执行代码
- 2023-01-13 502浏览
-
- 用Nginx反向代理部署go写的网站。
- 2023-01-17 502浏览
-
- Golang取得代码运行时间的问题
- 2023-02-24 501浏览
-
- 请问 go 代码如何实现在代码改动后不需要Ctrl+c,然后重新 go run *.go 文件?
- 2023-01-08 501浏览
-
- 如何从同一个 io.Reader 读取多次
- 2023-04-11 501浏览