Path: blob/master/Deep-Learning-with-OpenCV-DNN-Module/python/classification/classify.py
3150 views
import cv21import numpy as np23# read the ImageNet class names4with open('../../input/classification_classes_ILSVRC2012.txt', 'r') as f:5image_net_names = f.read().split('\n')6# final class names (just the first word of the many ImageNet names for one image)7class_names = [name.split(',')[0] for name in image_net_names]89# load the neural network model10model = cv2.dnn.readNet(model='../../input/DenseNet_121.caffemodel',11config='../../input/DenseNet_121.prototxt',12framework='Caffe')1314# load the image from disk15image = cv2.imread('../../input/image_1.jpg')16# create blob from image17blob = cv2.dnn.blobFromImage(image=image, scalefactor=0.01, size=(224, 224),18mean=(104, 117, 123))19# set the input blob for the neural network20model.setInput(blob)21# forward pass image blog through the model22outputs = model.forward()2324final_outputs = outputs[0]25# make all the outputs 1D26final_outputs = final_outputs.reshape(1000, 1)27# get the class label28label_id = np.argmax(final_outputs)29# convert the output scores to softmax probabilities30probs = np.exp(final_outputs) / np.sum(np.exp(final_outputs))31# get the final highest probability32final_prob = np.max(probs) * 100.33# map the max confidence to the class label names34out_name = class_names[label_id]35out_text = f"{out_name}, {final_prob:.3f}"3637# put the class name text on top of the image38cv2.putText(image, out_text, (25, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0),392)40cv2.imshow('Image', image)41cv2.waitKey(0)42cv2.imwrite('../../outputs/result_image.jpg', image)434445