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就解决问题了。

这个错误通常是因为指定的列名数量与文件中列的数量不匹配。请检查你指定的列名数量是否正确,并确保文件中列的数量与指定的列名数量相同。如果你没有指定列名,则可以通过设置`header=None`来告诉Pandas该文件中没有列名。如果你指定的列名数量与文件中列的数量不同,可以尝试将列名设置为`None`,让Pandas自动推断列名。你可以尝试以下代码: ``` data = pd.read_csv('/home/w123/Documents/data-analysis/40-0-data/ratio/40-0-ratio.txt', header=None, usecols=[1, 2]) y = data.iloc[:, :-1].values.reshape(-1, 1) X = data.iloc[:, -1].values.reshape(-1, 1) regressor = LinearRegression() regressor.fit(X, y) y_pred = regressor.predict(X) print("Regression Function: y = {:.2f} + {:.2f}x".format(regressor.intercept_[0], regressor.coef_[0][0])) plt.scatter(X, y, color='blue') plt.plot(X, y_pred, color='red') data2 = pd.read_csv('/home/w123/Documents/data-analysis/40-0-data/ratio/40-5-ratio.txt', header=None, usecols=[1, 2]) y2 = data2.iloc[:, :-1].values.reshape(-1, 1) X2 = data2.iloc[:, -1].values.reshape(-1, 1) regressor2 = LinearRegression() regressor2.fit(X2, y2) y2_pred = regressor2.predict(X2) print("Regression Function: y = {:.2f} + {:.2f}x".format(regressor2.intercept_[0], regressor2.coef_[0][0])) plt.scatter(X2, y2, color='green') plt.plot(X2, y2_pred, color='orange') plt.legend(['Regression Line 2', 'Observations 2']) data3 = pd.read_csv('/home/w123/Documents/data-analysis/40-0-data/ratio/40-10-ratio.txt', header=None, usecols=[1, 2]) y3 = data3.iloc[:, :-1].values.reshape(-1, 1) X3 = data3.iloc[:, -1].values.reshape(-1, 1) regressor3 = LinearRegression() regressor3.fit(X3, y3) y3_pred = regressor3.predict(X3) print("Regression Function: y = {:.2f} + {:.2f}x".format(regressor3.intercept_[0], regressor.coef_[0][0])) plt.scatter(X3, y3, color='purple') plt.plot(X3, y3_pred, color='yellow') plt.title('Linear Regression') plt.xlabel('Independent Variable') plt.ylabel('Dependent Variable') plt.legend(['Regression Line 1', 'Observations 1', 'Regression Line 2', 'Observations 2', 'Regression Line 3', 'Observations 3']) plt.show() ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值