Comparing images or movies
This revision is from 2024/02/09 16:44. You can Restore it.
With Python, comparing image using Structural Similarity Index (SSIM) or using a perceptual hashing algorithm like pHash.
pip install scikit-image opencv-python pip install python-phash
Comparing Images using SSIM (Structural Similarity Index):
import cv2 import numpy as np from skimage import measure # Load images img1 = cv2.imread('image1.jpg', 0) # grayscale img2 = cv2.imread('image2.jpg', 0) # grayscale # Ensure both images have the same dimensions assert img1.shape == img2.shape, "Images must have the same dimensions" # Compute SSIM ssim = measure.compare_ssim(img1, img2) print("SSIM:", ssim)
Comparing Images using pHash (Perceptual Hashing):
import phash # Load images img1 = cv2.imread('image1.jpg') img2 = cv2.imread('image2.jpg') # Compute pHash hash1 = phash.dct_image_hash(img1) hash2 = phash.dct_image_hash(img2) # Compare hashes distance = hamming_distance(hash1, hash2) print("Hamming Distance:", distance)
Structural Similarity Index (SSIM) and perceptual hashing algorithms like pHash can be useful for comparing images that are not identical but visually similar. These techniques are based on different principles, but both aim to quantify the similarity between images from a human perception perspective.
- Structural Similarity Index (SSIM): SSIM is a metric that compares two images by assessing their structural information. It takes into account luminance, contrast, and structure to calculate a similarity score between 0 and 1, with 1 indicating perfect similarity. To use SSIM for image comparison, follow these steps:
- Preprocess images: Resize and normalize the images to a common size.
- Calculate local mean, variance, and covariance for each image.
- Compute the SSIM score for each local window (block) in the images.
- Average the SSIM scores across all windows to get the global SSIM score.
- A higher global SSIM score indicates greater similarity.