Open In App

How to Read a JPEG or PNG Image in PyTorch

Last Updated : 03 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads