当前位置: 首页 > backend >正文

将.pt文件执行图像比对

目录

1. 加载模型

2. 图像预处理

3. 提取图像特征

4. 计算相似度

 调用API或封装函数即可实现端到端比对


使用.pt文件进行图像比对通常涉及以下步骤:


1. 加载模型

python

import torch# 假设模型是PyTorch保存的权重文件
model = YourModelClass()  # 需与保存时的模型结构一致
model.load_state_dict(torch.load('model.pt'))
model.eval()  # 切换到推理模式

2. 图像预处理

使用torchvision.transforms标准化输入:

python

from torchvision import transformspreprocess = transforms.Compose([transforms.Resize((224, 224)),  # 根据模型要求调整尺寸transforms.ToTensor(),transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])  # ImageNet标准化
])

3. 提取图像特征

将图像输入模型,获取特征向量:

python

from PIL import Imagedef get_features(image_path):img = Image.open(image_path).convert('RGB')img_tensor = preprocess(img).unsqueeze(0)  # 添加batch维度with torch.no_grad():features = model(img_tensor)  # 假设模型输出特征向量return features.squeeze()  # 去除batch维度

4. 计算相似度

使用余弦相似度或欧氏距离:

python

import torch.nn.functional as F# 假设features1和features2是两张图的特征向量
cos_sim = F.cosine_similarity(features1, features2, dim=0)  # 值越接近1越相似
euclidean_dist = torch.norm(features1 - features2, p=2)    # 值越小越相似

 调用API或封装函数即可实现端到端比对

 

# 端到端图像比对函数封装
import torch
import torch.nn.functional as F
from torchvision import transforms
from PIL import Imageclass ImageComparator:def __init__(self, model_path, device='cpu'):self.device = torch.device(device)self.model = torch.load(model_path, map_location=device)self.model.eval()self.preprocess = transforms.Compose([transforms.Resize(256),transforms.CenterCrop(224),transforms.ToTensor(),transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])def extract_features(self, img_path):img = Image.open(img_path).convert('RGB')return self.model(self.preprocess(img).unsqueeze(0).to(self.device))[0]def compare(self, img1_path, img2_path):with torch.no_grad():f1, f2 = self.extract_features(img1_path), self.extract_features(img2_path)return F.cosine_similarity(f1, f2, dim=0).item()# 使用示例
comparator = ImageComparator('model.pt', device='cuda' if torch.cuda.is_available() else 'cpu')
similarity = comparator.compare('img1.jpg', 'img2.jpg')
print(f"Similarity Score: {similarity:.4f}")

http://www.xdnf.cn/news/6451.html

相关文章:

  • Java详解RabbitMQ工作模式之发布订阅模式
  • 具备AI功能的银河麒麟桌面操作系统已正式上市
  • 手搓传染病模型(SEI - SEIAR )
  • xp_cmdshell bcp 导出文件
  • 道通龙鱼系列-混合翼无人机:垂直起降+长时续航
  • 嵌入式自学第二十二天(5.15)
  • 02、基础入门-Spring生态圈
  • 云上玩转 Qwen3 系列之三:PAI-LangStudio x Hologres构建ChatBI数据分析Agent应用
  • 机器学习第十三讲:独热编码 → 把“红黄蓝“颜色变成001/010/100的数字格式
  • 数据结构之图的应用场景及其代码
  • MySQL 用户权限管理:从入门到精通
  • 26考研 | 王道 | 计算机组成原理 | 一、计算机系统概述
  • Java:跨越时代的编程语言传奇
  • 2025年黑客扫段攻击激增:如何构建智能防御体系保障业务安全?
  • Makefile与CMake
  • AI大模型应用:17个实用场景解锁未来
  • 软件设计师考试《综合知识》CPU考点分析(2019-2023年)——求三连
  • 让AI帮我写一个word转pdf的工具
  • 从《西游记》到微调大模型:一场“幻觉”与“认知”的对话20250515
  • 在 VMware 中挂载 U 盘并格式化为 ext4 文件系统的完整指南
  • 企业在蓝海市场有哪些推进目标?
  • 操作系统学习笔记第3章 内存管理(灰灰题库)
  • 嵌入式学习--江科大51单片机day7
  • Metagloves Pro+Manus Core:一套组合拳打通虚拟制作与现实工业的任督二脉
  • 题海拾贝:P4017 最大食物链计数
  • 399. 除法求值
  • 自然资源和空间数据应用平台
  • 深度学习框架---TensorFlow概览
  • 【vue】【环境配置】项目无法npm run serve,显示node版本过低
  • 【2025最新】VSCode Cline插件配置教程:免费使用Claude 3.7提升编程效率