Skip to content

Instantly share code, notes, and snippets.

@doron2402
Created October 1, 2020 20:43

Revisions

  1. doron2402 created this gist Oct 1, 2020.
    30 changes: 30 additions & 0 deletions opencv_deep_learning_vision_caffe.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,30 @@
    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()