the following python code is working fine to an extent but it is too slow, pls check how…
- User
the following python code is working fine to an extent but it is too slow, pls check how to hasten the comparison process:
import os import shutil from PIL import Image, ExifTags import imagehash from concurrent.futures import ThreadPoolExecutor, as_completed import logging import cv2 from skimage.metrics import structural_similarity as ssim import torch import torchvision.transforms as transforms from torch.cuda import is_available
Configure logging
logging.basicConfig( filename='image_matching_debug.log', filemode='w', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s' )
Set up CUDA device
device = torch.device('cuda' if is_available() else 'cpu')
def initialize_cuda(): if is_available(): torch.cuda.empty_cache() # Warm up CUDA dummy_tensor = torch.zeros(1).cuda() del dummy_tensor
def get_image_orientation(image): 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_hashes(image_path): try: image = Image.open(image_path).convert("RGB") # Convert PIL Image to tensor and move to GPU transform = transforms.ToTensor() image_tensor = transform(image).unsqueeze(0).to(device)
# Handle orientations orientation = get_image_orientation(image) if orientation == 6: image_tensor = torch.rot90(image_tensor, k=3, dims=[2, 3]) elif orientation == 3: image_tensor = torch.rot90(image_tensor, k=2, dims=[2, 3]) elif orientation == 8: image_tensor = torch.rot90(image_tensor, k=1, dims=[2, 3]) hashes = [] for angle in [0, 90, 180, 270]: if angle != 0: rotated_tensor = torch.rot90(image_tensor, k=angle//90, dims=[2, 3]) else: rotated_tensor = image_tensor # Convert back to PIL for hashing rotated_image = transforms.ToPILImage()(rotated_tensor.squeeze(0).cpu()) hash_value = imagehash.phash(rotated_image) hashes.append(hash_value) return hashes except Exception as e: logging.error(f"Error processing {image_path}: {str(e)}") return []def compare_images(thumbnail_hashes, original_hashes, max_distance=5): closest_distance = float('inf') for t_hash in thumbnail_hashes: for o_hash in original_hashes: distance = t_hash - o_hash if distance < closest_distance: closest_distance = distance if distance == 0: return True, 0 return closest_distance <= max_distance, closest_distance
def secondary_ssim_check(image1_path, image2_path, threshold=0.85): try: img1 = cv2.imread(image1_path, cv2.IMREAD_GRAYSCALE) img2 = cv2.imread(image2_path, cv2.IMREAD_GRAYSCALE)
if img1 is None or img2 is None: logging.error(f"Error reading images for SSIM: {image1_path}, {image2_path}") return False # Convert to tensors and move to GPU img1_tensor = torch.from_numpy(img1).float().unsqueeze(0).unsqueeze(0).to(device) img2_tensor = torch.from_numpy(img2).float().unsqueeze(0).unsqueeze(0).to(device) # Ensure same size if img1_tensor.shape != img2_tensor.shape: img2_tensor = torch.nn.functional.interpolate( img2_tensor, size=(img1_tensor.shape[2], img1_tensor.shape[3]) ) # Calculate SSIM on GPU ssim_score = ssim( img1_tensor.cpu().numpy().squeeze(), img2_tensor.cpu().numpy().squeeze(), data_range=255 ) return ssim_score >= threshold except Exception as e: logging.error(f"SSIM error between {image1_path} and {image2_path}: {str(e)}") return False - Assistant