Recent Posts
«   2025/06   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Today
Total
관리 메뉴

코드민수

[Python] 중복 이미지 제거 본문

[Python]/코드

[Python] 중복 이미지 제거

코드민수 2023. 3. 30. 11:06
BIG

지정된 디렉토리에서 중복된 이미지를 찾아서 삭제하는 방법입니다.

 

이미지 파일이 많고 파일명에 규칙이 없는 경우 중복 파일을 찾는 것은 번거롭고 어려운 작업입니다.

 

해당 코드에서는 MD5 알고리즘을 사용하여 이미지를 고유하게 식별할 수 있는 Hash 값을 추출하고

 

이를 기준으로 중복 여부를 판단하여 중복 이미지를 삭제했습니다.

from PIL import Image
import os
import hashlib

def find_duplicate_images(rootdir):
    hash_dict = {}
    duplicates = []
    for subdir, dirs, files in os.walk(rootdir):
        for file in files:
            filepath = os.path.join(subdir, file)
            # Open the image and calculate its hash
            with open(filepath, 'rb') as f:
                img_hash = hashlib.md5(f.read()).hexdigest()
            # Check if the hash already exists
            if img_hash in hash_dict:
                duplicates.append(filepath)
            else:
                hash_dict[img_hash] = filepath
    return duplicates

def delete_duplicate_images(duplicates):
    for file in duplicates:
        os.remove(file)
        print("Deleted:", file)

if __name__ == '__main__':
    rootdir = 'D:/image' # root directory
    duplicates = find_duplicate_images(rootdir)
    if duplicates:
        print("Duplicate images found:")
        for file in duplicates:
            print(file)
        delete_duplicate_images(duplicates)
    else:
        print("No duplicate images found.")

rootdir 만 이미지를 탐색할 폴더로 지정하주시고 실행하면 됩니다.

 

코드 실행 시 중복 이미지가 바로 삭제되기 때문에 필요하다면 백업을 해두시는 것이 좋습니다.

LIST