Finding duplicate images using perceptual hashes requires a function that can compare the hash of a newly added image with the hashes of existing images stored in the database to determine if there are any duplicates or near duplicates.
In the scenario you've described, you'll want to define what constitutes a "duplicate" image with respect to the perceptual hash. A simple and common approach is to consider images with identical hashes as duplicates. However, for perceptual hashes, you might also want to find near-duplicates, i.e., images whose hashes are similar within a certain threshold.
Let's start with the simpler case of finding exact duplicates:
async def find_exact_duplicates(db: Session):
# Query for a list of (ahash, count) tuples where count is the number of occurrences of each ahash
duplicates_query = db.query(
models.Image.ahash, func.count(models.Image.ahash)
).group_by(
models.Image.ahash
).having(
func.count(models.Image.ahash) > 1
)
# Execute the query
duplicates = duplicates_query.all()
# For each duplicate ahash found, query to get the associated images
duplicate_images = []
for ahash, count in duplicates:
images = db.query(models.Image).filter(models.Image.ahash == ahash).all()
duplicate_images.append(images)
return duplicate_images
Now, let's consider a scenario where you want to find near-duplicate images. To do this, you'd need to define a distance metric to compare hashes. The imagehash library provides a - operator to compute the Hamming distance between two hashes. You can define a threshold, such that if the distance is below that threshold, you consider the images near-duplicates.
Here's how you might approach finding near-duplicate images based on a threshold:
from imagehash import hex_to_hash
# Define a threshold for what you consider as "similar"
# Lower values are stricter, only very similar hashes will be near-duplicates
THRESHOLD = 5 # for example, maximum 5 bits different
async def find_near_duplicates(db: Session):
all_images = db.query(models.Image.ahash).all()
near_duplicate_images = []
for i in range(len(all_images)):
for j in range(i + 1, len(all_images)):
hash1 = hex_to_hash(all_images[i].ahash)
hash2 = hex_to_hash(all_images[j].ahash)
if hash1 - hash2 < THRESHOLD:
near_duplicate_pair = (all_images[i], all_images[j])
near_duplicate_images.append(near_duplicate_pair)
# Return near-duplicate image pairs
return near_duplicate_images
This function compares each image with every other image in the dataset to find near-duplicates, which is an O(n^2) operation and can be resource-intensive for large datasets. To improve efficiency, you may need to index your ahash values or implement a more efficient searching algorithm. Keep in mind that creating this function may not perform well with a large number of images and you should consider optimizing it if performance becomes an issue.