chanhua commited on
Commit
6c9df61
1 Parent(s): 3264246

Upload 2 files

Browse files
Files changed (1) hide show
  1. image_feature.py +27 -25
image_feature.py CHANGED
@@ -49,8 +49,8 @@ DEVICE = torch.device('cpu')
49
 
50
 
51
  # 第二种方式推理图片相似度
52
- processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224")
53
- model = AutoModel.from_pretrained("google/vit-base-patch16-224").to(DEVICE)
54
 
55
 
56
  # tensor([0.6061], device='cuda:0', grad_fn=<SumBackward1>)
@@ -83,35 +83,37 @@ def infer3(url1, url2):
83
 
84
  except Exception as e:
85
  print(f"发生了一个错误: {e}")
 
 
86
  finally:
87
  # 无论是否发生异常,都会执行此代码块
88
  print("这是finally块")
89
 
90
 
91
  # 推理
92
- def infer2(url):
93
- # image_real = Image.open(requests.get(img_urls[0], stream=True).raw).convert("RGB")
94
- image = Image.open(requests.get(url, stream=True).raw).convert("RGB")
95
- inputs = processor(image, return_tensors="pt").to(DEVICE)
96
- outputs = model(**inputs)
97
- return outputs.pooler_output
98
 
99
 
100
  # 推理
101
- def infer1(image1, image2):
102
- try:
103
- embed_real = infer2(image1)
104
- embed_gen = infer2(image2)
105
- similarity_score = cosine_similarity(embed_real, embed_gen, dim=1)
106
- print(similarity_score)
107
- # 如果你想在CPU上操作这个值,你需要先将tensor移动到CPU
108
- t_cpu = similarity_score.cpu()
109
-
110
- # 然后提取这个值
111
- return t_cpu.item()
112
-
113
- except Exception as e:
114
- print(f"发生了一个错误: {e}")
115
- finally:
116
- # 无论是否发生异常,都会执行此代码块
117
- print("这是finally块")
 
49
 
50
 
51
  # 第二种方式推理图片相似度
52
+ # processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224")
53
+ # model = AutoModel.from_pretrained("google/vit-base-patch16-224").to(DEVICE)
54
 
55
 
56
  # tensor([0.6061], device='cuda:0', grad_fn=<SumBackward1>)
 
83
 
84
  except Exception as e:
85
  print(f"发生了一个错误: {e}")
86
+
87
+ return 0.0
88
  finally:
89
  # 无论是否发生异常,都会执行此代码块
90
  print("这是finally块")
91
 
92
 
93
  # 推理
94
+ # def infer2(url):
95
+ # # image_real = Image.open(requests.get(img_urls[0], stream=True).raw).convert("RGB")
96
+ # image = Image.open(requests.get(url, stream=True).raw).convert("RGB")
97
+ # inputs = processor(image, return_tensors="pt").to(DEVICE)
98
+ # outputs = model(**inputs)
99
+ # return outputs.pooler_output
100
 
101
 
102
  # 推理
103
+ # def infer1(image1, image2):
104
+ # try:
105
+ # embed_real = infer2(image1)
106
+ # embed_gen = infer2(image2)
107
+ # similarity_score = cosine_similarity(embed_real, embed_gen, dim=1)
108
+ # print(similarity_score)
109
+ # # 如果你想在CPU上操作这个值,你需要先将tensor移动到CPU
110
+ # t_cpu = similarity_score.cpu()
111
+ #
112
+ # # 然后提取这个值
113
+ # return t_cpu.item()
114
+ #
115
+ # except Exception as e:
116
+ # print(f"发生了一个错误: {e}")
117
+ # finally:
118
+ # # 无论是否发生异常,都会执行此代码块
119
+ # print("这是finally块")