In many times, it is necessary to process images using both OpenCV and PyTorch. To achieve this, we need to convert OpenCV image to PyTorch tensor, which is the fundamental data structure used in PyTorch. Luckily, this conversion process is straightforward. This tutorial shows how to do that using Python.
Prepare environment
- Install the following packages using
pip
:
pip install torch torchvision
pip install opencv-python
Code
In the following code, we read the image using OpenCV. It uses the BGR color space as its default color format for images. On the other hand, PyTorch uses the RGB color space. Therefore, we're converting the color space from BGR to RGB. In OpenCV, images are represented as NumPy arrays. So finally, we convert the NumPy array to a PyTorch tensor. That's it, now tensor can be used in PyTorch for further processing tasks.
import cv2
import torchvision.transforms as transforms
cvImg = cv2.imread('test.jpg')
cvImg = cv2.cvtColor(cvImg, cv2.COLOR_BGR2RGB)
tensorImg = transforms.ToTensor()(cvImg)
Leave a Comment
Cancel reply