Reputation: 1
I have a dictionary in which each key has a certain amount of images saved. Like this:
key 1: [image1, image2, image3, image4]
After calculating the SSIM between each image of the key and the last image of the key: For example:
s1 = ssim(image4, image1)
If the value of s
is bigger than a threshold, the image is kept in the dictionary.
key 1: [image1, image2, image3, image4]
If the value of s
is less than a threshold, the image is deleted in the dictionary.
Then:
key 1: [image2, image3, image4]
But in doing this I get the error:
IndexError: pop index out of range
Can anyone tell me what is wrong?
CODE
for img in range(len(img_dict1[key])):
similarity=ssim(img_dict1[key][-1],img_dict1[key][img])
if similarity > 0.85:
continue
else:
img_dict1[key] = list(img_dict1[key]).pop(img)
Upvotes: 0
Views: 50
Reputation: 896
You are modifing the img_dict1[key]
list while you iterate its elements. So at the end of loop the list could be shorter than at begining. len(img_dict1[key])
is evaluated once, at the begining.
More pythonic is to build new list:
img_dict1[key] = [x for x in img_dict[key]
if ssim(img_dict1[key][-1], x) > 0.85]
Upvotes: 0
Reputation: 123393
You need to be careful about modifying the thing you are iterating over. To avoid that in this case you could use something called a list comprehension:
img_dict1[key] = [img_dict1[key][i] for i in range(len(img_dict1[key]))
if ssim(img_dict1[key][-1], img_dict1[key][i]) > 0.85]
This replaces the list with a new version that only has the elements in it you want.
Upvotes: 1
Reputation: 818
Do it like this:
for img in range(len(img_dict1[key])):
similarity=ssim(img_dict1[key][-1],img_dict1[key][img])
if similarity > 0.85:
continue
else:
img_dict1[key].pop(img)
Explanation: pop
automatically removes the element from the list/dictionary and modifies the list/dictionary on call. You only assign pop to a value if you want to use that value later. In your case, you don't need to assign it to anything.
Upvotes: 0