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

将.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}")

相关文章:

  • 赛博放生:用数字技术重构心灵仪式
  • 跨系统数据烟囱如何破局?豪森智源HSMES重构制造协同新范式‌
  • AI全域智能监控系统重构商业清洁管理范式——从被动响应到主动预防的监控效能革命
  • 数据科学和机器学习的“看家兵器”——pandas模块 之四
  • 上线前测试组发现问题较多。开发总结
  • 数控机床控制单元技术方案:基于EFISH-SCB-RK3588/SAIL-RK3588的赛扬N100/N150国产化替代全场景解析
  • c++从入门到精通(四)--动态内存,模板与泛型编程
  • 小白入门:GitHub 远程仓库使用全攻略
  • 印度全印度游戏联合会(AIGF)介绍与用途
  • 基于YOLOv5的葡萄病害智能识别系统开发实践
  • JSX语法介绍
  • Java并发编程面试题总结
  • 面向对象编程 接口vs抽象类的区别?
  • 如何快速入门-衡石科技分析平台
  • (十九)Java集合框架深度解析:从基础到高级应用
  • 第28周——InceptionV1实现猴痘识别
  • K8S Gateway AB测试、蓝绿发布、金丝雀(灰度)发布
  • next.js实现项目搭建
  • 023-C语言预处理详解
  • 致远OA周报日报管理应用包【附百度网盘下载链接,官方售价8K】
  • 网站专题模板下载/网络营销网站推广
  • 高端网站建设服务/查网站权重
  • 昌吉做58网站的/广告推广平台
  • 360做的网站首页/小黄豆crm
  • 强企网做网站/网上营销新观察网
  • flash手机网站制作/前端seo搜索引擎优化