Skip to content

Instantly share code, notes, and snippets.

@kasari
Created October 13, 2018 11:20
Show Gist options
  • Save kasari/2b858aff1a8679d8e010f0c62acf3b8e to your computer and use it in GitHub Desktop.
Save kasari/2b858aff1a8679d8e010f0c62acf3b8e to your computer and use it in GitHub Desktop.
package main
import (
"image"
"gocv.io/x/gocv"
)
func main() {
webcam, err := gocv.OpenVideoCapture(0)
if err != nil {
panic(err)
}
window := gocv.NewWindow("Horizontal Time Slicer")
mb := NewMatBuffer(50)
img := gocv.NewMat()
resizedImg := gocv.NewMat()
for {
webcam.Read(&img)
gocv.Resize(img, &resizedImg, image.Point{img.Cols() / 3, img.Rows() / 3}, 0.5, 0.5, gocv.InterpolationDefault)
mb.Push(resizedImg.Clone())
window.IMShow(mb.HorizontalTimeSliceMat())
window.WaitKey(1)
}
}
type MatBuffer struct {
bufsize int
buf []gocv.Mat
}
func NewMatBuffer(bufsize int) *MatBuffer {
return &MatBuffer{
bufsize: bufsize,
buf: make([]gocv.Mat, 0, bufsize),
}
}
func (mb *MatBuffer) Push(mat gocv.Mat) {
if len(mb.buf) == mb.bufsize {
mb.buf = mb.buf[1:mb.bufsize]
}
mb.buf = append(mb.buf, mat)
}
func (mb *MatBuffer) DelayMat() gocv.Mat {
return mb.buf[0]
}
func (mb *MatBuffer) HorizontalTimeSliceMat() gocv.Mat {
if len(mb.buf) != mb.bufsize {
return mb.buf[0]
}
sizePerMat := 14
originMat := mb.buf[mb.bufsize-1].Clone()
originMa := NewMatAccessor(originMat)
for i, mat := range mb.buf {
ma := NewMatAccessor(mat)
for j := 0; j < sizePerMat; j++ {
rowData := ma.GetRowData(sizePerMat*i + j)
originMa.SetRowData(sizePerMat*i+j, rowData)
}
}
return originMa.ToMat()
}
type MatAccessor struct {
mat gocv.Mat
rows int
cols int
mt gocv.MatType
data []byte
}
func NewMatAccessor(mat gocv.Mat) *MatAccessor {
return &MatAccessor{
mat: mat,
rows: mat.Rows(),
cols: mat.Cols(),
mt: mat.Type(),
data: mat.ToBytes(),
}
}
func (ma *MatAccessor) GetRowData(row int) []byte {
start := row * ma.cols
end := start + ma.cols
return ma.data[start:end]
}
func (ma *MatAccessor) SetRowData(row int, rowData []byte) {
start := row * ma.cols
for i := 0; i < ma.cols; i++ {
ma.data[start+i] = rowData[i]
}
}
func (ma *MatAccessor) ToMat() gocv.Mat {
mat, _ := gocv.NewMatFromBytes(ma.rows, ma.cols, ma.mt, ma.data)
return mat
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment