Milvus_Test.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. import towhee
  2. import cv2
  3. from towhee._types.image import Image
  4. import os
  5. import PIL.Image as Image
  6. import numpy as np
  7. from pymilvus import connections, FieldSchema, CollectionSchema, DataType, Collection, utility
  8. from MyModel2 import MyModel
  9. import torch
  10. from transformers import ViTFeatureExtractor, ViTModel
  11. from towhee.types.image_utils import to_image_color
  12. connections.connect(host='127.0.0.1', port='19530')
  13. dataset_path = ["D:\Code\ML\images\Mywork3\card_database_yolo/*/*/*/*"]
  14. img_id = 0
  15. yolo_num = 0
  16. vec_num = 0
  17. myModel = MyModel(r"D:\Code\ML\model\card_cls\res_card_out764_freeze5.pth", out_features=764)
  18. # myModel = MyModel(r"C:\Users\Administrator\.cache\torch\hub\checkpoints\resnet50-0676ba61.pth", out_features=1000)
  19. # myModel = MyEfficient('')
  20. # yolo_model = torch.hub.load(r"C:\Users\Administrator\.cache\torch\hub\ultralytics_yolov5_master", 'custom',
  21. # path="yolov5s.pt", source='local')
  22. # yolo_model = torch.hub.load("ultralytics/yolov5", "yolov5s")
  23. # 生成ID
  24. def get_id(param):
  25. global img_id
  26. img_id += 1
  27. return img_id
  28. # def eff_enbedding(img):
  29. # global vec_num
  30. # vec_num += 1
  31. # print('vec: ', vec_num)
  32. # return myModel.predict(img)
  33. # 生成向量
  34. def img2vec(img):
  35. global vec_num
  36. vec_num += 1
  37. print('vec: ', vec_num)
  38. return myModel.predict(img)
  39. # 生成信息
  40. path_num = 0
  41. def get_info(path):
  42. path = os.path.split(path)[0]
  43. path, num_and_player = os.path.split(path)
  44. num = num_and_player.split(' ')[0]
  45. player = ' '.join(os.path.split(num_and_player)[-1].split(' ')[1:])
  46. path, year = os.path.split(path)
  47. series = os.path.split(path)[1]
  48. rtn = "{} {} {} #{}".format(series, year, player, num)
  49. global path_num
  50. path_num += 1
  51. print(path_num, " loading " + rtn)
  52. return rtn
  53. def read_imgID(results):
  54. imgIDs = []
  55. for re in results:
  56. # 输出结果图片信息
  57. print('---------', re)
  58. imgIDs.append(re.id)
  59. return imgIDs
  60. # def yolo_detect(img):
  61. # results = yolo_model(img)
  62. #
  63. # pred = results.pred[0][:, :4].cpu().numpy()
  64. # boxes = pred.astype(np.int32)
  65. #
  66. # max_img = get_object(img, boxes)
  67. #
  68. # global yolo_num
  69. # yolo_num += 1
  70. # print("yolo_num: ", yolo_num)
  71. # return max_img
  72. #
  73. #
  74. # def get_object(img, boxes):
  75. # if isinstance(img, str):
  76. # img = Image.open(img)
  77. #
  78. # if len(boxes) == 0:
  79. # return img
  80. #
  81. # max_area = 0
  82. #
  83. # # 选出最大的框
  84. # x1, y1, x2, y2 = 0, 0, 0, 0
  85. # for box in boxes:
  86. # temp_x1, temp_y1, temp_x2, temp_y2 = box
  87. # area = (temp_x2 - temp_x1) * (temp_y2 - temp_y1)
  88. # if area > max_area:
  89. # max_area = area
  90. # x1, y1, x2, y2 = temp_x1, temp_y1, temp_x2, temp_y2
  91. #
  92. # max_img = img.crop((x1, y1, x2, y2))
  93. # return max_img
  94. # 创建向量数据库
  95. def create_milvus_collection(collection_name, dim):
  96. if utility.has_collection(collection_name):
  97. utility.drop_collection(collection_name)
  98. fields = [
  99. FieldSchema(name='img_id', dtype=DataType.INT64, is_primary=True),
  100. FieldSchema(name='path', dtype=DataType.VARCHAR, max_length=300),
  101. FieldSchema(name="info", dtype=DataType.VARCHAR, max_length=300),
  102. FieldSchema(name='embedding', dtype=DataType.FLOAT_VECTOR, descrition='image embedding vectors', dim=dim)
  103. ]
  104. schema = CollectionSchema(fields=fields, description='reverse image search')
  105. collection = Collection(name=collection_name, schema=schema)
  106. index_params = {
  107. 'metric_type': 'L2',
  108. 'index_type': "IVF_FLAT",
  109. 'params': {"nlist": dim}
  110. }
  111. collection.create_index(field_name="embedding", index_params=index_params)
  112. return collection
  113. # 判断是否加载已有数据库,或新创建数据库
  114. def is_creat_collection(have_coll, collection_name):
  115. if have_coll:
  116. # 连接现有的数据库
  117. collection = Collection(name=collection_name)
  118. else:
  119. # 新建立数据库
  120. collection = create_milvus_collection(collection_name, 2048)
  121. dc = (
  122. towhee.glob['path'](*dataset_path)
  123. .runas_op['path', 'img_id'](func=get_id)
  124. .runas_op['path', 'info'](func=get_info)
  125. # .image_decode['path', 'img']()
  126. # .runas_op['path', "object"](yolo_detect)
  127. .runas_op['path', 'vec'](func=img2vec)
  128. .tensor_normalize['vec', 'vec']()
  129. # .image_embedding.timm['img', 'vec'](model_name='resnet50')
  130. .ann_insert.milvus[('img_id', 'path', 'info', 'vec'), 'mr'](collection=collection)
  131. )
  132. print('Total number of inserted data is {}.'.format(collection.num_entities))
  133. return collection
  134. # 通过ID查询
  135. def query_by_imgID(collection, img_id, limit=1):
  136. expr = 'img_id == ' + str(img_id)
  137. res = collection.query(expr, output_fields=["path", "info"], offset=0, limit=limit, timeout=2)
  138. return res
  139. # 分别返回 编号,年份,系列
  140. def from_path_get_info(path):
  141. card_info = []
  142. for i in range(3):
  143. path = os.path.split(path)[0]
  144. card_info.append(os.path.split(path)[-1])
  145. card_info[0] = card_info[0].split('#')[-1]
  146. return card_info
  147. def from_query_path_get_info(path):
  148. card_info = []
  149. for i in range(3):
  150. path = os.path.split(path)[0]
  151. card_info.append(os.path.split(path)[-1])
  152. card_info[0] = card_info[0].split(' ')[0]
  153. return card_info
  154. if __name__ == '__main__':
  155. print('start')
  156. # 是否存在数据库
  157. have_coll = False
  158. # 默认模型
  159. # collection = is_creat_collection(have_coll=have_coll, collection_name="reverse_image_search")
  160. # 自定义模型
  161. collection = is_creat_collection(have_coll=have_coll, collection_name="reverse_image_search_myModel")
  162. # 测试的图片路径
  163. img_path = ["D:/Code/ML/images/test02/test(mosaic,pz)/*/*/*/*"]
  164. data = (towhee.glob['path'](*img_path)
  165. # image_decode['path', 'img']().
  166. # .runas_op['path', "object"](yolo_detect)
  167. .runas_op['path', 'vec'](func=img2vec)
  168. .tensor_normalize['vec', 'vec']()
  169. # image_embedding.timm['img', 'vec'](model_name='resnet50').
  170. .ann_search.milvus['vec', 'result'](collection=collection, limit=3)
  171. .runas_op['result', 'result_imgID'](func=read_imgID)
  172. .select['path', 'result_imgID', 'vec']()
  173. )
  174. print(data)
  175. collection.load()
  176. # res = query_by_imgID(collection, data[0].result_imgID[0])
  177. #
  178. # print(res[0])
  179. top3_num = 0
  180. top1_num = 0
  181. test_img_num = len(list(data))
  182. # 查询所有测试图片
  183. for i in range(test_img_num):
  184. top3_flag = False
  185. # 获取图片真正的编号, 年份, 系列
  186. source_code, source_year, source_series = from_path_get_info(data[i].path)
  187. # 每个测试图片返回三个最相似的图片ID,一一测试
  188. for j in range(3):
  189. res = query_by_imgID(collection, data[i].result_imgID[j])
  190. # 获取预测的图片的编号, 年份, 系列
  191. result_code, result_year, result_series = from_query_path_get_info(res[0]['path'])
  192. # 判断top1是否正确
  193. if j == 0 and source_code == result_code and source_year == result_year and source_series == result_series:
  194. top1_num += 1
  195. print(top1_num)
  196. elif j == 0:
  197. print('top_1 错误')
  198. # top3中有一个正确的标记为正确
  199. if source_code == result_code and source_year == result_year and source_series == result_series:
  200. top3_flag = True
  201. print("series: {}, year: {},code: {} === result - series: {}, year: {}, code: {}".format(
  202. source_series, source_year, source_code, result_series, result_year, result_code,
  203. ))
  204. if top3_flag:
  205. top3_num += 1
  206. print("====================================")
  207. print("测试图片共: ", test_img_num)
  208. top1_accuracy = (top1_num / test_img_num) * 100
  209. top3_accuracy = (top3_num / test_img_num) * 100
  210. print("top3 准确率:{} % \n top1 准确率: {} %".
  211. format(top3_accuracy, top1_accuracy))