常見錯誤現象
- 運行報錯 `OpenCV Error: Assertion failed (size.width>0 && size.height>0)` → `imread` 讀取失敗,`Mat` 為空。
- 調試時變量顯示 `` / 亂碼 → 釋放/雙重釋放、指針懸空。
核心排查清單
- 圖片路徑:
- 相對路徑基於**工作目錄**(默認項目目錄 `$(ProjectDir)`),非源文件目錄。
- 屬性 → Configuration Properties → Debugging → **Working Directory** 設置為圖片所在目錄,或代碼用絕對路徑 `C:/data/lena.jpg`。
- 將圖片設置為「複製到輸出目錄」:Solution Explorer → 圖片 → Properties → **Copy to Output Directory = Copy if newer**。
- 空指針防護**:
cv::Mat img = cv::imread("lena.jpg");
if (img.empty()) {
std::cerr << "Failed to load image!" << std::endl;
return -1;
}
cv::imshow("Window", img); // 確保非空再顯示
- OpenCV 版本與 VS 版本匹配**:
- OpenCV 4.x 需 VS2015+ (VC14+);VS2013 (VC12) 僅支援 OpenCV 3.x 官方預編譯包。
- 或自行用 CMake 編譯匹配版本。
- 調試技巧**:
- 在所有指針解引用前加 `if (ptr) { ... }`。
- 用 `cv::format` / `std::cout` 打印關鍵變量(路徑、矩陣尺寸、通道數)。
- 啟用「運行時檢查」:Properties → C/C++ → Code Generation → **Basic Runtime Checks = Both (/RTC1)**。
快速驗證步驟
#include
#include
int main() {
cv::Mat img = cv::imread("lena.jpg"); // 放在項目根目錄/輸出目錄
if (img.empty()) {
std::cout << "Current working dir: " << std::filesystem::current_path() << std::endl;
return -1;
}
cv::imshow("Test", img);
cv::waitKey(0);
return 0;
}
**90% 的 VS+OpenCV 入門報錯是路徑錯或空指針,養成 `empty()` 判斷 + 絕對路徑/複製到輸出目錄習慣即可避開。**