【debug】Corrupt JPEG data: premature end of data segment
数据集在读取的时候,判断一张图片是否损坏的方法也无法判断出。在训练时才出现标题处的报错。下面的代码是yolov5在数据读取时判断图片是否损坏的代码:
with open(im_file, 'rb') as f:
f.seek(-2, 2)
if f.read() != b'\xff\xd9': # corrupt JPEG
ImageOps.exif_transpose(Image.open(im_file)).save(im_file, 'JPEG', subsampling=0, quality=100)
msg = f'{prefix}WARNING: {im_file}: corrupt JPEG restored and saved'
现象:
在显示的过程中偶尔出现图像只显示一部分,剩余部分为灰色或者显示异常,并提示错误为:Corrupt JPEG data: premature end of data segment
原因:
由于下载、保存的时候出现意外,导致图片保存不完整。
解决方法:
import cv2
import numpy as np
def detect_uniform_image(image_path, threshold=0.90): //阈值根据图像的呈像可调节
# 读取图像
image = cv2.imread(image_path)
# 转换为灰度图像
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 计算像素值的直方图
hist = cv2.calcHist([gray], [0], None, [256], [0,256])
# 计算最常见的像素值的百分比
max_pixel_count = np.max(hist)
total_pixels = gray.shape[0] * gray.shape[1]
percentage = max_pixel_count / total_pixels
# 判断是否大多数像素值相同
if percentage >= threshold:
print(image_path)
else:
pass
# 图像路径
image_path = "img_path"
import os
for file in os.listdir(image_path):
# 检测图像中大多数像素值是否一样
detect_uniform_image(image_path+file)