Emgu.CV中修改USB2.0摄像头FourCC格式无效,如何解决?
问题
用Emgu.CV实现摄像头矩阵采集实时视频时,摄像头FPS偏低。通过厂商软件将视频格式从YUY2改为MJPG后,FPS达标,但代码中做同样操作却无效:读取FourCC属性返回值为22,既不是YUY2也不是MJPG。
尝试的代码如下:
// Ensure the captureArray is initialized if (captureArray[i][j] == null) { // Index -1 because the index 0 is empty to deselect the cameras captureArray[i][j] = new VideoCapture(camSelectComboBoxMatrix[i][j].SelectedIndex - 1); } // Set the FourCC property based on the desired format int fourcc; if (format.Equals("YUY2", StringComparison.OrdinalIgnoreCase)) { fourcc = VideoWriter.Fourcc('Y', 'U', 'Y', '2'); } else if (format.Equals("MJPG", StringComparison.OrdinalIgnoreCase)) { fourcc = VideoWriter.Fourcc('M', 'J', 'P', 'G'); } else { throw new ArgumentException("Unsupported video format. Use 'YUY2' or 'MJPG'."); } captureArray[i][j].Set(CapProp.FourCC, fourcc); // Log the FourCC property to verify it was set correctly double fourCCValue = captureArray[i][j].Get(CapProp.FourCC); string fourCCString = new string(new char[] { (char)((int)fourCCValue & 0xFF), (char)(((int)fourCCValue >> 8) & 0xFF), (char)(((int)fourCCValue >> 16) & 0xFF), (char)(((int)fourCCValue >> 24) & 0xFF) }); textBox1.AppendText($"FourCC: {fourCCString}\r\n");
哪怕直接设置MJPG对应的int值1196444237,读取后还是22。尝试更换后端,但后端为只读属性,也找不到初始化VideoCapture时指定后端的相关文档。
解决方案
初始化时直接指定后端与格式
Emgu.CV的VideoCapture构造函数支持传入后端参数,Windows下推荐用DShow或MSMF后端,初始化后再设置格式(部分摄像头需先设分辨率再设格式):int camIndex = camSelectComboBoxMatrix[i][j].SelectedIndex - 1; // 用MSMF后端初始化(对压缩格式支持更好) captureArray[i][j] = new VideoCapture(camIndex, VideoCapture.API.MSMF); // 先设置分辨率(可选,部分摄像头要求此顺序) captureArray[i][j].Set(CapProp.FrameWidth, 1920); captureArray[i][j].Set(CapProp.FrameHeight, 1080); // 设置MJPG格式 int mjpgFourcc = VideoWriter.Fourcc('M', 'J', 'P', 'G'); captureArray[i][j].Set(CapProp.FourCC, mjpgFourcc);先枚举摄像头支持的格式
部分摄像头仅支持特定格式,先枚举确认再设置:VideoCapture cap = new VideoCapture(camIndex, VideoCapture.API.DShow); for (int k = 0; ; k++) { double fourccVal = cap.Get(CapProp.FourCC, k); if (fourccVal == 0) break; string fourccStr = new string(new char[] { (char)((int)fourccVal & 0xFF), (char)(((int)fourccVal >> 8) & 0xFF), (char)(((int)fourccVal >> 16) & 0xFF), (char)(((int)fourccVal >> 24) & 0xFF) }); textBox1.AppendText($"Supported format: {fourccStr}\r\n"); }检查Set操作的返回值
Set方法返回bool值表示设置是否成功,先判断再验证:bool success = captureArray[i][j].Set(CapProp.FourCC, fourcc); if (!success) { textBox1.AppendText($"Failed to set {format} format\r\n"); }
内容的提问来源于stack exchange,提问作者Javier Castro
相关产品推荐
相关产品推荐

