transforms.RandomCrop((img_h, img_w)) raise ValueError(empty range for randrange)(%d,%d, %d)

问题

  File "E:/wj-lab/expStad/train.py", line 446, in 
    losses=train(epoch)
  File "E:/wj-lab/expStad/train.py", line 239, in train
    for batch_idx, (input1, input2, label1, label2) in enumerate(tqdm(trainloader)):

  File "D:\Anaconda3\envs\python35\lib\site-packages\tqdm\_tqdm.py", line 979, in __iter__
    for obj in iterable:
  File "D:\Anaconda3\envs\python35\lib\site-packages\torch\utils\data\dataloader.py", line 264, in __next__
    batch = self.collate_fn([self.dataset[i] for i in indices])

  File "D:\Anaconda3\envs\python35\lib\site-packages\torch\utils\data\dataloader.py", line 264, in 
    batch = self.collate_fn([self.dataset[i] for i in indices])

  File "E:\wj-lab\expStad\data_loader.py", line 38, in __getitem__
    img1 = self.transform(img1)

  File "D:\Anaconda3\envs\python35\lib\site-packages\torchvision\transforms\transforms.py", line 49, in __call__
    img = t(img)
  File "D:\Anaconda3\envs\python35\lib\site-packages\torchvision\transforms\transforms.py", line 421, in __call__
    i, j, h, w = self.get_params(img, self.size)

  File "D:\Anaconda3\envs\python35\lib\site-packages\torchvision\transforms\transforms.py", line 400, in get_params
    j = random.randint(0, w - tw)
  File "D:\Anaconda3\envs\python35\lib\random.py", line 227, in randint
    return self.randrange(a, b+1)
  File "D:\Anaconda3\envs\python35\lib\random.py", line 205, in randrange
    
raise ValueError("empty range for randrange() (%d,%d, %d)" % (istart, istop, width))

ValueError: empty range for randrange() (0,-59, -59)

出错源码

       normalize=transforms.Normalize(mean=[0.485,0.456,0.406], std=[0.229,0.224,0.225]) 
       transform_train = transforms.Compose([ 
                      transforms.ToPILImage(), 
                      transforms.Pad(10),
                      transforms.RandomCrop((348, 204)),
                      transforms.RandomHorizontalFlip(), 
                      transforms.ToTensor(),
                      normalize, ])

原因

随机裁剪越界,transforms.RandomCrop 调用 random.randint(a,b),生成的随机整数n取值范围(a<=n<=b),如果a=b,则n=a,如果a>b,就会报错

解决办法

注意到 ValueError: empty range for randrange() (0,-59, -59)   凡是出现类似错误的,都是调试数值范围

故 正确取值范围极限在  348-59-1=288      204-59-1=144    即最大取值范围在(288,144)

 transforms.RandomCrop((288, 144))

 normalize=transforms.Normalize(mean=[0.485,0.456,0.406], std=[0.229,0.224,0.225]) 
       transform_train = transforms.Compose([ 
                      transforms.ToPILImage(), 
                      transforms.Pad(10),
                      transforms.RandomCrop((288, 144)), # 修改处
                      transforms.RandomHorizontalFlip(), 
                      transforms.ToTensor(),
                      normalize, ])

 

你可能感兴趣的:(bug)