I keep running into "IndexError: list index out of range" but I can't seem to squash it. It's a simple program, but chasing issues in VSCode kind of causes more issues than it solves and I'm too new to coding to parse what's happening.
I have a folder of 50 similar png's that I have reduced to 512x512 and I want them to be sorted by sequentially finding the next unsorted image with image_difference's min_diff and building a new list of images based on that before renaming all files based on their order in the new list.
What is causing the indexerror? I've tried a few things from forums, but I can't tell the good from bad and it's all run together at this point.
This is what I've got so far: `
`import os
import cv2
import numpy as np
from skimage.metrics import structural_similarity as ssim
from tqdm import tqdm
from itertools import islice
from itertools import count
# path to the folder containing the images
folder_path = "D:\\resized"
# list all the images in the folder
images = [f for f in os.listdir(folder_path) if f.endswith(".jpg") or f.endswith(".png")]
# sort the images in lexicographic order
images.sort()
# function to calculate the difference between two images
def image_difference(img1, img2):
diff = cv2.absdiff(img1, img2)
return np.sum(diff)
# function to calculate the SSIM between two images
def image_ssim(img1, img2):
return ssim(img1, img2, win_size = 7, channel_axis=2)
# function to find the index of the image that has the smallest difference with the current image
def find_min_diff_index(current_image, images, folder_path):
min_diff = float('inf')
min_diff_index = -1
for j in count():
try:
diff = image_difference(cv2.imread(folder_path + "/" + current_image), cv2.imread(folder_path + "/" + images[j]))
if diff < min_diff:
min_diff = diff
min_diff_index = j
except IndexError:
break
return min_diff_index
# initialize the new list of images
new_images = []
# add the first image to the new list
new_images.append(images[0])
# loop through the remaining images
for i in tqdm(range(len(images))):
min_diff_index = find_min_diff_index(images[i], islice(images, i+1, len(images)),folder_path)
# check if the SSIM between current image and the next image is greater than a threshold
if min_diff_index !=-1 and image_ssim(cv2.imread(folder_path + "/" + new_images[-1]), cv2.imread(folder_path + "/" + images[min_diff_index]))> 0.8:
# add the next image with the smallest difference to the new list
new_images.append(images[min_diff_index])
# remove the added image from the list
images.pop(min_diff_index)
i -= 1
else:
# remove the current image from the list
images.pop(i)
i -= 1
# rename the images i the new order
for i in range(len(new_images)):
if new_images[i].endswith(".png"):
os.rename(folder_path + "/" + new_images[i], folder_path + "/" + str(i) + ".png")
else:
os.rename(folder_path + "/" + new_images[i], folder_path + "/" + str(i) + ".jpg")`