首页 > 解决方案 > 如何修复 OpenCV 中的“抛出异常”错误?

问题描述

我在 Visual Studio 2017 中编译 OpenCV 程序时遇到错误。当我使用该函数imwrite保存灰度图像时发生错误。你可以在这里看到截图

这里的屏幕截图

我试图将文件复制opencv_world320.dll到我的目录项目但仍然不行。

这是代码:

#include <opencv2/opencv.hpp>
#include <opencv/highgui.h>
#include <iostream>
using namespace std;
using namespace cv;

int main(int argv, char** argc)
{
   Mat img_original = imread("lisa.jpg",CV_LOAD_IMAGE_UNCHANGED);
   Mat img_grayscale = imread("lisa.jpg", CV_LOAD_IMAGE_GRAYSCALE);

   imshow("Lisa-Original", img_original);
   imshow("Lisa-Grayscale", img_grayscale);

   imwrite("LisaGray.jpg", img_grayscale);
   waitKey(0);
   return 0;
}

这是一个例外:

在 1_open_image_lisa.exe 中的 0x00007FFC7D9B86C2 (opencv_world320.dll) 处引发异常:0xC0000005:访问冲突读取位置 0x000001926A40F000。发生了

标签: c++imagevisual-studioopencvexception

解决方案


The code isn't wrong by itself, and even if the imread wasn't successful, the imwrite wouldn't throw. (Although, empty cv::Mat written to jpg file create empty files, which aren't recognize as valid image files).

So, to pinpoint your exact problem, use the try/catch mechanism:

try {
    imshow("Lisa-Original", img_original);
    imshow("Lisa-Grayscale", img_grayscale);

    imwrite("LisaGray.jpg", img_grayscale);
}
catch(cv::Exception& e) {
    std::cout << e.msg << std::endl;
}

On my computer, when imwrite fail because of the format, the message is:

OpenCV(4.0.0) D:\Dev\Opencv4\opencv-4.0.0\opencv-4.0.0\modules\imgcodecs\src\loadsave.cpp:661: error: (-2:Unspecified error) could not find a writer for the specified extension in function 'cv::imwrite_'

In this case, try to use another format to save the picture, and/or check if opencv was compiled with the correct options and libraries.


推荐阅读