OSError: image file is truncated与PIL.UnidentifiedImageError: cannot identify image file的解决方案

编程入门 行业动态 更新时间:2024-10-27 04:28:05

原因分析

在我们使用 PIL 处理图像数据的时候。如果我们的数据集里的某些图片部分损坏或者直接打不开了,就会出现一些错误。比如这个错误OSError: image file is truncated,又或者是PIL.UnidentifiedImageError: cannot identify image file。

————————————————————————————————————————

解决方案

1.手动更替这个受损的图片

这个方法适用于受损数据量少的数据集

2.将无用的数据直接抛掉

from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True

这个方法的运用的意思是 当遇到数据截断的图片时,PIL会直接break,跳出函数,不报错,进行下一个。这个方法适用于错误 OSError: image file is truncated

3.使用try except跳过这个异常

            try:
                real_input = Image.open(img_dir).convert('RGB')
                input_images = self.img_transform(real_input)
                input_images = input_images[2, :, :]
                input_images = np.expand_dims(input_images, axis=0)

                bufImg = Image.open(gt_dir).convert('RGB')
                dilated_bufImg = self.img_transform(bufImg)
                dilated_bufImg = dilated_bufImg[2, :, :]
                output_images = np.expand_dims(dilated_bufImg, axis=0)

                sample_info = {}
                sample_info['input_images'] = input_images
                sample_info['output_images'] = output_images
                return sample_info

            except:
                print('ERROR, Path: ', img_dir)
                img_dir = os.path.join(self.imageset_dir, "004255_2.png")
                real_input = Image.open(img_dir).convert('RGB')
                input_images = self.img_transform(real_input)
                input_images = input_images[2, :, :]
                input_images = np.expand_dims(input_images, axis=0)

                sample_info = {}
                sample_info['input_images'] = input_images
                sample_info['output_images'] = input_images
                return sample_info

我这里是将受损的图片用正常的图片进行代替并返回。如果不返回值,batch会缺少一个数据,后面会报错TypeError的错。这个方法适用于 PIL.UnidentifiedImageError: cannot identify image file

更多推荐

OSError: image file is truncated与PIL.UnidentifiedImageError: cannot identify ima

本文发布于:2023-06-14 05:07:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1441427.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:解决方案   file   image   OSError   truncated

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!