torchvision tensor conversion & preprocessing
This sample converts an image captured from the INFINICAM GbE-2 into a tensor (the multi-dimensional array used by PyTorch) for the AI library PyTorch, and uses torchvision for preprocessing (resizing and blurring). This is the entry point for feeding camera images into AI models such as image recognition.
-
Install PyTorch and torchvision
PyTorch is a large library (about 130 MB), so it is not in the
requirements.txtof the sample code bundle. Install it only if you need it, with this one line.Terminal window python -m pip install --only-binary=:all: torch torchvision --extra-index-url https://download.pytorch.org/whl/cpuIf it ends with
Successfully installed ... torch-... torchvision-..., it worked. -
Enter and save the program
Save the following code as
torchvision_process.pyinC:\infinicam_projects\python.import torchfrom torchvision.transforms import v2from torchvision.utils import save_imagefrom pypuclib import CameraFactory, PUCExceptionprint("Connecting to the camera...")try:# Connect to the GbE-2 at this IP addresscam = CameraFactory().create(ip="192.168.0.10")except PUCException as e:print("Error: could not connect to the camera.", e)raise SystemExit(1)try:# Receive one frame of compressed data and decode it into an image (a NumPy array)image = cam.decoder().decode(cam.grab())finally:cam.close()# Convert the NumPy array to a PyTorch tensor (shape: color x height x width)if image.ndim == 2:# Monochrome: (height, width) -> (1, height, width)tensor = torch.from_numpy(image).unsqueeze(0)else:# Color: swap BGR to RGB, then (height, width, 3) -> (3, height, width)tensor = torch.from_numpy(image[:, :, ::-1].copy()).permute(2, 0, 1)# Turn integers from 0 to 255 into decimals from 0.0 to 1.0tensor = tensor.float() / 255.0print("Converted tensor:", list(tensor.shape), tensor.dtype,f"(value range {tensor.min():.2f} to {tensor.max():.2f})")# Define the processing done before the image goes into an AI model (preprocessing)preprocess = v2.Compose([v2.Resize((224, 224), antialias=True), # Shrink to 224 x 224v2.GaussianBlur(kernel_size=5, sigma=1.0), # Blur slightly to reduce noise])processed = preprocess(tensor)print("Tensor after preprocessing:", list(processed.shape))# Models usually take a batch of images (number of images x color x height x width)batch = processed.unsqueeze(0)print("Shape passed to the model:", list(batch.shape))# Save the preprocessed image so you can check it by eyesave_image(processed, "torch_processed.png")print("Saved: torch_processed.png") -
Run it
Run the following 2 lines, one at a time, in Command Prompt (or PowerShell).
Terminal window cd C:\infinicam_projects\pythonTerminal window python torchvision_process.pyIf you see output like the following and a 224 × 224 image
torch_processed.pngis created, it worked (the value range depends on how bright the scene is).Connecting to the camera...Converted tensor: [1, 600, 800] torch.float32 (value range 0.38 to 1.00)Tensor after preprocessing: [1, 224, 224]Shape passed to the model: [1, 1, 224, 224]Saved: torch_processed.png
How the program works
Section titled “How the program works”1. Convert a NumPy array to a tensor
Section titled “1. Convert a NumPy array to a tensor”tensor = torch.from_numpy(image).unsqueeze(0)torch.from_numpy()converts a NumPy array into a PyTorch tensor. It does not copy the contents, so the conversion is instant.- PyTorch handles images in the shape “color x height x width”. A monochrome image is “height x width”, so
unsqueeze(0)adds a “color” dimension (of size 1) at the front. - A color image is “height x width x color”, so
permute(2, 0, 1)reorders it to “color x height x width”. Before that,[:, :, ::-1]swaps the color order from BGR to RGB (most PyTorch models expect RGB).
2. Turn values into decimals from 0.0 to 1.0
Section titled “2. Turn values into decimals from 0.0 to 1.0”tensor = tensor.float() / 255.0Most AI models take pixel values as decimals from 0.0 to 1.0. float() turns the values into decimals, which are then divided by 255.
3. Chain the preprocessing (Compose)
Section titled “3. Chain the preprocessing (Compose)”preprocess = v2.Compose([ v2.Resize((224, 224), antialias=True), v2.GaussianBlur(kernel_size=5, sigma=1.0),])When you list steps in v2.Compose, a single line, preprocess(tensor), runs all of them in order from the top.
| Step | What it does |
|---|---|
v2.Resize((224, 224)) |
Shrinks the image to 224 × 224. Many well-known image recognition models take images of this size |
v2.GaussianBlur(...) |
Blurs slightly to reduce fine noise |
4. Shape it for the model
Section titled “4. Shape it for the model”batch = processed.unsqueeze(0)AI models are built to process several images at once (a batch). Even for a single image, you add an “number of images” dimension at the front to make it “number of images x color x height x width” before passing it in.
