前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Demo:用PyTorch Hub几行代码体验对象分割

Demo:用PyTorch Hub几行代码体验对象分割

作者头像
深度学习与Python
发布2019-07-10 11:25:55
1.1K0
发布2019-07-10 11:25:55
举报
文章被收录于专栏:深度学习与python

喜欢就点关注吧!

使用PyTorch Hub只需一行代码即可导入需要的模型,PyTorch Hub是一个简易API和工作流程,为复现研究提供了基本构建模块,包含预训练模型库。

代码语言:javascript
复制
import torch
model = torch.hub.load('pytorch/vision', 'deeplabv3_resnet101', pretrained=True)
model.eval()

从网站加载图片

代码语言:javascript
复制
# Download an example image from the pytorch website
import urllib
url, filename = ("https://github.com/pytorch/hub/raw/master/dog.jpg", "dog.jpg")
try: urllib.URLopener().retrieve(url, filename)
except: urllib.request.urlretrieve(url, filename)

对图片进行预处理。在PyTorch Hub中所有预先训练的模型都期望输入图像归一化成相同的格式,即小批量的3通道RGB形状图像(N,3,H,W),其中N是图像的数量,H并且W预期至少是224像素。必须将图像加载到一定范围内[0,1],然后使用mean=[0.485,0.456,0.406] 和标准化std =[0.229,0.224,0.225]。

代码语言:javascript
复制
# sample execution (requires torchvision)
from PIL import Image
from torchvision import transforms
input_image = Image.open(filename)
preprocess = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])

input_tensor = preprocess(input_image)
input_batch = input_tensor.unsqueeze(0) # create a mini-batch as expected by the model

# move the input and model to GPU for speed if available
if torch.cuda.is_available():
    input_batch = input_batch.to('cuda')
    model.to('cuda')

with torch.no_grad():
    output = model(input_batch)['out'][0]
output_predictions = output.argmax(0)

这里的输出是形状的(21, H, W),并且在每个位置处存在对应于每个类的预测的非标准化概率。要获得每个类的最大预测概率,然后对不同类别用不同颜色显示。

代码语言:javascript
复制
# create a color pallette, selecting a color for each class
palette = torch.tensor([2 ** 25 - 1, 2 ** 15 - 1, 2 ** 21 - 1])
colors = torch.as_tensor([i for i in range(21)])[:, None] * palette
colors = (colors % 255).numpy().astype("uint8")

# plot the semantic segmentation predictions of 21 classes in each color
r = Image.fromarray(output_predictions.byte().cpu().numpy()).resize(input_image.size)
r.putpalette(colors)

import matplotlib.pyplot as plt
plt.imshow(r)
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2019-06-29,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 深度学习与python 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档