最近在网上下了一批jpg图片作为训练集,发现使用opencv的imread读取图片时总是出现Premature end of JPEG file报错,查找了网上资料发现时jpg图像受损导致,遂问gpt写了一段代码用以检测错误图片:
import os
import cv2
from skimage.io import imread
def check_image_integrity(image_path):
try:
img = imread(image_path)
return False
except Exception as e:
print(f"Error reading file {image_path}: {e}")
return True
def check_images_in_folder(folder_path):
intact_images = []
corrupted_images = []
for filename in os.listdir(folder_path):
if filename.endswith(('.jpg', '.jpeg', '.png', '.bmp', '.gif')):
image_path = os.path.join(folder_path, filename)
check_image_integrity(image_path)
return intact_images, corrupted_images
# 示例用法
folder_path = "your_folder"
intact_images, corrupted_images = check_images_in_folder(folder_path)