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

修复OpenCV JPEG读取错误
本文介绍如何修改OpenCV源代码以捕获损坏的JPEG文件读取错误,并提供了解决方法,包括如何添加自定义错误处理函数以及编译配置说明。
错误类型: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 "<stdin>", line 1, in <module>
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 fileor directory
 
解决方法如下:
修改modules/contrib/src/rgbdodometry.cpp代码:
#include<unsupported/Eigen/MatrixFunctions> 修改为 #include</usr/local/include/eigen3/unsupported/Eigen/MatrixFunctions>
 
### 如何修复包含 &#39;premature end of data segment&#39; 和 &#39;extraneous bytes before marker 0xd9&#39; 错误的 JPEG 图像文件 当遇到 `Corrupt JPEG data: XX extraneous bytes before marker 0xXX` 或者 `premature end of data segment` 的错误提示时,这通常意味着JPEG 文件存在数据损坏或编码不一致的情况[^1]。 #### 方法一:使用在线工具和服务 一些网站提供免费服务来尝试自动修复受损的JPEG 文件。这些平台利用复杂的算法分析并尽可能恢复原始图像质量。然而,在上传敏感照片之前应谨慎考虑隐私问题。 #### 方法二:借助专门软件手动编辑 对于更精细控制的需求,可以选择安装图形处理应用程序如 Adobe Photoshop、GIMP 等支持读取部分破坏但仍可识别片段的功能来进行裁剪或其他形式的部分保留性修正操作;另外还有特定针对修复功能的小型实用程序比如JPEG Repair Toolbox 可供选择。 #### 方法三:编程方式批量处理(Python) 如果面对大量此类问题,则编写脚本可能是最高效的办法之一: ```python import os from PIL import Image def fix_jpeg(file_path): try: img = Image.open(file_path) img.verify() # 验证文件是否有效而不加载整个图像入内存 img.close() if not img.format == "JPEG": raise ValueError("Not a valid JPEG file.") with open(file_path,&#39;rb+&#39;) as f: content=f.read() start=content.find(b&#39;\xff\xd8&#39;) end=content.rfind(b&#39;\xff\xd9&#39;) if start != -1 and end != -1: fixed_content=content[start:end+2] f.seek(0) f.write(fixed_content) f.truncate() print(&#39;Fixed:&#39;,file_path) except Exception as e: print(&#39;Failed to process&#39;,file_path,e) for root, dirs, files in os.walk("/path/to/images"): for name in files: if name.lower().endswith(".jpg") or name.lower().endswith(&#39;.jpeg&#39;): full_file_name=os.path.join(root,name) fix_jpeg(full_file_name) ``` 此代码遍历指定目录下的所有 .jpg/.jpeg 文件,并试图移除任何位于 SOI (Start Of Image) 标记 `\xFF\xD8` 后面以及 EOI (End Of Image) 标记 `\xFF\xD9` 前面多余的字节序列[^2]。 上述方法可以帮助缓解由 libjpeg 库引发的相关异常状况,但需要注意的是并非所有的损坏都能被完全纠正,特别是那些严重损毁以至于无法解析基本结构的信息丢失情形下[^3]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值