ValueError: The number of elements in ‘fill‘ does not match the number of bands of the image (3 != 4

Posted WinstonYF

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ValueError: The number of elements in ‘fill‘ does not match the number of bands of the image (3 != 4相关的知识,希望对你有一定的参考价值。

错误:ValueError: The number of elements in ‘fill’ does not match the number of bands of the image (3 != 4)

  File "/home/lxn/anaconda3/envs/mutilLabelClass/lib/python3.6/site-packages/torch/utils/data/_utils/fetch.py", line 44, in fetch
    data = [self.dataset[idx] for idx in possibly_batched_index]
  File "/home/lxn/anaconda3/envs/mutilLabelClass/lib/python3.6/site-packages/torch/utils/data/_utils/fetch.py", line 44, in <listcomp>
    data = [self.dataset[idx] for idx in possibly_batched_index]
  File "resnet50.py", line 59, in __getitem__
    img = self.transforms(img)
  File "/home/lxn/anaconda3/envs/mutilLabelClass/lib/python3.6/site-packages/torchvision/transforms/transforms.py", line 60, in __call__
    img = t(img)
  File "/home/lxn/anaconda3/envs/mutilLabelClass/lib/python3.6/site-packages/torch/nn/modules/module.py", line 889, in _call_impl
    result = self.forward(*input, **kwargs)
  File "/home/lxn/anaconda3/envs/mutilLabelClass/lib/python3.6/site-packages/torchvision/transforms/transforms.py", line 1419, in forward
    return F.affine(img, *ret, interpolation=self.interpolation, fill=fill)
  File "/home/lxn/anaconda3/envs/mutilLabelClass/lib/python3.6/site-packages/torchvision/transforms/functional.py", line 1071, in affine
    return F_pil.affine(img, matrix=matrix, interpolation=pil_interpolation, fill=fill)
  File "/home/lxn/anaconda3/envs/mutilLabelClass/lib/python3.6/site-packages/torchvision/transforms/functional_pil.py", line 268, in affine
    opts = _parse_fill(fill, img, '5.0.0')
  File "/home/lxn/anaconda3/envs/mutilLabelClass/lib/python3.6/site-packages/torchvision/transforms/functional_pil.py", line 255, in _parse_fill
    raise ValueError(msg.format(len(fill), num_bands))
ValueError: The number of elements in 'fill' does not match the number of bands of the image (3 != 4)

找到报错的地方:
home/lxn/anaconda3/envs/mutilLabelClass/lib/python3.6/site-packages/torchvision/transforms/functional_pil.py

添加中间输出变量

def _parse_fill(fill, img, min_pil_version, name="fillcolor"):
    # Process fill color for affine transforms
    major_found, minor_found = (int(v) for v in PILLOW_VERSION.split('.')[:2])
    major_required, minor_required = (int(v) for v in min_pil_version.split('.')[:2])
    if major_found < major_required or (major_found == major_required and minor_found < minor_required):
        if fill is None:
            return {}
        else:
            msg = ("The option to fill background area of the transformed image, "
                   "requires pillow>={}")
            raise RuntimeError(msg.format(min_pil_version))

    num_bands = len(img.getbands())
    print("fill::",fill)
    print("num_bands::",num_bands)
    if fill is None:
        fill = 0
    if isinstance(fill, (int, float)) and num_bands > 1:
        fill = tuple([fill] * num_bands)
    if isinstance(fill, (list, tuple)):
        if len(fill) != num_bands:
            msg = ("The number of elements in 'fill' does not match the number of "
                   "bands of the image ({} != {})")
            raise ValueError(msg.format(len(fill), num_bands))

        fill = tuple(fill)

    return {name: fill}

在这里插入图片描述
问题找到了,这里有一个的num_band是4,其他都是3。

下面,我们就去找num_band为4的图片:
找到数据集,然后运行:

import os
import re
import json
import random
from PIL import Image

for filepath,dirnames,filenames in os.walk(r'./images'):
    
    for filename in filenames:
        #只获取图片文件
        if filename.endswith(('jpg','png','jpeg','bmp','JPG','PNG','JPEG','BMP')):
            #print(filepath+'/'+filename)
            img = Image.open(filepath+'/'+filename)
            if len(img.getbands())>3:
                print(filename)
                print(img.getbands())

输出结果:
3_16229952640004_c1s1_040i221i702i374i777.png
(‘R’, ‘G’, ‘B’, ‘A’)

这样就找到了,我的数据集里,只有一个png,其他全是jpg,那么删除这个png就解决问题了。

以上是关于ValueError: The number of elements in ‘fill‘ does not match the number of bands of the image (3 != 4的主要内容,如果未能解决你的问题,请参考以下文章

ValueError: Bin labels must be one fewer than the number of bin edges

在 Django 迁移期间收到“ValueError: Found wrong number of (0) of constraint for ...”

为啥 df.cumsum() 给出 ValueError: Wrong number of items passed, placement 意味着 1

ValueError: Found input variables with contrast numbers of samples: [75, 1] 在 Python 中是啥意思?

结合两列给出 ValueError: Wrong number of items passed 2, placement 意味着 1

valueError: This solver needs samples of at least 2 classes in the data, but the data contains only