避免视频捕获延迟的 gocv 实用技巧
来源:stackoverflow
时间:2024-03-18 08:00:31 284浏览 收藏
在使用 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学习网公众号,一起学习编程~
-
502 收藏
-
502 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
139 收藏
-
204 收藏
-
325 收藏
-
478 收藏
-
486 收藏
-
439 收藏
-
357 收藏
-
352 收藏
-
101 收藏
-
440 收藏
-
212 收藏
-
143 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 485次学习