mirror of
https://github.com/gen2brain/cam2ip.git
synced 2025-12-16 12:28:35 +00:00
Add video file reader
This commit is contained in:
50
video/video.go
Normal file
50
video/video.go
Normal file
@@ -0,0 +1,50 @@
|
||||
// Package video.
|
||||
package video
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"image"
|
||||
|
||||
"github.com/lazywei/go-opencv/opencv"
|
||||
)
|
||||
|
||||
// Video represents video.
|
||||
type Video struct {
|
||||
video *opencv.Capture
|
||||
}
|
||||
|
||||
// New returns new Video for given path.
|
||||
func New(filename string) (video *Video, err error) {
|
||||
video = &Video{}
|
||||
|
||||
video.video = opencv.NewFileCapture(filename)
|
||||
if video.video == nil {
|
||||
err = fmt.Errorf("video: can not open video %s", filename)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// Read reads next frame from video and returns image.
|
||||
func (v *Video) Read() (img image.Image, err error) {
|
||||
if v.video.GrabFrame() {
|
||||
frame := v.video.RetrieveFrame(1)
|
||||
img = frame.ToImage()
|
||||
} else {
|
||||
err = fmt.Errorf("video: can not grab frame")
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// Close closes video.
|
||||
func (v *Video) Close() (err error) {
|
||||
if v.video == nil {
|
||||
err = fmt.Errorf("video: video is not opened")
|
||||
return
|
||||
}
|
||||
|
||||
v.video.Release()
|
||||
v.video = nil
|
||||
return
|
||||
}
|
||||
62
video/video_test.go
Normal file
62
video/video_test.go
Normal file
@@ -0,0 +1,62 @@
|
||||
package video
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"image/jpeg"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestVideo(t *testing.T) {
|
||||
video, err := New("ranko.mp4")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
defer video.Close()
|
||||
|
||||
tmpdir, err := ioutil.TempDir(os.TempDir(), "cam2ip")
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
defer os.RemoveAll(tmpdir)
|
||||
|
||||
var i int
|
||||
var n int = 10
|
||||
|
||||
timeout := time.After(time.Duration(n) * time.Second)
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-timeout:
|
||||
//fmt.Printf("Fps: %d\n", i/n)
|
||||
return
|
||||
default:
|
||||
i += 1
|
||||
|
||||
img, err := video.Read()
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
file, err := os.Create(filepath.Join(tmpdir, fmt.Sprintf("%03d.jpg", i)))
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
err = jpeg.Encode(file, img, &jpeg.Options{Quality: 75})
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
err = file.Close()
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user