与 Django 的自定义比较(汉明距离)

Custom comparisons with Django (hamming distance)

我有以下代码可以让我找到相等的图像(相同的),但是说我只想找到汉明距离在一定数量以下的图像,可以将其合并到 django 查询集中,还是原始的sql 不知何故?我不想获取所有内容并与 python 进行比较,因为那非常非常慢而且我有很多图像。

当前代码:

def duplicates(request):
    duplicate_images = []
    images = Image.objects.all()
    for image in images:
        duplicates = Image.objects.filter(hash=image.hash).exclude(pk=image.pk)
        for duplicate in duplicates:
            duplicate_images.append([image, duplicate])
        if len(duplicate_images) > 1000:
            break

以下是如何使用 postgres 扩展实现这一点:

https://github.com/eulerto/pg_similarity

安装:

$ git clone https://github.com/eulerto/pg_similarity.git
$ cd pg_similarity
$ USE_PGXS=1 make
$ USE_PGXS=1 make install
$ psql mydb
psql (9.3.5)
Type "help" for help.

mydb=# CREATE EXTENSION pg_similarity;
CREATE EXTENSION

不,您可以使用自定义 "WHERE" 子句创建 Django 查询集,以便使用 hamming_text 函数

image = Image.objects.get(pk=1252) # the image you want to compare to
similar = Image.objects.extra(where=['hamming_text(hash,%s)>=0.88'],
                              params=[image.hash])

瞧,它起作用了!

注意:这里的汉明距离是自动归一化的,所以0表示完全不同,1表示相同。