我使用double for循环来遍历Picture文件夹中的文件。如果第一张图片等于第二张图片,则从文件夹中删除第二张图片,并从我要遍历的文件列表中删除该图片。我的程序留下了一些重复的图像,并且没有删除它们,但是当我再次运行该程序时,它会删除重复的图像。如何正确遍历文件,以便删除所有重复的图像?
我已尝试减少不必要的if,else循环,以确保文件不会在程序中丢失。
path = "Pictures"
directory = os.listdir(path)
for first_file in directory:
for second_file in directory:
if first_file == second_file:
continue
if first_file.endswith(".jpg") and second_file.endswith(".jpg"):
first_file_path = R"Pictures\{}".format(first_file)
second_file_path = R"Pictures\{}".format(second_file)
img1 = cv2.imread(first_file_path, 1)
img2 = cv2.imread(second_file_path, 1)
img1 = cv2.resize(img1, (100,100))
img2 = cv2.resize(img2, (100,100))
difference = cv2.subtract(img1, img2)
b, g, r = cv2.split(difference)
if cv2.countNonZero(b) == 0 and cv2.countNonZero(g) == 0 and cv2.countNonZero(r) == 0:
os.remove(second_file_path)
directory.remove(second_file)