pytroch ,cv2,PIL,读取图片以及通道转换

            img = Image.open(os.path.join('data',image_name))
            img = img.resize((112, 112), Image.BILINEAR)
            img = np.array(img, dtype=np.float32) # img:(h,w,3) RGB
            img = img[:, :, ::-1] # img: (h,w,3) BGR
            img -= np.array((104, 117, 123)) #  BGR
            img = img.transpose((2, 0, 1)) # img:(3,h,w)
            img = img.reshape((1, )+img.shape) #增加一维chw,nchw   
            torch.from_numpy


################################################
        image_path = "test.jpg"
        img_raw = cv2.imread(image_path, cv2.IMREAD_COLOR) #bgr
        #img_cv = cv2.cvtColor(img_cv, cv2.COLOR_BGR2RGB) #rgb
        img = np.float32(img_raw)
        im_height, im_width, _ = img.shape
        scale = torch.Tensor([img.shape[1], img.shape[0], img.shape[1], img.shape[0]])
        img -= (104, 117, 123)  #bgr
        img = img.transpose(2, 0, 1) #hwc chw
        img = torch.from_numpy(img).unsqueeze(0) #chw  to nchw

在这里插入图片描述在这里插入图片描述

#-*-coding: UTF-8 -*-
import torch
from PIL import Image
from torchvision import transforms
import cv2
import numpy as np
device = torch.device('cuda')
transform=transforms.Compose([
            transforms.Resize(224),
            # transforms.CenterCrop(224),
            transforms.ToTensor(),
            transforms.Normalize(mean=[0.485,0.456,0.406],
                                 std=[0.229,0.224,0.225])
                            ])
def prediect():
    img_path ="868.jpg" 
    model = torch.load("model.pth") 
    model.eval()  #必须加评估
    device = torch.device('cuda')
    net=model
    net = net.cuda()#=net.to(device) 转移到CUDA上
    torch.no_grad()
    img=Image.open(img_path)
    img=transform(img).unsqueeze(0) #tensor nchw 0-1
    img_ = img.cuda()#img.to(device) 转移到CUDA上
    outputs = net(img_)
    _, predicted = torch.max(outputs, 1) #返回一维数组
    print (predicted.shape)  #tensor([0], device='cuda:0'))
    print (predicted[0].cpu()) #cuda tensor 变成 cpu tensor
    print (predicted[0].item()) #一个,tensor,值直接取得元素

发布了112 篇原创文章 · 获赞 150 · 访问量 29万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览