Friday, December 27, 2024
Google search engine
HomeLanguagesHow to Read a JPEG or PNG Image in PyTorch

How to Read a JPEG or PNG Image in PyTorch

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

 

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments