How can I fix "Exception Thrown" error in OpenCV?


I meet an error while compile my OpenCV program in Visual Studio 2017. The error occurred when I used the function imwrite to save a grayscale image. You can see the screenshot here

the screen capture here

I tried to copy file opencv_world320.dll to my directory project but still not ok.

This is the code:

#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);
   return 0;

This is the exception:

Exception thrown at 0x00007FFC7D9B86C2 (opencv_world320.dll) in 1_open_image_lisa.exe: 0xC0000005: Access violation reading location 0x000001926A40F000. occurred

asked on Stack Overflow Jul 2, 2019 by Hoàng Đức • edited Jul 2, 2019 by nathancy

2 Answers


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.

answered on Stack Overflow Jul 3, 2019 by Pims

It happen to mine too. You can use "Release" configuration instead of "DEBUG"'s when you run your C++ code. It works for me, but do not know why!

answered on Stack Overflow Jun 19, 2020 by Sam

User contributions licensed under CC BY-SA 3.0