QtCreator 中使用 OpenCV VideoCapture,第一次開啟攝像頭正常,點擊「停止調試」後再次運行報錯:libv4l2: error turning on stream: Invalid argument。雖然解構函數呼叫了 cap.release(),但資源未釋放。
QtCreator「停止調試」按鈕會強制終止進程(SIGKILL),不會執行 C++ 解構函數,導致 VideoCapture 未釋放 /dev/video* 設備鎖定。直接點視窗關閉鍵(正常退出)則會執行解構函數,故可重複開啟。
VideoCapture cap;
void openCamera(int camId) {
if (cap.isOpened()) cap.release(); // 確保釋放舊實例
cap.open(camId);
if (!cap.isOpened()) throw runtime_error("無法開啟攝像頭");
}
void MainWindow::closeEvent(QCloseEvent *event) {
if (cap.isOpened()) cap.release();
QMainWindow::closeEvent(event);
}
在終端機執行 lsof /dev/video0 確認進程是否仍佔用設備。若殘留,手動 kill -9 PID 後再測試。
OpenCV 編譯時啟用 -D WITH_GSTREAMER=ON,運行時設定 cap.open("v4l2src device=/dev/video0 ! video/x-raw,format=BGR ! appsink", CAP_GSTREAMER),GStreamer 管線在進程結束時由系統自動清理,較穩健。