pytorch保存一张图的所有特征图

  • 需要先了解所用网络的结构
import torch.nn as nn
import torch

class Simple(nn.Module):
	def __init__(self):
		super().__init__()
		self.feature = nn.Sequential(
			nn.Conv2d(3, 16, 3, 1, 1, bias=True),
			nn.MaxPool2d(2),
			nn.Conv2d(16, 32, 3, 1, 1, bias=True),
			nn.MaxPool2d(2),
			nn.Conv2d(32, 64, 3, 1, 1, bias=True),
			nn.MaxPool2d(2),
			nn.Conv2d(64, 128, 3, 1, 1, bias=True),
			nn.MaxPool2d(2),
			nn.Conv2d(128, 256, 3, 1, 1, bias=True),
			nn.MaxPool2d(2),
			nn.Conv2d(256, 512, 3, 1, 1, bias=True)
		)
		self.fc = nn.Sequential(
			nn.Linear(512*16, 1000),
			nn.ReLU(),
			nn.Linear(1000, 100),
			nn.ReLU(),
			nn.Linear(100, 6)
		)
		
	def forward(self, x):
		f = self.feature(x)
		f = f.view(-1, 512*16)
		return self.fc(f)
  • 加载模型,预处理图片,记得要保证存储目录存在哦~
net=Simple()
paras=torch.load('', map_location='cuda')
net.load_state_dict(paras)
net.cuda().eval()
raw = cv2.imread('')
im = cv2.resize(raw, (150, 150))
im = im / 255.0
im = np.transpose(im, (2,0,1))
im = im.reshape(1,3,150,150)
im = torch.from_numpy(im).float().cuda()
for ch in net.feature.children():
		im = ch(im)
		b, c, h, w = im.shape
		for ci in range(c):
			fm = im[0][ci]
			ma = torch.max(fm)
			mi = torch.min(fm)
			fm = 255 * (fm - mi) / (ma - mi)
			fm = fm.cpu().detach().numpy().astype('uint8')
			fm = fm.reshape(h, w, 1)
			cv2.imwrite('log/feature/{}-{}.jpg'.format(h, ci), fm)
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

刀么克瑟拉莫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值