Skip to content
Related Articles

Related Articles

How to Read a JPEG or PNG Image in PyTorch

Improve Article
Save Article
  • Last Updated : 03 Jun, 2022
Improve Article
Save Article

In this article, we are going to discuss how to Read a JPEG or PNG Image using PyTorch in Python.

image_read() method

In PyTorch, the image_read() method is used to read an image as input and return a tensor of size [C, H, W], where C represents a number of channels and H, W represents height and width respectively. The below syntax is used to read a JPEG or PNG image in PyTorch.

Syntax:  torchvision.io.read_image(p)

Parameter:

  • p: This is image path with image name.

Return: This method return a tensor of size [C, H, W].

The below image is used for demonstration:

 

Example 1:

The following program is to understand how to read jpg images.

Python3




# Import required libraries
import torch
import torchvision
from torchvision.io import read_image
import torchvision.transforms as T
  
# read the jpg image
pic = read_image('img.jpg')
  
# convert this torch tensor to PIL image 
PIL_img = T.ToPILImage()(pic)
  
# display result
PIL_img.show()


Output:

How to Read a JPEG or PNG Image in PyTorch

 

Example 2:

The following program is to understand how to read png images.

Python3




# Import required libraries
import torch
import torchvision
from torchvision.io import read_image
import torchvision.transforms as T
  
# read the png image
pic = read_image('img.png')
  
# convert this torch tensor to PIL image 
PIL_img = T.ToPILImage()(pic)
  
# display result
PIL_img.show()


Output:

How to Read a JPEG or PNG Image in PyTorch

 


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!