<jupyter_start><jupyter_text><jupyter_code>from torchvision import models, datasets, transforms
from torch.utils.data import DataLoader
import json
import numpy as np
from PIL import Image
from matplotlib.pyplot import imshow
%matplotlib inline

# Download sample image
! wget -O "/content/bike.jpg" https://github.com/Gan4x4/CV-HSE2019/raw/master/data/2bikes.jpeg

# Store it in Pillow format and show it
pil_image = Image.open("/content/bike.jpg")
imshow(pil_image)

# Download ImageNet labels file
! wget -O labels.json https://s3.amazonaws.com/deep-learning-models/image-models/imagenet_class_index.json
with open("labels.json") as json_file:
    labels = json.load(json_file)

# Load GoogeNet pretrained on ImageNet
model = models.googlenet(pretrained = True)
# Classify image

transform=transforms.Compose([transforms.ToTensor()])
tensor_image = transform(pil_image)
tensor_image =tensor_image.unsqueeze(0)

# Switch model to evalution mode
model.eval()

# Run model
output = model(tensor_image)

# Display Top 5 class names
top_class_indexes = np.argsort(output[0].detach().numpy())[-5:]
for i in np.flip(top_class_indexes):
  print (labels[str(i)][1])
# OpenCV vs Pillow
import cv2
import matplotlib.pyplot as plt
plt.figure()

# Open CV image store colors in BGR 
opencv_image = cv2.imread("/content/bike.jpg") 
plt.imshow(pil_image)
print ("Pillow", np.array(pil_image).shape,'RGB',np.array(pil_image).dtype)
plt.show()
plt.imshow(opencv_image)
print ("OpenCV",opencv_image.shape,'BGR')
plt.show()
opencv_image_rgb = cv2.cvtColor(opencv_image, cv2.COLOR_BGR2RGB)
plt.imshow(opencv_image_rgb)
plt.show()

#Imshow for Tensor
def tensor_show(inp, title=None):
    inp = inp.numpy().transpose((1, 2, 0))
    plt.imshow(inp)
    if title is not None:
        plt.title(title)
    plt.pause(0.001) 

print("Pytorch tensor",tensor_image.shape,tensor_image.dtype)<jupyter_output>Pillow (640, 960, 3) RGB uint8
{'fraction_non_alphanumeric': 0.12401883830455258, 'fraction_numerical': 0.01726844583987441, 'mean_word_length': 5.503401360544218, 'pattern_counts': {'":': 0, '<': 4, '<?xml version=': 0, '>': 4, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '464351', 'license': 'MIT', 'n_tokens_mistral': 735, 'n_tokens_neox': 709, 'n_words': 154, 'path': 'helloworld/HelloWorld.ipynb', 'repo_name': 'Gan4x4/hse-cv2019', 'size': '1911'}