使用OpenCvSharp调用Logitech C920摄像头出现彩色条纹问题求助
OpenCvSharp调用Logitech C920摄像头显示彩色条纹问题排查与解决
问题描述
- 现象:使用OpenCvSharp调用摄像头采集图像时,屏幕仅显示移动的彩色条纹
- 环境:Windows 11系统、i5-10400处理器、16GB内存,Logitech C920摄像头(已确认在Logitech Capture等软件中可正常工作,系统隐私设置无异常)
- 所用代码:
using OpenCvSharp; class Program { static void Main() { // Create the video capture object using (VideoCapture capture = new VideoCapture(0, VideoCaptureAPIs.DSHOW)) { capture.Set(VideoCaptureProperties.FrameWidth, 320); capture.Set(VideoCaptureProperties.FrameHeight, 240); // Check if the camera was opened correctly if (!capture.IsOpened()) { Console.WriteLine("Could not open the camera."); return; } // Create a window to display the camera video Cv2.NamedWindow("Camera Capture"); // Loop to capture and display the camera video while (true) { // Capture a frame from the camera Mat frame = new Mat(); capture.Read(frame); // Check if the frame is empty if (frame.Empty()) break; // Display the frame in the window Cv2.ImShow("Camera Capture", frame); // Check if the 'Esc' key was pressed (27 is the ASCII code for 'Esc') if (Cv2.WaitKey(500) == 27) break; } // Close the window and release resources Cv2.DestroyAllWindows(); } } }
排查与解决方法
1. 更换视频捕获后端
Windows 11对Media Foundation(MSMF)的兼容性优于DSHOW,尝试替换后端:
using (VideoCapture capture = new VideoCapture(0, VideoCaptureAPIs.MSMF))
2. 强制指定摄像头编码格式
Logitech C920支持MJPEG编码,强制设置该格式可避免格式转换异常:
using (VideoCapture capture = new VideoCapture(0, VideoCaptureAPIs.DSHOW)) { // 先设置编码格式,再调整分辨率 capture.Set(VideoCaptureProperties.FourCC, VideoWriter.FourCC('M', 'J', 'P', 'G')); capture.Set(VideoCaptureProperties.FrameWidth, 320); capture.Set(VideoCaptureProperties.FrameHeight, 240); // 后续代码不变 }
3. 调整帧读取与显示参数
- 复用
Mat对象避免资源泄漏 - 降低
WaitKey参数值,减少帧延迟导致的显示异常:
Mat frame = new Mat(); while (true) { capture.Read(frame); if (frame.Empty()) break; Cv2.ImShow("Camera Capture", frame); // 将WaitKey(500)改为WaitKey(1),提升帧率 if (Cv2.WaitKey(1) == 27) break; } frame.Release();
4. 验证分辨率兼容性
尝试使用C920原生支持的分辨率(如1280x720、1920x1080)替换320x240,避免非标准分辨率导致的格式错误。
5. 更新OpenCvSharp版本
通过NuGet安装最新稳定版,修复旧版本的兼容性bug:
Install-Package OpenCvSharp4 Install-Package OpenCvSharp4.runtime.win
内容的提问来源于stack exchange,提问作者Sábio dos seis caminhos
相关产品推荐
相关产品推荐

