How to Read a JPEG or PNG Image in PyTorch
Last Updated :
03 Jun, 2022
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 torch
import torchvision
from torchvision.io import read_image
import torchvision.transforms as T
pic = read_image( 'img.jpg' )
PIL_img = T.ToPILImage()(pic)
PIL_img.show()
|
Output:
Example 2:
The following program is to understand how to read png images.
Python3
import torch
import torchvision
from torchvision.io import read_image
import torchvision.transforms as T
pic = read_image( 'img.png' )
PIL_img = T.ToPILImage()(pic)
PIL_img.show()
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...