코드민수
[Python] 중복 이미지 제거 본문
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
'[Python] > 코드' 카테고리의 다른 글
[Python] 레이블 없는 이미지 찾기 (0) | 2023.04.03 |
---|---|
[Python] JSON 파일에서 오브젝트 클래스 분석 (히스토그램) (0) | 2023.03.31 |
[Python] 파이썬에서 이미지 Open하는 다양한 방법 (0) | 2023.03.27 |
[Python] 폴더 내 존재하는 파일을 텍스트 파일에 쓰기 (0) | 2023.03.26 |
[Python] xlsx → csv 변환 (0) | 2023.03.24 |