How to use a pretrained .caffemodel (already installed from a dataset page) and .prototxt file of the trained network architecture for prediction on a single image (for gender classification)?
How to use a pretrained .caffemodel (already installed from a dataset page) and .prototxt file of the trained network architecture for prediction on a single image (for gender classification)?
Caffe models could be run within OpenCV. Besides, you don't have to have Caffe installation on your environment.
Model loading
import cv2
model = cv2.dnn.readNetFromCaffe("x.prototxt", "y.caffemodel")
Resizing inputs
You need to resize your input image to the expected input size of the reference model. This is mentioned in the prototxt file. For example, the following model expects (1, 3, 160, 160) shaped inputs.
input: "data"
input_dim: 1
input_dim: 3
input_dim: 160
input_dim: 160
You can read and resize the image as shown below.
img = cv2.imread("img.jpg")
img = cv2.resize(img , (160, 160)) #this is (160, 160, 3) shaped image
img_blob = cv2.dnn.blobFromImage(img ) #this is (1, 3, 160, 160) shaped image
Prediction
You can pass resized images to the built models now.
model.setInput(img_blob)
output = model.forward()
print(output)
This works even if Caffe is not installed in your environment. OpenCV also wraps torch and tensorflow models as well.