Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hackassin
GitHub Repository: hackassin/learnopencv
Path: blob/master/Deep-Learning-with-OpenCV-DNN-Module/python/classification/classify.py
3150 views
1
import cv2
2
import numpy as np
3
4
# read the ImageNet class names
5
with open('../../input/classification_classes_ILSVRC2012.txt', 'r') as f:
6
image_net_names = f.read().split('\n')
7
# final class names (just the first word of the many ImageNet names for one image)
8
class_names = [name.split(',')[0] for name in image_net_names]
9
10
# load the neural network model
11
model = cv2.dnn.readNet(model='../../input/DenseNet_121.caffemodel',
12
config='../../input/DenseNet_121.prototxt',
13
framework='Caffe')
14
15
# load the image from disk
16
image = cv2.imread('../../input/image_1.jpg')
17
# create blob from image
18
blob = cv2.dnn.blobFromImage(image=image, scalefactor=0.01, size=(224, 224),
19
mean=(104, 117, 123))
20
# set the input blob for the neural network
21
model.setInput(blob)
22
# forward pass image blog through the model
23
outputs = model.forward()
24
25
final_outputs = outputs[0]
26
# make all the outputs 1D
27
final_outputs = final_outputs.reshape(1000, 1)
28
# get the class label
29
label_id = np.argmax(final_outputs)
30
# convert the output scores to softmax probabilities
31
probs = np.exp(final_outputs) / np.sum(np.exp(final_outputs))
32
# get the final highest probability
33
final_prob = np.max(probs) * 100.
34
# map the max confidence to the class label names
35
out_name = class_names[label_id]
36
out_text = f"{out_name}, {final_prob:.3f}"
37
38
# put the class name text on top of the image
39
cv2.putText(image, out_text, (25, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0),
40
2)
41
cv2.imshow('Image', image)
42
cv2.waitKey(0)
43
cv2.imwrite('../../outputs/result_image.jpg', image)
44
45