Preprocessing images and inference in convolutional networks
We train artificial neural networks for application in our tasks. Here, some conditions arise. Firstly, we need to prepare input data in the format and range that our network can handle. Secondly, we need to pass our data to the network properly. OpenCV helps us to perform both steps, and in this recipe we examine how to use OpenCV's dnn
module to easily convert an image to a tensor and perform an inference.
Getting ready
Before you proceed with this recipe, you need to install the OpenCV 3.3.1 (or higher) Python API package.
How to do it...
For this recipe, you need to complete the following steps:
- Import the modules we're going to use:
import cv2 import numpy as np
- Open an input image, preprocess it, and convert it to a tensor:
image = cv2.imread('../data/Lena.png', cv2.IMREAD_COLOR) tensor = cv2.dnn.blobFromImage(image, 1.0, (224, 224), (104, 117, 123), False, False);
- Convert two images to tensors with...