Corrupt JPEG data: 36 extraneous bytes before marker 0xd9,opencv获取imread报错方法

错误类型:Corrupt JPEG data: 36 extraneous bytes before marker 0xd9
原因:opencv imread默认有错误直接跳过,不会返回,需要修改源码才能使之报错

① 修改 modules/highgui/src/grfmt_jpeg.cpp 文件,在 error_exit()函数下面添加以下代码:
METHODDEF(void)
output_message( j_common_ptr cinfo )
{
char buffer[JMSG_LENGTH_MAX];

/* Create the message */
(*cinfo->err->format_message) (cinfo, buffer);

/* Default OpenCV error handling instead of print */
CV_Error(CV_StsError, buffer);
}

②在 decoder error handler 添加以上函数的实现:
state->cinfo.err = jpeg_std_error(&state->jerr.pub);
state->jerr.pub.error_exit = error_exit;
state->jerr.pub.output_message = output_message; /* Add this line */

③ 在 encoder error handler 添加以上函数的实现:
cinfo.err = jpeg_std_error(&jerr.pub);
jerr.pub.error_exit = error_exit;
jerr.pub.output_message = output_message; /* Add this line */

④ 修改完后重新编译opencv,在imread错误的jpg文件后会报错了:
>>> cv2.imread("/var/opencv/bad_image.jpg")
OpenCV Error: Unspecified error (Corrupt JPEG data: 1137 extraneous bytes before marker 0xc4) in output_message, file /var/opencv/opencv-2.4.9/modules/highgui/src/grfmt_jpeg.cpp, line 180
Traceback (most recent call last):
File "", line 1, in
cv2.error: /var/opencv/opencv-2.4.9/modules/highgui/src/grfmt_jpeg.cpp:180: error: (-2) Corrupt JPEG data: 1137 extraneous bytes before marker 0xc4 in function output_message

这时,opencv写imread的代码 一定要用 try catch语法:
try{
im = imread( " XXX.jpg" );
}
catch(char *str){
xxx
}




ps:如果linux系统重新装了eigen3,那么编译opencv会报错:
[..]/ modules / contrib / src / rgbdodometry . cpp : 65 : 47 : fatal error : unsupported / Eigen / MatrixFunctions : No such file or directory
解决方法如下:
修改modules/contrib/src/rgbdodometry.cpp代码:
#include / Eigen / MatrixFunctions> 修改为 #include

你可能感兴趣的:(opencv)