# -*- coding: utf-8 -*- ''' resnet18 用imagenet预训练好的模型 提取fc之前的特征 仅输出数据''' import os.path import torch import torch.nn as nn from torchvision import models, transforms from torch.autograd import Variable import numpy as np from PIL import Image import warnings warnings.filterwarnings("ignore") features_dir = 'D:/' img_path = "./A.jpg" file_name = img_path.split('/')[-1] feature_path = os.path.join(features_dir, file_name + '.txt') print(feature_path) transform1 = transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor()] ) img = Image.open(img_path) img1 = transform1(img) # print(img1) resnet18_feature_extractor = models.resnet18(pretrained=False) resnet18_feature_extractor.load_state_dict(torch.load('./resnet18-f37072fd.pth')) resnet18_feature_extractor.fc = nn.Linear(512, 512) torch.nn.init.eye(resnet18_feature_
resnet18 用imagenet预训练好的模型 提取fc之前的特征 仅输出数据
最新推荐文章于 2024-07-22 10:17:38 发布
该博客介绍了如何利用Python和torch库,通过预训练的ResNet18模型提取图像在全连接层前的特征,并将这些特征保存到文件中。首先,对图像进行预处理,然后加载预训练模型并替换其全连接层,接着对图像进行前向传播,得到特征向量,最后将特征向量保存为CSV文件。
摘要由CSDN通过智能技术生成