我正在為我的 customdatset 類撰寫一個腳本,但是Index out of range每當我使用 for 回圈訪問資料時都會出現錯誤,如下所示:
cd = CustomDataset(df)
for img, target in cd:
pass
我意識到我可能在讀取一些影像時遇到問題(如果它們已損壞),因此我實作了一個random_on_error功能,如果當前影像有問題,它會選擇隨機影像。我確信這就是問題所在。正如我注意到的那樣,讀取資料集中的所有 2160 張影像時沒有任何問題(我列印每次迭代的索引號)但回圈不會停止并讀取第 2161 張影像,這會導致Index out of range通過讀取處理的例外隨機影像。這種情況永遠持續下去。
這是我的課:
class CustomDataset(Dataset):
def __init__(self, data: pd.DataFrame, augmentations=None, exit_on_error=False, random_on_error: bool = True):
"""
:param data: Pandas dataframe with paths as first column and target as second column
:param augmentations: Image transformations
:param exit_on_error: Stop execution once an exception rises. Cannot be used in conjunction with random_on_error
:param random_on_error: Upon an exception while reading an image, pick a random image and process it instead.
Cannot be used in conjuntion with exit_on_error.
"""
if exit_on_error and random_on_error:
raise ValueError("Only one of 'exit_on_error' and 'random_on_error' can be true")
self.image_paths = data.iloc[:, 0].to_numpy()
self.targets = data.iloc[:, 1].to_numpy()
self.augmentations = augmentations
self.exit_on_error = exit_on_error
self.random_on_error = random_on_error
def __len__(self):
return self.image_paths.shape[0]
def __getitem__(self, index):
image, target = None, None
try:
image, target = self.read_image_data(index)
except:
print(f"Exception occurred while reading image, {index}")
if self.exit_on_error:
print(self.image_paths[index])
raise
if self.random_on_error:
random_index = np.random.randint(0, self.__len__())
print(f"Replacing with random image, {random_index}")
image, target = self.read_image_data(random_index)
else: # todo implement return logic when self.random_on_error is false
return
if self.augmentations is not None:
aug_image = self.augmentations(image=image)
image = aug_image["image"]
image = np.transpose(image, (2, 0, 1))
return (
torch.tensor(image, dtype=torch.float),
torch.tensor(target, dtype=torch.long)
)
def read_image_data(self, index: int) -> ImagePlusTarget:
# reads image, converts to 3 channel ndarray if image is grey scale and converts rgba to rgb (if applicable)
target = self.targets[index]
image = io.imread(self.image_paths[index])
if image.ndim == 2:
image = np.expand_dims(image, 2)
if image.shape[2] > 3:
image = color.rgba2rgb(image)
return image, target
我相信問題出在 中的except塊(第 27 行)__getitem__(),因為當我洗掉它時,代碼作業正常。但我看不出這里有什么問題。
任何幫助表示贊賞,謝謝
uj5u.com熱心網友回復:
您如何期望 python 知道何時停止從您的CustomDataset.
__getitem__在中定義方法CustomDataset使其成為python 中的可迭代物件。也就是說,python 可以一個一個地迭代CustomDataset's 的專案。但是,可迭代物件必須引發StopIteration或者IndexError讓 python 知道它到達了迭代的結尾。
您可以更改回圈以顯式使用__len__您的資料集:
for i in range(len(cd)):
img, target = cd[i]
或者,如果超出范圍,您應該確保您raise IndexError來自資料集。index這可以使用多個except子句來完成。
就像是:
try:
image, target = self.read_image_data(index)
except IndexError:
raise # do not handle this error
except:
# treat all other exceptions (corrupt images) here
...
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/437705.html
上一篇:django-React-Axios:資料未保存在資料庫中
下一篇:shaded.databricks.org.apache.hadoop.fs.azure.AzureException:掛載后嘗試列出目錄時出現例外
