OSError:图像文件被截断

aba*_*der 6 python python-imaging-library

当我处理一堆图像时,其中一个图像出现此错误

File "/home/tensorflowpython/firstmodel/yololoss.py", line 153, in data_generator
    image, box = get_random_data(annotation_lines[i], input_shape, random=True)
  File "/home/tensorflowpython/firstmodel/yololoss.py", line 226, in get_random_data
    image = image.resize((nw,nh), Image.BICUBIC)
  File "/home/tensorflowpython/kenv/lib/python3.6/site-packages/PIL/Image.py", line 1858, in resize
    self.load()
  File "/home/tensorflowpython/kenv/lib/python3.6/site-packages/PIL/ImageFile.py", line 247, in load
    "(%d bytes not processed)" % len(b)
OSError: image file is truncated (25 bytes not processed)
Run Code Online (Sandbox Code Playgroud)

我已经尝试过这里建议的解决方案,但它不起作用

我的代码看起来像这样

from PIL import Image

def get_random_data(annotation_line, input_shape, random=True, max_boxes=20, jitter=.3, hue=.1, sat=1.5, val=1.5, proc_img=True):
    Image.LOAD_TRUNCATED_IMAGES = True    
    line = annotation_line.split()
    image = Image.open(line[0])
    iw, ih = image.size
    h, w = input_shape
    box = np.array([np.array(list(map(int,box.split(',')))) for box in line[1:]])
    try:
       image.load()
    except IOError:
        pass # You can always log it to logger
    if not random:
        # resize image
        scale = min(w/iw, h/ih)
        nw = int(iw*scale)
        nh = int(ih*scale)
        dx = (w-nw)//2
        dy = (h-nh)//2
        image_data=0
        if proc_img:
            image = image.resize((nw,nh), Image.BICUBIC)
            new_image = Image.new('RGB', (w,h), (128,128,128))
            new_image.paste(image, (dx, dy))
            image_data = np.array(new_image)/255.

        # correct boxes
        box_data = np.zeros((max_boxes,5))
        if len(box)>0:
            np.random.shuffle(box)
            if len(box)>max_boxes: box = box[:max_boxes]
            box[:, [0,2]] = box[:, [0,2]]*scale + dx
            box[:, [1,3]] = box[:, [1,3]]*scale + dy
            box_data[:len(box)] = box

        return image_data, box_data

    # resize image
    new_ar = w/h * rand(1-jitter,1+jitter)/rand(1-jitter,1+jitter)
    scale = rand(.25, 2)
    if new_ar < 1:
        nh = int(scale*h)
        nw = int(nh*new_ar)
    else:
        nw = int(scale*w)
        nh = int(nw/new_ar)

    image = image.resize((nw,nh), Image.BICUBIC) #error occurs here
Run Code Online (Sandbox Code Playgroud)

我的错误和之前的解决方案之间的区别是,我的错误是操作系统错误,解决方案是IO错误

编辑:我已经找出导致此错误的图像,可以从此链接下载它

rol*_*f82 12

我尝试了您与截断图像链接的解决方案,它有效。在尝试应用此解决方案时,您犯了一个小错误:您必须设置ImageFile.LOAD_TRUNCATED_IMAGES=True,而不是Image.LOAD_TRUNCATED_IMAGES

LOAD_TRUNCATED_IMAGES最初并不存在于Image模块中,因此当您Image.LOAD_TRUNCATED_IMAGES=True设置一个库未使用的新变量时。

所以我认为你必须这样做:

from PIL import ImageFile, Image
ImageFile.LOAD_TRUNCATED_IMAGES = True

image = Image.open("00090.jpg")
# resize now doesn't fail
image.resize((h, w), Image.BICUBIC)
Run Code Online (Sandbox Code Playgroud)