There is Python code for copy pictures and remove duplicates. This code doesn't work…
- User
There is Python code for copy pictures and remove duplicates. This code doesn't work well with image hash. Please rewrite it using 90% image equation criteria
import os from PIL import Image import hashlib import shutil
Define the input and output directories
input_dir = 'input/' output_dir = 'output/'
Create the output directory if it does not exist
if not os.path.exists(output_dir): os.makedirs(output_dir)
Helper function to calculate the hash of an image file
def get_image_hash(img_path): with Image.open(img_path) as img: # Some images may have an alpha layer, convert to RGB to avoid issues image_data = img.convert('RGB').tobytes() # Create a hash of the image data return hashlib.md5(image_data).hexdigest()
Keep track of image hashes to identify duplicates
image_hashes = set()
for file_name in os.listdir(input_dir): if file_name.lower().endswith('.png'): # Build the full file path file_path = os.path.join(input_dir, file_name)
code# Calculate the image hash img_hash = get_image_hash(file_path) # If the hash is new (non-duplicate), copy the image if img_hash not in image_hashes: image_hashes.add(img_hash) dest_path = os.path.join(output_dir, file_name) shutil.copy(file_path, dest_path) print(f"Copied: {file_name}") else: print(f"Duplicate found, skipping: {file_name}")print("Finished copying images.")
- Assistant