Hash를 이용해 중복 이미지 찾기

Intro

앞선 포스팅에서 해시의 개념과 함께 해시를 이용해 텍스트, 숫자, 이미지를 고정된 길이의 문자열(해시)로 변환하는 방법을 살펴봤다.

이러한 특성을 활용하면 이미지 파일의 내용이 완전히 동일한지 비교하여 중복 이미지를 정확하게 찾아낼 수 있다.

이미지 준비

  • 총 3개의 사과, 배 이미지 파일을 준비했다.
  • 이 중 2개는 같은 사과 이미지이며, 1개는 배 이미지이다.
  • 3개의 이미지 파일은 모두 파일명이 다르다.

코드

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
import hashlib
import os
from collections import defaultdict

def file_hash(path, algo="md5", chunk_size=8192):
    h = hashlib.new(algo)
    with open(path, "rb") as f:
        for chunk in iter(lambda: f.read(chunk_size), b""):
            h.update(chunk)
    return h.hexdigest()

def hash_files_in_directory(directory_path):
    hash_map = defaultdict(list)
    for root, _, files in os.walk(directory_path):
        for name in files:
            if name.lower().endswith((".jpg", ".jpeg", ".png", ".bmp", ".gif", ".webp")):
                path = os.path.join(root, name)
                hash_map[file_hash(path)].append(path)
    return hash_map

def check_duplicates(directory_path):
    hash_map = hash_files_in_directory(directory_path)
    duplicates = {h:paths for h, paths in hash_map.items() if len(paths) > 1}
    for paths in duplicates.values():
        print("중복 이미지 : ")
        for p in paths:
            print(" ", p)

directory_path = "/data/img"
check_duplicates(directory_path)
1
2
3
중복 이미지 : 
  /data/img/img01.png
  /data/img/img02.png

Comments