chanhua commited on
Commit
8589cca
1 Parent(s): b688840

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +1 -1
  2. image_feature.py +23 -15
app.py CHANGED
@@ -3,7 +3,7 @@ import image_feature as func
3
 
4
 
5
  def work11(image1, image2):
6
- return func.xiang(image1)
7
  # return func.infer1(image1, image2)
8
  # return func.infer4(image1, image2)
9
 
 
3
 
4
 
5
  def work11(image1, image2):
6
+ return func.similarity_cpu(image1, image2)
7
  # return func.infer1(image1, image2)
8
  # return func.infer4(image1, image2)
9
 
image_feature.py CHANGED
@@ -141,23 +141,17 @@ def infer1(image1, image2):
141
  print("这是finally块")
142
 
143
  # 输出图片向量
144
- def xiang(upload_image):
145
  try:
 
 
 
 
 
 
146
 
147
- image = upload_image.convert('RGB')
148
-
149
- # processor = AutoImageProcessor.from_pretrained('facebook/dinov2-giant')
150
- # model = AutoModel.from_pretrained('facebook/dinov2-giant')
151
-
152
- processor = AutoImageProcessor.from_pretrained('google/vit-large-patch16-224-in21k')
153
- model = ViTModel.from_pretrained('google/vit-large-patch16-224-in21k')
154
-
155
- inputs = processor(images=image, return_tensors="pt").to(DEVICE)
156
- outputs = model(**inputs)
157
- # last_hidden_states = outputs.last_hidden_state
158
-
159
- return outputs.last_hidden_state
160
-
161
  except Exception as e:
162
  print(f"发生了一个错误: {e}")
163
  return '异常'+ str(e)
@@ -166,3 +160,17 @@ def xiang(upload_image):
166
  print("这是finally块")
167
 
168
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
141
  print("这是finally块")
142
 
143
  # 输出图片向量
144
+ def similarity_cpu(image1, image2):
145
  try:
146
+ embed_real = xl_infer(image1)
147
+ embed_gen = xl_infer(image2)
148
+ similarity_score = cosine_similarity(embed_real, embed_gen, dim=1)
149
+ print(similarity_score)
150
+ # 如果你想在CPU上操作这个值,你需要先将tensor移动到CPU
151
+ t_cpu = similarity_score.cpu()
152
 
153
+ # 然后提取这个值
154
+ return t_cpu.item()
 
 
 
 
 
 
 
 
 
 
 
 
155
  except Exception as e:
156
  print(f"发生了一个错误: {e}")
157
  return '异常'+ str(e)
 
160
  print("这是finally块")
161
 
162
 
163
+ # 推理
164
+ def xl_infer(url):
165
+ image = url.convert('RGB')
166
+
167
+ # processor = AutoImageProcessor.from_pretrained('facebook/dinov2-giant')
168
+ # model = AutoModel.from_pretrained('facebook/dinov2-giant')
169
+
170
+ processor = AutoImageProcessor.from_pretrained('google/vit-large-patch16-224-in21k')
171
+ # model = ViTModel.from_pretrained('google/vit-large-patch16-224-in21k')
172
+ model = AutoModel.from_pretrained('google/vit-large-patch16-224-in21k')
173
+
174
+ inputs = processor(images=image, return_tensors="pt").to(DEVICE)
175
+ outputs = model(**inputs)
176
+ return outputs.pooler_output