I am trying to resize and normalise all the images in a folder but at the end, it throws an error saying list is out of range
def resize():
data = []
img_size = 244
data_dir = r'C:\technocolab project2\archive'
for img in os.listdir(data_dir):
try:
imgPath = os.path.join(data_dir,img)
images = cv2.imread(imgPath, cv2.IMREAD_GRAYSCALE)
image_resized = cv2.resize(images,(img_size,img_size))
data.append(img_resized)
except:
pass
return data
data = resize()
print(len(data))
sample = data[0]
print(sample.shape)
the error that it shows is given in the figure that says:
IndexError: list index out of range
CodePudding user response:
You are returning your data list in the first iteration of your for loop. You should untab your return return data statemente at the same level of the for loop.
Edit: This code works perfectly for me
import cv2
import os
def resize():
data = []
img_size = 244
data_dir = "./imgs"
for img in os.listdir(data_dir):
try:
imgPath = os.path.join(data_dir,img)
images = cv2.imread(imgPath, cv2.IMREAD_GRAYSCALE)
image_resized = cv2.resize(images,(img_size,img_size))
data.append(image_resized)
except:
pass
return data
data = resize()
print(len(data))
sample = data[0]
print(sample.shape)
CodePudding user response:
Well, what is happening is: the img_resized
variable is not declared and the exception is triggered, so you have pass
, then you return the empty array, since return
is inside the loop.
Fix the variable name and put return
outside the loop.