Get image from webcam and load into pytorch


I’m doing a project with pytorch and I need to get a single image and pass to my CNN.
I already have the code working to get the image from my webcam. My CNN is trained and now I need to pass my image to the CNN.

Is that possible with some custom Dataset? Anyone has some tip to give me about that?

Usually, you just take the image )say as numpy array from OpenCV), convert to a tensor and unsqueeze the batch dimension. You need to apply the same transformations, for OpenCV you might also have to shuffle the channels BGR->RGB.

Best regards


Thank you!
I will try that!

in kornia we have this handy function for that:

import cv2
import kornia
import torch
import numpy as np

def load_opencv_img(img_path: str) -> torch.Tensor:
    img: np.ndarray = cv2.imread(img_path, cv2.IMREAD_COLOR)  # HxWx3
    img_t: torch.Tensor = kornia.image_to_tensor(img)  # 1xCxHxW
    img_t = kornia.bgr_to_grayscale(img_t)  # Bx1xHxW
    return img_t