def get_image_orientation(image):
"""Retrieve the orientation tag from an image's EXIF data."""
try:
exif = image._getexif()
if exif is not None:
for tag, value in exif.items():
decoded = ExifTags.TAGS.get(tag, tag)
if decoded == "Orientation":
return value
return None
except Exception as e:
logging.error(f"Error retrieving EXIF data: {str(e)}")
return None
def calculate_image_hash(image_path):
"""Calculate the perceptual hash of an image after correcting orientation."""
try:
image = Image.open(image_path).convert("RGB")
def compare_hashes(hash1, hash2, max_distance=5):
"""Compare two hashes and return True if the distance is within max_distance."""
if hash1 is None or hash2 is None:
return False
distance = hash1 - hash2
return distance <= max_distance
def secondary_ssim_check(image1_path, image2_path, threshold=0.85):
"""Perform a secondary check using SSIM to confirm image match."""
try:
img1 = cv2.imread(image1_path, cv2.IMREAD_GRAYSCALE)
img2 = cv2.imread(image2_path, cv2.IMREAD_GRAYSCALE)
code
if img1 is None or img2 is None:
logging.error(f"Error reading images for SSIM: {image1_path}, {image2_path}")
return False
# Ensure same size
if img1.shape != img2.shape:
img2 = cv2.resize(img2, (img1.shape[1], img1.shape[0]))
# Calculate SSIM
ssim_score = ssim(img1, img2, data_range=img1.max() - img1.min())
return ssim_score >= threshold
except Exception as e:
logging.error(f"SSIM error between {image1_path} and {image2_path}: {str(e)}")
return False
def process_thumbnail(thumbnail_path, original_hash_dict, output_folder, max_distance, copied_files):
"""Process a thumbnail image to find and copy the matching original image."""
thumbnail_file = os.path.basename(thumbnail_path)
thumbnail_hashes = calculate_thumbnail_hashes(thumbnail_path)
code
if not thumbnail_hashes:
logging.warning(f"Skipping thumbnail {thumbnail_file} due to hash calculation error.")
print(f"Skipping thumbnail {thumbnail_file} due to hash calculation error.")
return False, None, None
# Find matching original images
matches = []
for original_path, original_hash in original_hash_dict.items():
for thumbnail_hash in thumbnail_hashes:
if compare_hashes(thumbnail_hash, original_hash, max_distance):
matches.append(original_path)
break # Stop at first match for this original image
# If matches found, proceed with secondary SSIM check
for best_match in matches:
original_file = os.path.basename(best_match)
if original_file not in copied_files:
ssim_passed = secondary_ssim_check(best_match, thumbnail_path)
if ssim_passed:
try:
output_path = os.path.join(output_folder, original_file)
shutil.copy2(best_match, output_path)
copied_files.add(original_file)
print(f"Copied matching image: {original_file} to {output_folder}")
return True, original_file, 0 # Assuming perfect match after SSIM
except Exception as e:
logging.error(f"Error copying {original_file} to output: {str(e)}")
return False, None, None
else:
logging.info(f"SSIM check failed for: {original_file} with thumbnail: {thumbnail_file}")
logging.info(f"No suitable match found for thumbnail: {thumbnail_file}")
print(f"No suitable match found for thumbnail: {thumbnail_file}")
return False, None, None
def find_matching_images(thumbnails_folder, originals_folder, output_folder, max_distance=5):
"""Main function to find and copy matching images from originals to output based on thumbnails."""
if not os.path.exists(output_folder):
os.makedirs(output_folder)
logging.info(f"Created output folder at {output_folder}")
print(f"Created output folder at {output_folder}")
code
original_files = [f for f in os.listdir(originals_folder) if f.lower().endswith(('.jpg', '.jpeg', '.png'))]
original_image_paths = [os.path.join(originals_folder, f) for f in original_files]
print(f"Found {len(original_files)} original images.")
logging.info(f"Found {len(original_files)} original images.")
# Compute hashes for original images
original_hash_dict = {}
with ProcessPoolExecutor() as executor:
futures = {executor.submit(calculate_image_hash, path): path for path in original_image_paths}
for future in as_completed(futures):
path = futures[future]
hash_value = future.result()
original_hash_dict[path] = hash_value
if not hash_value:
logging.warning(f"No hash computed for original image: {path}")
thumbnail_files = [f for f in os.listdir(thumbnails_folder) if f.lower().endswith(('.jpg', '.jpeg', '.png'))]
thumbnail_image_paths = [os.path.join(thumbnails_folder, f) for f in thumbnail_files]
print(f"Found {len(thumbnail_files)} thumbnail images.")
logging.info(f"Found {len(thumbnail_files)} thumbnail images.")
copied_files = set()
total_matches = 0
# Process thumbnails (small number, so sequential processing is acceptable)
for thumbnail_path in thumbnail_image_paths:
matched, original_file, _ = process_thumbnail(thumbnail_path, original_hash_dict, output_folder, max_distance, copied_files)
if matched:
total_matches += 1
logging.info(f"Matched thumbnail with original: {original_file}")
print(f"Image matching completed. Total matches found: {total_matches}")
logging.info(f"Image matching completed. Total matches found: {total_matches}")
find_matching_images(
thumbnails_folder,
originals_folder,
output_folder,
max_distance=50 # Adjust the threshold as needed
)
Yes, you can pre-process the images in the thumbnails folder to correct their orientation before starting the matching process. This can be beneficial for a few reasons:
Simplification of Processing: By ensuring that all thumbnail images are correctly oriented beforehand, you reduce the complexity within your matching functions. This means you won't need to handle multiple rotations during hash calculations, potentially speeding up the process.
Consistency: Having all images in a consistent orientation can improve the reliability of your matching algorithm, especially if some images lack EXIF orientation data or have incorrect metadata.
User Experience: If you plan to display these thumbnails elsewhere, having them correctly oriented improves the visual consistency and user experience.
Here's how you can modify your code to check and correct the orientation of images in the thumbnails folder before starting the matching process:
Step 1: Create a Function to Correct Image Orientation
Add a function that opens an image, checks its EXIF orientation data, and rotates it if necessary:
python
def correct_image_orientation(image_path):
"""Corrects the orientation of an image based on its EXIF data."""
try:
image = Image.open(image_path)
exif = image._getexif()
if exif is not None:
orientation_key = next(
(key for key, value in ExifTags.TAGS.items() if value == "Orientation"), None
)
if orientation_key and orientation_key in exif:
orientation = exif[orientation_key]
logging.debug(f"Image {image_path} has EXIF orientation: {orientation}")
# Correct the image orientation based on the EXIF data
if orientation == 3:
image = image.rotate(180, expand=True)
elif orientation == 6:
image = image.rotate(270, expand=True)
elif orientation == 8:
image = image.rotate(90, expand=True)
# Remove the EXIF Orientation tag to prevent issues
exif[orientation_key] = 1
image.info["exif"] = exif
# Save the corrected image back to the same path
image.save(image_path)
logging.debug(f"Corrected orientation for image: {image_path}")
except Exception as e:
logging.error(f"Error correcting orientation for {image_path}: {str(e)}")
Step 2: Apply the Function to All Thumbnails Before Matching
Before you start the matching process, iterate over all images in your thumbnails folder and correct their orientation:
python
def preprocess_thumbnails(thumbnails_folder):
"""Pre-process thumbnails by correcting their orientation."""
thumbnail_files = [
f for f in os.listdir(thumbnails_folder)
if f.lower().endswith(('.jpg', '.jpeg', '.png'))
]
for thumbnail_file in thumbnail_files:
thumbnail_path = os.path.join(thumbnails_folder, thumbnail_file)
correct_image_orientation(thumbnail_path)
logging.info("Thumbnail preprocessing completed.")
print("Thumbnail preprocessing completed.")
Step 3: Integrate the Preprocessing Step into Your Main Function
Modify your find_matching_images function to include the preprocessing step:
python
def find_matching_images(thumbnails_folder, originals_folder, output_folder, max_distance=5):
"""Main function to find and copy matching images from originals to output based on thumbnails."""
if not os.path.exists(output_folder):
os.makedirs(output_folder)
logging.info(f"Created output folder at {output_folder}")
print(f"Created output folder at {output_folder}")
# **NEW**: Preprocess thumbnails
preprocess_thumbnails(thumbnails_folder)
# Rest of your existing code...
Notes:
EXIF Data: Be aware that saving the image after correcting it may not preserve all original EXIF metadata. If preserving EXIF data is important, you may need to copy the metadata explicitly.
Rotation: The rotate function with expand=True ensures that the entire image is kept after rotation, adjusting the image size as necessary.
Orientation Tag Reset: After rotating the image, it's good practice to reset the orientation in the EXIF data to 1 (normal orientation) to prevent future misinterpretations.
Error Handling: Ensure that you have proper error handling in place in case any image cannot be processed.
Updated Code Snippet Incorporating Changes
Here's how your updated code may look with the preprocessing step added:
python
# ... (Previous imports and configurations)
def correct_image_orientation(image_path):
"""Corrects the orientation of an image based on its EXIF data."""
try:
image = Image.open(image_path)
exif = image._getexif()
if exif is not None:
orientation_key = next(
(key for key, value in ExifTags.TAGS.items() if value == "Orientation"), None
)
if orientation_key and orientation_key in exif:
orientation = exif[orientation_key]
logging.debug(f"Image {image_path} has EXIF orientation: {orientation}")
# Correct the image orientation based on the EXIF data
if orientation == 3:
image = image.rotate(180, expand=True)
elif orientation == 6:
image = image.rotate(270, expand=True)
elif orientation == 8:
image = image.rotate(90, expand=True)
# Remove the EXIF Orientation tag to prevent issues
exif[orientation_key] = 1
# Save EXIF data if needed
image.save(image_path)
logging.debug(f"Corrected orientation for image: {image_path}")
except Exception as e:
logging.error(f"Error correcting orientation for {image_path}: {str(e)}")
def preprocess_thumbnails(thumbnails_folder):
"""Pre-process thumbnails by correcting their orientation."""
thumbnail_files = [
f for f in os.listdir(thumbnails_folder)
if f.lower().endswith(('.jpg', '.jpeg', '.png'))
]
for thumbnail_file in thumbnail_files:
thumbnail_path = os.path.join(thumbnails_folder, thumbnail_file)
correct_image_orientation(thumbnail_path)
logging.info("Thumbnail preprocessing completed.")
print("Thumbnail preprocessing completed.")
def find_matching_images(thumbnails_folder, originals_folder, output_folder, max_distance=5):
"""Main function to find and copy matching images from originals to output based on thumbnails."""
if not os.path.exists(output_folder):
os.makedirs(output_folder)
logging.info(f"Created output folder at {output_folder}")
print(f"Created output folder at {output_folder}")
# Preprocess thumbnails
preprocess_thumbnails(thumbnails_folder)
# Rest of your existing code...
Conclusion
By adding this preprocessing step, you ensure that all thumbnail images are correctly oriented before the matching process begins. This can potentially improve the accuracy of your matching algorithm and simplify your code, as you may no longer need to handle multiple rotation angles within your calculate_thumbnail_hashes function.
Note: Since you're now rotating the thumbnails to the correct orientation before processing, you can modify calculate_thumbnail_hashes to remove redundant rotations if desired. However, keeping them might still be beneficial in case some images were not correctly re-oriented due to missing or incorrect EXIF data.
Let me know if you need further assistance or clarification on any of these steps!