Gocv图片合成视频(无音频)

Gocv图片合成视频(无音频),第1张

Home :: GoCV - Golang Computer Vision Using OpenCV 4

写在前面:

我只用png和jpg图片生成了avi格式的视频,还不懂mp4怎么生成。我想我应该去看ffmpeg,不过opencv的VideoWriter应该能生成mp4视频的啊,fourcc不对?如何控制生成的视频时长?作为一名前端,还不懂。

版本信息:

gocv version: 0.29.0

opencv lib version: 4.5.4

我需要这些:

Go语言标准库文档中文版 | Go语言中文网 | Golang中文社区 | Golang中国

Home :: GoCV - Golang Computer Vision Using OpenCV 4

gocv package - gocv.io/x/gocv - pkg.go.dev

丑陋的代码:

package main

import (
	"fmt"
	"image"
	"image/png"
	"os"

	"gocv.io/x/gocv"
)

func main() {
	filename := "video01.avi" // 尾巴要有数字,不知道哪里少了个库
	fourcc := "MJPG"
	bfs := float64(25)
	frameWidth := 512
	frameHeight := 512
	videoWriter, err := gocv.VideoWriterFile(filename, fourcc, bfs, frameWidth, frameHeight, true)

	// 本地图片文件数组
	imgs := [...]string{"static/test.jpg", "static/test.png"}

	if err != nil {
		fmt.Println("视频写文件错误")
		return
	}
	defer videoWriter.Close()

	if !videoWriter.IsOpened() {
		fmt.Println("打开视频写文件失败")
	}

	// 写本地jpeg图片
	mat := gocv.IMRead(imgs[0], gocv.IMReadColor)
	// Resize的作用就是图片和视频尺寸不一致的时候弄到一致,至于怎么保持图片比例还不懂
	gocv.Resize(mat, &mat, image.Point{X: frameWidth, Y: frameHeight}, 0, 0, gocv.InterpolationArea)
	gocv.CvtColor(mat, &mat, gocv.ColorBGRToRGBA)
	defer mat.Close()

	for i := 0; i < 100; i++ {
		videoWriter.Write(mat)
	}

	// 写本地png图片 if path.Ext(imgs[i]) == string(gocv.PNGFileExt) // 判断.png
	file, _ := os.Open(imgs[1])
	defer file.Close()
	img, _ := png.Decode(file)
	mat, _ = gocv.ImageToMatRGB(img)
	// Resize的作用就是图片和视频尺寸不一致的时候弄到一致,至于怎么保持图片比例还不懂
	gocv.Resize(mat, &mat, image.Point{X: frameWidth, Y: frameHeight}, 0, 0, gocv.InterpolationArea)

	gocv.CvtColor(mat, &mat, gocv.ColorBGRToRGBA)
	defer mat.Close()

	for i := 0; i < 100; i++ {
		videoWriter.Write(mat)
	}

	fmt.Println("ok")
}

// 网络图片转Mat
// func saveImageFromURL(imgURL string) (gocv.Mat, error) {
// 	dummy := gocv.Mat{}
// 	resp, err := http.Get(imgURL)
// 	if err != nil {
// 		return dummy, err
// 	}
// 	content, _ := ioutil.ReadAll(resp.Body)
// 	if resp.StatusCode > 202 {
// 		return dummy, errors.New(string(content))
// 	}
// 	defer resp.Body.Close()
// 	mat, _ := gocv.IMDecode(content, gocv.IMReadColor)
// 	if m.Empty() {
// 		return dummy, fmt.Errorf("invalid image content from URL: `%s`", imgURL)
// 	}
// 	return mat, nil
// }


 

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/993949.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存