Milvus_Test.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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 MyModel import MyModel
  9. from MyEfficientNet import MyEfficient
  10. import torch
  11. from transformers import ViTFeatureExtractor, ViTModel
  12. from towhee.types.image_utils import to_image_color
  13. connections.connect(host='127.0.0.1', port='19530')
  14. dataset_path = ["D:\Code\ML\images\Mywork3\card_database_yolo/*/*/*/*"]
  15. img_id = 0
  16. vec_num = 0
  17. myModel = MyModel(r"D:\Code\ML\model\card_cls\res_card_out764_freeze4.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. pred = results.pred[0][:, :4].cpu().numpy()
  63. boxes = pred.astype(np.int32)
  64. max_img = get_object(img, boxes)
  65. return max_img
  66. def get_object(img, boxes):
  67. if isinstance(img, str):
  68. img = Image.open(img)
  69. if len(boxes) == 0:
  70. return img
  71. max_area = 0
  72. # 选出最大的框
  73. x1, y1, x2, y2 = 0, 0, 0, 0
  74. for box in boxes:
  75. temp_x1, temp_y1, temp_x2, temp_y2 = box
  76. area = (temp_x2 - temp_x1) * (temp_y2 - temp_y1)
  77. if area > max_area:
  78. max_area = area
  79. x1, y1, x2, y2 = temp_x1, temp_y1, temp_x2, temp_y2
  80. max_img = img.crop((x1, y1, x2, y2))
  81. return max_img
  82. # 创建向量数据库
  83. def create_milvus_collection(collection_name, dim):
  84. if utility.has_collection(collection_name):
  85. utility.drop_collection(collection_name)
  86. fields = [
  87. FieldSchema(name='img_id', dtype=DataType.INT64, is_primary=True),
  88. FieldSchema(name='path', dtype=DataType.VARCHAR, max_length=300),
  89. FieldSchema(name="info", dtype=DataType.VARCHAR, max_length=300),
  90. FieldSchema(name='embedding', dtype=DataType.FLOAT_VECTOR, descrition='image embedding vectors', dim=dim)
  91. ]
  92. schema = CollectionSchema(fields=fields, description='reverse image search')
  93. collection = Collection(name=collection_name, schema=schema)
  94. index_params = {
  95. 'metric_type': 'L2',
  96. 'index_type': "IVF_FLAT",
  97. 'params': {"nlist": dim}
  98. }
  99. collection.create_index(field_name="embedding", index_params=index_params)
  100. return collection
  101. # 判断是否加载已有数据库,或新创建数据库
  102. def is_creat_collection(have_coll, collection_name):
  103. if have_coll:
  104. # 连接现有的数据库
  105. collection = Collection(name=collection_name)
  106. else:
  107. # 新建立数据库
  108. collection = create_milvus_collection(collection_name, 2048)
  109. dc = (
  110. towhee.glob['path'](*dataset_path)
  111. .runas_op['path', 'img_id'](func=get_id)
  112. .runas_op['path', 'info'](func=get_info)
  113. # .image_decode['path', 'img']()
  114. # .runas_op['path', "object"](yolo_detect)
  115. .runas_op['path', 'vec'](func=img2vec)
  116. .tensor_normalize['vec', 'vec']()
  117. # .image_embedding.timm['img', 'vec'](model_name='resnet50')
  118. .ann_insert.milvus[('img_id', 'path', 'info', 'vec'), 'mr'](collection=collection)
  119. )
  120. print('Total number of inserted data is {}.'.format(collection.num_entities))
  121. return collection
  122. # 通过ID查询
  123. def query_by_imgID(collection, img_id, limit=1):
  124. expr = 'img_id == ' + str(img_id)
  125. res = collection.query(expr, output_fields=["path", "info"], offset=0, limit=limit, timeout=2)
  126. return res
  127. def from_path_get_series(path):
  128. for i in range(3):
  129. path = os.path.split(path)[0]
  130. series = os.path.split(path)[-1]
  131. return series
  132. if __name__ == '__main__':
  133. print('start')
  134. # 是否存在数据库
  135. have_coll = False
  136. # 默认模型
  137. # collection = is_creat_collection(have_coll=have_coll, collection_name="reverse_image_search")
  138. # 自定义模型
  139. collection = is_creat_collection(have_coll=have_coll, collection_name="reverse_image_search_myModel")
  140. # 测试的图片路径
  141. img_path = ["D:/Code/ML/images/test02/test2/*/*/*/*"]
  142. data = (towhee.glob['path'](*img_path)
  143. # image_decode['path', 'img']().
  144. .runas_op['path', "object"](yolo_detect)
  145. .runas_op['object', 'vec'](func=img2vec)
  146. .tensor_normalize['vec', 'vec']()
  147. # image_embedding.timm['img', 'vec'](model_name='resnet50').
  148. .ann_search.milvus['vec', 'result'](collection=collection, limit=3)
  149. .runas_op['result', 'result_imgID'](func=read_imgID)
  150. .select['path', 'result_imgID', 'vec']()
  151. )
  152. print(data)
  153. collection.load()
  154. # res = query_by_imgID(collection, data[0].result_imgID[0])
  155. #
  156. # print(res[0])
  157. top3_num = 0
  158. top1_num = 0
  159. test_img_num = len(list(data))
  160. # 查询所有测试图片
  161. for i in range(test_img_num):
  162. top3_flag = False
  163. # 获取图片真正的系列
  164. source_card_series = from_path_get_series(data[i].path)
  165. # 获取图片真正的编号
  166. source_num = os.path.split(os.path.split(data[i].path)[0])[-1].split('#')[-1]
  167. # 每个测试图片返回三个最相似的图片ID,一一测试
  168. for j in range(3):
  169. res = query_by_imgID(collection, data[i].result_imgID[j])
  170. # 获取预测的图片的系列
  171. result_card_series = from_path_get_series(res[0]['path'])
  172. # 获取预测的图片的编号
  173. result_num = os.path.split(os.path.split(res[0]['path'])[0])[-1].split(' ')[0].split('#')[-1]
  174. # 判断top1是否正确
  175. if j == 0 and source_num == result_num and source_card_series == result_card_series:
  176. top1_num += 1
  177. # top3中有一个正确的标记为正确
  178. if source_num == result_num and source_card_series == result_card_series:
  179. top3_flag = True
  180. # 日志
  181. if j == 0 and source_num == result_num and source_card_series == result_card_series:
  182. print(top1_num)
  183. elif j == 0:
  184. print('top_1 错误')
  185. print("series: {}, num: {} === result - series: {}, num: {}".format(
  186. source_card_series, source_num, result_card_series, result_num
  187. ))
  188. if top3_flag:
  189. top3_num += 1
  190. print("====================================")
  191. print("测试图片共: ", test_img_num)
  192. top1_accuracy = (top1_num / test_img_num) * 100
  193. top3_accuracy = (top3_num / test_img_num) * 100
  194. print("top3 准确率:{} % \n top1 准确率: {} %".
  195. format(top3_accuracy, top1_accuracy))
  196. '''
  197. 测试图片共: 168
  198. 自定义resnet50_freeze_out421 + yolo + normalize
  199. top3 准确率:96.42857142857143 %
  200. top1 准确率: 95.23809523809523 %
  201. 测试图片: 773, 数据库图片: 5848
  202. 自定义resnet50_freeze_out421 + yolo + normalize
  203. 测试图片共: 773
  204. top3 准确率:96.63648124191462 %
  205. top1 准确率: 95.60155239327295 %
  206. 测试图片: 773, 数据库图片: 5848
  207. 自定义resnet50_out764_freeze + yolo + normalize
  208. top3 准确率:96.76584734799482 %
  209. top1 准确率: 96.50711513583441 %
  210. '''