我想用OpenCVSharp加载本地摄像头,然后逐帧推流至RTMP,要留拉流的时候是实时的而不是每次拉流都是重头开始,应该如何写?急( ╯□╰ ),我写了一段可以执行,但是每次拉流都是重头开始播放。
internal class Test4
{
private const int WIDTH = 640;
private const int HEIGHT = 480;
private static string rtmpUrl = "rtmp://192.168.1.35:1935/live/abc";
static void Main()
{
using var capture = new VideoCapture(0);
capture.FrameWidth = WIDTH;
capture.FrameHeight = HEIGHT;
capture.BufferSize = 2;
if (!capture.IsOpened())
{
Console.WriteLine("Error: Unable to open the camera.");
return;
}
var ffmpeg = "ffmpeg.exe";
Console.WriteLine("Start");
var sw = new Stopwatch();
sw.Start();
var inputArgs = $"-y -f image2pipe -i -";
var outputArgs = $"-vcodec libx264 -crf 23 -pix_fmt yuv420p -preset ultrafast -f flv {rtmpUrl}";
var process = new Process
{
StartInfo =
{
FileName = ffmpeg,
Arguments = $"{inputArgs} {outputArgs}",
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardInput = true,
RedirectStandardError = true,
},
};
process.ErrorDataReceived += (sender, eventArgs) => Console.WriteLine(eventArgs.Data);
process.Start();
process.BeginErrorReadLine();
var ffmpegIn = process.StandardInput.BaseStream;
while (true)
{
using var frame = new Mat();
capture.Read(frame);
if (frame.Empty())
break;
var imageByte = frame.ToBitmap().GetBytes(ImageFormat.Png);
ffmpegIn.Write(imageByte, 0, imageByte.Length);
Cv2.ImShow("Camera Feed", frame);
if (Cv2.WaitKey(30) >= 0)
break;
}
Console.WriteLine("Drawing done");
ffmpegIn.Flush();
ffmpegIn.Close();
process.WaitForExit();
process.Dispose();
sw.Stop();
Console.WriteLine($"Video creating done {sw.Elapsed.TotalSeconds:0.00}s");
Console.ReadLine();
}
}
用python是实现了,但是同样的ffmepg命令在C#中执行是花屏
ffmpeg_bin = 'ffmpeg'
# 设置摄像头分辨率
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
cap.set(cv2.CAP_PROP_BUFFERSIZE, 2)
fps = cap.get(cv2.CAP_PROP_FPS)
print("fps:", fps)
# 设置缓冲区大小为2
# 定义视频编码器
fourcc = cv2.VideoWriter_fourcc(*'X264')
# 创建FFmpeg命令行参数
ffmpeg_cmd = ['ffmpeg',
'-y',
'-r','15',
'-f', 'rawvideo',
'-pixel_format', 'bgr24',
'-video_size', '640x480',
'-i', '-',
'-c:v', 'libx264',
'-preset', 'ultrafast',
'-bufsize','425984',
'-x264opts','ref=10',
#'-tune', 'zerolatency',
'-pix_fmt', 'yuv420p',
'-f', 'flv',
'rtmp://101.34.67.44:1935/live/hahaha']
# 启动FFmpeg进程
ffmepg_process = subprocess.Popen(ffmpeg_cmd, stdin=subprocess.PIPE)
while True:
success, img = cap.read()
ffmepg_process.stdin.write(img.tobytes())
cv2.imshow("Image", img)
cv2.waitKey(1)