Skip to content
Snippets Groups Projects
Commit a1ec10bb authored by Jeppe Gade's avatar Jeppe Gade
Browse files

New stuff

parent efe30f45
No related branches found
No related tags found
No related merge requests found
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchsummary import summary
import requests
from PIL import Image
from io import BytesIO
from torchvision import transforms
import numpy as np
import pandas as pd
import os
#from pycocotools.coco import COCO
import skimage.io as io
import matplotlib.pyplot as plt
from pathlib import Path
from coco_utils import get_image
model = torch.hub.load('pytorch/vision:v0.10.0', 'mobilenet_v2', pretrained=True)
#Enable following to only get CNN part:
model = torch.nn.Sequential(*(list(model.children())[:-1]))
model.eval()
from PIL import Image
from torchvision import transforms
input_image = get_image("http://images.cocodataset.org/val2017/000000148783.jpg")
preprocess = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
transforms.Resize(256),
transforms.CenterCrop(224),
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():
#Outputs mini-batch that can be input to model
def preprocessImage(image):
input_tensor = preprocess(input_image)
return input_tensor.unsqueeze(0) # create a mini-batch as expected by the model
#Runs the CNN on input
def runCNN(image):
input_batch = preprocessImage(image)
if torch.cuda.is_available():
input_batch = input_batch.to('cuda')
model.to('cuda')
with torch.no_grad():
return model(input_batch)
with torch.no_grad():
output = model(input_batch)
# Tensor of shape 1000, with confidence scores over Imagenet's 1000 classes
# print(output[0])
import numpy as np
# # The output has unnormalized scores. To get probabilities, you can run a softmax on it.
probabilities = torch.nn.functional.softmax(output[0], dim=0)
# print(probabilities)
a = np.argmax(probabilities)
print(a)
print(probabilities[a])
\ No newline at end of file
if __name__=="__main__":
#Run entire thing
input_image = get_image("http://images.cocodataset.org/val2017/000000148783.jpg")
output = runCNN(input_image)
output.shape
#Shape of output:
#torch.Size([1, 1280, 7, 7])
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment