中。有一个需求:计算图片的相似度,需要解决两个问题:生成ahash存储和计算ahash之间的距离生成ahash《生成ahash》选择以下pythonimagehash库之一。(github:https://github.com/JohannesBu...)从ioimportBytesIOimportnumpyimportimagehashfromPILimportImagedefcreate_vector(file:BytesIO)->bytes:image=Image.open(file)hash=imagehash.average_hash(image)_vector=[]forhinhash.hash:_vector.extend(h)vector=bytes(numpy.packbits([int(v)forvin_vector],axis=-1).tolist())返回vectorcreate_vector函数输出类型为bytes,即二进制序列imagehash.average_hash(image)输出的hash对象。hash对象有一个hash属性,这个属性的类型是list[list[bool]],打印如下,其实是一个8x8=64位的序列[[FalseFalseFalseFalseFalseFalseFalseFalse][真假假假真假假假][假假真真真真真真假假][假假假真真假真真][假假真真真假假假][假假真真真真真假假假]][假真真真真真真FalseTrueTrue][FalseFalseFalseTrueTrueFalseTrueTrue]]向量数据库《存储和计算ahash之间的距离》选择milvus创建集合定义集合:importsettingsfrompymilvusimport(connections,Collection,FieldSchema,CollectionSchema,DataType,)从记录器导入loggerconnections.connect(host=settings.MILVUS_CONFIG.host,port=settings.MILVUS_CONFIG.port,)schema=CollectionSchema([FieldSchema("id",DataType.INT64,is_primary=True,auto_id=True),FieldSchema("meta_id",DataType.INT64),FieldSchema("company_id",DataType.INT64),FieldSchema("image_vector",dtype=DataType.BINARY_VECTOR,dim=64)])#如果集合不存在,会自动创建;存在,不会重复创建collection=Collection(settings.MILVUS_CONFIG.collection.name,schema)使用的vector类型是dtype=DataType.BINARY_VECTOR,为什么不选择float因为我不知道如何将ahash转换为float关于vectorindex问题,因为我选择的“向量类型”是BINARY_VECTOR因此,索引类型只有BIN_FLAT和BIN_IVF_FLAT是可选的。详见https://milvus.io/docs/v2.2.x...InsertahashintomilvusclassTestVector(unittest.TestCase):deftest_insert_vector(self):"""Insertahashintomilvuspython-munittesttesting.test_milvus.TestVector.test_insert_vector"""oss_file_path='image_hash/testing/WechatIMG193.jpeg'文件=BytesIO(bucket.get_object(oss_file_path).read())vector=create_vector(file)m_pk=insert_vector(vector,meta_id=2、company_id=1)logger.debug(f'milvuspk:{m_pk}')queryahashfrommilvusdeftest_search(self):"""批量调用后端接口入库python-munittesttesting.test_milvus.TestVector.test_search"""oss_file_path='image_hash/testing/WechatIMG193.jpeg'file=BytesIO(open(BASE_DIR/'testing'/'resource'/'WechatIMG193.jpeg','rb').read())vector=create_vector(文件)logger.debug(向量)行:列表[dict[str,Any]]=collection.search(data=[vector],param={"metric_type":'HAMMING',"params":{"nprobe":32}},anns_field='image_vector',output_fields=['id','meta_id','company_id'],limit=10,)logger.debug(rows)logger.debug(type(rows))注意metric_type,因为我选择的“向量类型”是BINARY_VECTOR,因此,应选择metric_type以支持BINARY_VECTOR
