Skip to content

Instantly share code, notes, and snippets.

@doron2402
Created October 1, 2020 20:43
Show Gist options
  • Save doron2402/2ee320c65445f89173a67156f4a8ed42 to your computer and use it in GitHub Desktop.
Save doron2402/2ee320c65445f89173a67156f4a8ed42 to your computer and use it in GitHub Desktop.
OpenCV Deep Learning Vision using Caffe
import numpy as np
import cv2
IMAGE_TO_PROCESS = 'image.png'
TXT_BASED_CLASSIFICATION = 'words.txt'
def get_txt_data(file):
rows = open(file).read().strip().split('\n')
return rows
img = cv2.imread(IMAGE_TO_PROCESS)
rows = get_txt_data(TXT_BASED_CLASSIFICATION)
classes = [r[r.find(' ') + 1:] for r in rows]
net = cv2.dnn.readNetFromCaffe('./FILE.prototxt','./MODEL.caffemodel')
blob = cv2.dnn.blobFromImage(img, 1, (224,224))
net.setInput(blob)
output = net.forward()
# Get last 10 images
idx = np.argsort(outp[0])[::-1][:10]
# Print Probability
for (i,id) in enumerate(idx):
print(f'{i+1} {classes[id]} ({id}): Probability {output[0][id]*100}')
# If you would like to show the image uncomment the lines below
# cv2.imshow('Image', img)
## Wait for key before exiting
# cv2.waitKey(0)
## Make sure to destroy the windows at the end
# cv2.destroyAllWindows()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment