AL B
AL B

Reputation: 223

Calculating index of images with uneven sizes

I am trying to calculate a sharpness index of several images that have uneven sizes inside a loop.

I have made a function (gder) and I used it inside the loop, however I get an error message which i suspect is due to the uneven image size.

import torch
import torchvision.transforms as transforms
import torchvision.datasets as datasets
import torchvision.models as models
import torch.nn as nn
import torch.optim as optim
import numpy as np
import os
from PIL import Image
import numpy as np

dirname='/home/Data/Images/'
nimages=[]
for name in os.listdir(dirname):
    im=Image.open(os.path.join(dirname,name))
    imarray=np.array(im)
    nimages.append(imarray)

nimages=np.asarray(nimages)

import array
derv=[]

def gder(image):
    gy,gx=np.gradient(image)
    gnorm = np.sqrt(gx**2 + gy**2)
    return np.average(gnorm)

for i in range (0, 5):
    derv[i]=gder(nimages[i])

The last loop gives me the error Traceback (most recent call last): File "", line 2, in IndexError: list assignment index out of range

I suspect the problem is that the images are a different size. Does anyone know how to get around this problem or suggest another way to do this?

Upvotes: 0

Views: 52

Answers (2)

brechmos
brechmos

Reputation: 1316

It is just a matter of appending:

for i in range (0, 5):
    derv.append(gder(nimages[i]))

Your list is empty so you can't add things in there without using an append.

Upvotes: 1

bnaecker
bnaecker

Reputation: 6430

The issue is derv = []. By doing this, you set it to an empty list, but then you try to assign to various indices, say index 1. That doesn't exist, because the list has size 0. You need to call derv.append(gder(nimages[i])) to add a new value to the list.

Upvotes: 2

Related Questions